package yanagishima.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import yanagishima.service.PrestoService;

@Singleton
public class PrestoServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private final PrestoService prestoService;

	@Inject
	public PrestoServlet(PrestoService prestoService) {
		this.prestoService = prestoService;
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HashMap<String, Object> retVal = new HashMap<String, Object>();
		String query = getParam(request, "query");
		List<String> list = prestoService.doQuery(query);
		retVal.put("results", list);
		writeJSON(response, retVal);

	}

	private void writeJSON(HttpServletResponse resp, Object obj)
			throws IOException {
		resp.setContentType("application/json");
		ObjectMapper mapper = new ObjectMapper();
		OutputStream stream = resp.getOutputStream();
		mapper.writeValue(stream, obj);
	}

	private String getParam(HttpServletRequest request, String name)
			throws ServletException {
		String p = request.getParameter(name);
		if (p == null)
			throw new ServletException("Missing required parameter '" + name
					+ "'.");
		else
			return p;
	}

}

@@ -128,16 +128,43 @@
 il.List;
+%0Aimport java.util.Optional;
 %0A%0Aimport
@@ -879,169 +879,251 @@
 %0A%0A%09%09
-HashMap%3CString, Object%3E retVal = new HashMap%3CString, Object%3E();%0A%09%09String query = getParam(request, %22query%22);%0A%09%09List%3CString%3E list = prestoService.doQuery(query);%0A
+Optional%3CString%3E queryOptional = Optional.ofNullable(request.getParameter(%22query%22));%0A%09%09queryOptional.ifPresent(query -%3E %7B%0A%09%09%09List%3CString%3E list = prestoService.doQuery(query);%0A%09%09%09HashMap%3CString, Object%3E retVal = new HashMap%3CString, Object%3E();%0A%09
 %09%09re
@@ -1149,16 +1149,27 @@
  list);%0A
+%09%09%09try %7B%0A%09%09
 %09%09writeJ
@@ -1190,16 +1190,91 @@
 retVal);
+%0A%09%09%09%7D catch (IOException e) %7B%0A%09%09%09%09throw new RuntimeException(e);%0A%09%09%09%7D%0A%09%09%7D);
 %0A%0A%09%7D%0A%0A%09p
@@ -1533,266 +1533,8 @@
 %0A%09%7D%0A
-%0A%09private String getParam(HttpServletRequest request, String name)%0A%09%09%09throws ServletException %7B%0A%09%09String p = request.getParameter(name);%0A%09%09if (p == null)%0A%09%09%09throw new ServletException(%22Missing required parameter '%22 + name%0A%09%09%09%09%09+ %22'.%22);%0A%09%09else%0A%09%09%09return p;%0A%09%7D%0A
+%09
 %0A%7D%0A

use Optional