Batch Results Retrieval in Java
From Textserver wiki
1 ////////////////////////////////////////////////////////////////////////////
2 //
3 // Example client to submit a batch request to TextServer
4 // SERVICENAME service, and wait for the job to be finished.
5 //
6 // Input must be a ZIP file containing one or more text files to analyze
7 // Output will be a ZIP file containing results for each input file in
8 // the requested format (XML, json, conll)
9 //
10 ////////////////////////////////////////////////////////////////////////////
11
12
13 import org.apache.http.client.HttpClient;
14 import org.apache.http.HttpResponse;
15 import org.apache.http.HttpStatus;
16 import org.apache.http.entity.mime.content.FileBody;
17
18 import org.apache.http.client.methods.HttpPost;
19 import org.apache.http.entity.mime.MultipartEntityBuilder;
20 import org.apache.http.impl.client.HttpClientBuilder;
21 import org.apache.http.util.EntityUtils;
22
23 import java.io.File;
24 import java.io.InputStream;
25 import java.io.FileOutputStream;
26
27 public class RetrieveResults {
28
29 // service base URL
30 static final String textServer_URL = "http://frodo.lsi.upc.edu:8080/TextWS/textservlet/ws";
31
32 public static void main(String[] args) throws Exception {
33
34 // Get request parameters
35 System.out.print("TextServer Username: ");
36 String user = System.console().readLine();
37 System.out.print("TextServer Job Token ID: ");
38 String tokenID = System.console().readLine();
39 System.out.print("Output ZIP file: ");
40 String outfname = System.console().readLine();
41
42
43 // prepare request to poll for completion and retrieve results
44 request = new HttpPost(textServer_URL+"/resultRetrieve");
45 request.setEntity(MultipartEntityBuilder
46 .create()
47 .addTextBody("username", user)
48 .addTextBody("tokenID", tokenID)
49 .build() );
50
51 System.out.println("Polling server for job completion");
52 response = client.execute(request);
53 content = EntityUtils.toString(response.getEntity());
54
55 // we got an error code, lets see which one
56 if (response.getStatusLine().getStatusCode()==HttpStatus.SC_SERVICE_UNAVAILABLE &&
57 content.substring(0,8).equals("[TS-125]") ) {
58 // SC=503 and TS_code=TS-125 mean job is not finished. keep waiting
59 System.out.println("Job not finished yet.");
60 System.exit(0);
61 }
62 else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
63 // some unexpected error happened
64 System.out.println(content);
65 System.exit(1);
66 }
67
68 // No errors, we got response.
69 // write the received ZIP result to output file
70 InputStream sin = response.getEntity().getContent();
71 byte data[] = new byte[sin.available()];
72 sin.read(data);
73
74 FileOutputStream outf = new FileOutputStream(outfname);
75 outf.write(data);
76 outf.close();
77
78 System.out.println("Job finished. Results saved to "+outfname);
79 }
80 }