package yanagishima.servlet;

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

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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import yanagishima.result.PrestoQueryResult;
import yanagishima.service.PrestoService;

@Singleton
public class PrestoServlet extends HttpServlet {

	private static Logger LOGGER = LoggerFactory.getLogger(PrestoServlet.class);

	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 {

		Optional<String> queryOptional = Optional.ofNullable(request
				.getParameter("query"));
		queryOptional.ifPresent(query -> {

			HashMap<String, Object> retVal = new HashMap<String, Object>();

			try {
				PrestoQueryResult prestoQueryResult = prestoService
						.doQuery(query);
				if (prestoQueryResult.getUpdateType() == null) {// select
					retVal.put("headers", prestoQueryResult.getColumns());
					retVal.put("results", prestoQueryResult.getRecords());
					Optional<String> warningMessageOptinal = Optional
							.ofNullable(prestoQueryResult.getWarningMessage());
					warningMessageOptinal.ifPresent(warningMessage -> {
						retVal.put("warn", warningMessage);
					});
				}
			} catch (Throwable e) {
				LOGGER.error(e.getMessage(), e);
				retVal.put("error", e.getMessage());
			}

			try {
				writeJSON(response, retVal);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}

		});

	}

	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);
	}

}

@@ -1093,21 +1093,16 @@
 (request
-%0A%09%09%09%09
 .getPara
@@ -1118,16 +1118,16 @@
 ery%22));%0A
+
 %09%09queryO
@@ -1288,23 +1288,16 @@
 oService
-%0A%09%09%09%09%09%09
 .doQuery
@@ -1545,16 +1545,8 @@
 onal
-%0A%09%09%09%09%09%09%09
 .ofN
@@ -2002,20 +2002,17 @@
 ect obj)
-%0A%09%09%09
+ 
 throws I

change format