view src/main/java/de/mpiwg/gazetteer/rest/SaveNewText.java @ 0:7682c04c63a8

First commit of the source code!
author "jurzua <jurzua@mpiwg-berlin.mpg.de>"
date Tue, 10 Mar 2015 14:50:41 +0100
parents
children
line wrap: on
line source

package de.mpiwg.gazetteer.rest;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.icefaces.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;

import de.mpiwg.gazetteer.bo.LGBranch;
import de.mpiwg.gazetteer.bo.LGFile;
import de.mpiwg.gazetteer.utils.DataProvider;
import de.mpiwg.gazetteer.utils.JSONUtils;
import de.mpiwg.gazetteer.utils.exceptions.GazetteerException;

public class SaveNewText extends AbstractServletMethod{

	public static String name = "saveNew";
	
	public static void execute(HttpServletRequest request, HttpServletResponse response) throws Exception{
		response.setContentType("application/json");
		JSONObject json = new JSONObject();
		
		if (ServletFileUpload.isMultipartContent(request)) {
			String text = getRequestPart(request, "text");
			Long userId = getRequestLongPart(request, "userId");
			Long sectionId = getRequestLongPart(request, "sectionId");
			String label = getRequestPart(request, "label");

			if(StringUtils.isNotEmpty(text) && userId != null && sectionId != null){
				Long branchId = DataProvider.getInstance().saveNewFile(text, label, sectionId, userId);
				LGBranch branch = DataProvider.getInstance().getBranch(branchId);	
				LGFile file = DataProvider.getInstance().getFile(branch.getCurrentLastFileId());
				
				JSONObject jsonBranch = JSONUtils.branch2JSON(branch);
				JSONObject jsonFile = JSONUtils.file2JSON(file, true);
				
				json.put("branch", jsonBranch);
				json.put("file", jsonFile);	
				json.put("status", "ok");
				
			}else{
				json.put("status", "error");
				json.put("message", "Following parameters are mandatory: text, userId, sectionId.");
				json.put("code", GazetteerException.CODE);
			}
			
		} else {
			json.put("status", "error");
			json.put("message", "Content-type wrong. It should be: multipart/form-data");
			json.put("code", GazetteerException.CODE);
		}
		
		
		
		PrintWriter out = response.getWriter();
		out.print(json.toString());
		out.flush();
	}
	
}