1   package eu.fbk.dh.tint.runner;
2   
3   import org.glassfish.grizzly.Buffer;
4   import org.glassfish.grizzly.http.server.HttpHandler;
5   import org.glassfish.grizzly.http.server.Request;
6   import org.glassfish.grizzly.http.server.Response;
7   import org.slf4j.Logger;
8   import org.slf4j.LoggerFactory;
9   
10  import java.io.*;
11  import java.util.HashMap;
12  import java.util.Map;
13  
14  /**
15   * Created with IntelliJ IDEA.
16   * User: alessio
17   * Date: 21/07/14
18   * Time: 15:30
19   * To change this template use File | Settings | File Templates.
20   */
21  
22  public class TintHandler extends HttpHandler {
23  
24      private static final Logger LOGGER = LoggerFactory.getLogger(TintHandler.class);
25      private TintPipeline pipeline;
26  
27      public static Map<TintRunner.OutputFormat, String> contentTypes = new HashMap<>();
28  
29      static {
30          contentTypes.put(TintRunner.OutputFormat.CONLL, "text/plain");
31          contentTypes.put(TintRunner.OutputFormat.XML, "text/xml");
32          contentTypes.put(TintRunner.OutputFormat.NAF, "text/xml");
33          contentTypes.put(TintRunner.OutputFormat.JSON, "text/json");
34          contentTypes.put(TintRunner.OutputFormat.TEXTPRO, "text/plain");
35          contentTypes.put(TintRunner.OutputFormat.READABLE, "text/plain");
36      }
37  
38      public TintHandler(TintPipeline pipeline) {
39          this.pipeline = pipeline;
40      }
41  
42      public void writeOutput(Response response, String contentType, String output) throws IOException {
43          response.setContentType(contentType);
44          response.setCharacterEncoding("UTF-8");
45          response.addHeader("Access-Control-Allow-Origin", "*");
46          response.getWriter().write(output);
47      }
48  
49      @Override
50      public void service(Request request, Response response) throws Exception {
51  
52          request.setCharacterEncoding("UTF-8");
53  
54          Buffer postBody = request.getPostBody(1024);
55          String text = postBody.toStringContent();
56  
57          if (request.getParameter("text") != null) {
58              text = request.getParameter("text");
59          }
60  
61          String outputFormat = request.getParameter("format");
62  
63          InputStream inputStream = new ByteArrayInputStream(text.getBytes());
64          OutputStream outputStream = new ByteArrayOutputStream();
65  
66          TintRunner.OutputFormat format = TintRunner.getOutputFormat(outputFormat, TintRunner.OutputFormat.JSON);
67          pipeline.run(inputStream, outputStream, format);
68  
69          LOGGER.debug("Text: {}", text);
70  
71          String output = outputStream.toString();
72  
73          writeOutput(response, contentTypes.get(format), output);
74      }
75  }