view src/main/java/de/mpiwg/gazetteer/rest/AbstractServletMethod.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.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

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

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import de.mpiwg.web.SessionBean;

public abstract class AbstractServletMethod {
	
	private static Logger LOGGER = Logger.getLogger(AbstractServletMethod.class);

	
	
	protected static void writeError(HttpServletResponse response, String message){
		try {
			JSONObject json = new JSONObject();
			json.put("status", "error");
			json.put("message", message);
			
			PrintWriter out = response.getWriter();
			out.print(json.toString());
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected static Long getQueryLongParam(HttpServletRequest request, String paraName) {
		String value = request.getParameter(paraName);
		if (StringUtils.isNotEmpty(value)) {
			try {
				return Long.parseLong(value);
			} catch (Exception e) {
			}
		}
		return null;
	}
	
	protected static Long getRequestLongPart(HttpServletRequest request, String partName) throws IOException,
			IllegalStateException, ServletException {
		
		String value = getRequestPart(request, partName);
		
		try {
			Long v = Long.parseLong(value);
			return v;
		} catch (Exception e) {
		}
		
		return null;
		
	}

	protected static String getRequestPart(HttpServletRequest request, String partName) throws IOException,
			IllegalStateException, ServletException {

		String partText = null;
		final Part filePart = request.getPart(partName);

		if (filePart != null) {
			OutputStream out = null;
			InputStream filecontent = null;

			try {
				out = new ByteArrayOutputStream();
				filecontent = filePart.getInputStream();

				int read = 0;
				final byte[] bytes = new byte[1024];

				while ((read = filecontent.read(bytes)) != -1) {
					out.write(bytes, 0, read);
				}

				partText = out.toString();

			} catch (FileNotFoundException fne) {
				LOGGER.info("Problems during file upload. Error: " + fne.getMessage());
			} finally {
				if (out != null) {
					out.close();
				}
				if (filecontent != null) {
					filecontent.close();
				}
			}
		}

		return partText;
	}
	
}