1   package eu.fbk.dkm.pikes.tintopclient;
2   
3   import eu.fbk.utils.core.CommandLine;
4   import org.apache.commons.io.FileUtils;
5   import org.apache.commons.io.IOUtils;
6   import org.apache.http.HttpEntity;
7   import org.apache.http.NameValuePair;
8   import org.apache.http.client.config.RequestConfig;
9   import org.apache.http.client.entity.UrlEncodedFormEntity;
10  import org.apache.http.client.methods.CloseableHttpResponse;
11  import org.apache.http.client.methods.HttpPost;
12  import org.apache.http.client.utils.URIBuilder;
13  import org.apache.http.impl.client.CloseableHttpClient;
14  import org.apache.http.impl.client.HttpClients;
15  import org.apache.http.message.BasicNameValuePair;
16  import org.slf4j.LoggerFactory;
17  
18  import java.io.File;
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.net.MalformedURLException;
22  import java.net.URI;
23  import java.net.URISyntaxException;
24  import java.net.URL;
25  import java.util.ArrayList;
26  import java.util.List;
27  
28  /**
29   * Created by alessio on 02/03/15.
30   */
31  
32  public class TintopClient {
33  
34      private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TintopClient.class);
35  
36      static public Integer DEFAULT_TIMEOUT = 60000;
37  
38      protected TintopServer server;
39      private Integer timeout;
40      private boolean fake = false;
41  
42      public void setFake(boolean fake) {
43          this.fake = fake;
44      }
45  
46      public TintopClient(String serverUrl) throws MalformedURLException {
47          URL url = new URL(serverUrl);
48          this.server = new TintopServer(url);
49      }
50  
51      public TintopClient(TintopServer server) {
52          this(server, DEFAULT_TIMEOUT);
53      }
54  
55      public TintopClient(TintopServer server, Integer timeout) {
56          this.server = server;
57          this.timeout = timeout;
58      }
59  
60      public String call(String text) throws URISyntaxException, IOException {
61  
62          RequestConfig defaultRequestConfig = RequestConfig.custom()
63                  .setSocketTimeout(timeout)
64                  .setConnectTimeout(timeout)
65                  .setConnectionRequestTimeout(timeout)
66                  .build();
67  
68          CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
69          URI uri = new URIBuilder()
70                  .setScheme(server.getProtocol())
71                  .setHost(server.getHost())
72                  .setPort(server.getPort())
73                  .setPath(server.getPath())
74                  .build();
75          logger.debug("Calling URI " + uri.toString());
76  
77          if (!fake) {
78              HttpPost httpPost = new HttpPost(uri);
79  
80              List<NameValuePair> nameValuePairs = new ArrayList<>(1);
81              nameValuePairs.add(new BasicNameValuePair("naf", text));
82              UrlEncodedFormEntity form = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
83              httpPost.setEntity(form);
84  
85              try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
86                  int statusCode = response.getStatusLine().getStatusCode();
87                  logger.debug("Status code: " + statusCode);
88  
89                  if (statusCode != 200) {
90                      logger.error(uri.toString());
91                      throw new IOException(
92                              String.format("%d: %s", statusCode, response.getStatusLine().getReasonPhrase()));
93                  }
94  
95                  HttpEntity entity = response.getEntity();
96                  if (entity != null) {
97                      try (InputStream instream = entity.getContent()) {
98                          logger.info("NAF retrieved");
99                          return IOUtils.toString(instream);
100                     }
101                 }
102             }
103         }
104 
105         throw new IOException("Null result");
106     }
107 
108     public static void main(String[] args) {
109         try {
110             final CommandLine cmd = CommandLine
111                     .parser()
112                     .withName("./tintop-client")
113                     .withHeader("Run the Tintop Client")
114                     .withOption("i", "input", "Input file", "FILE",
115                             CommandLine.Type.FILE_EXISTING, true, false, true)
116                     .withOption("s", "server", "Server address", "URL:PORT",
117                             CommandLine.Type.STRING, true, false, true)
118                     .withOption("t", "timeout", String.format("Timeout (default %d ms)", DEFAULT_TIMEOUT),
119                             "milliseconds", CommandLine.Type.INTEGER, true, false, false)
120                     .withLogger(LoggerFactory.getLogger("eu.fbk")).parse(args);
121 
122             String serverUrl = cmd.getOptionValue("server", String.class);
123             File inputFile = cmd.getOptionValue("input", File.class);
124             Integer timeout = cmd.getOptionValue("timeout", Integer.class, DEFAULT_TIMEOUT);
125 
126             URL url = new URL(serverUrl);
127             TintopServer server = new TintopServer(url);
128             TintopClient client = new TintopClient(server, timeout);
129 
130             String whole = FileUtils.readFileToString(inputFile);
131             System.out.println(client.call(whole));
132         } catch (Exception e) {
133             CommandLine.fail(e);
134         }
135     }
136 
137 }