Debian Codegraph @

bindings/java/org/linkgrammar/LGRemoteClient.java

raw
1 package org.linkgrammar;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.io.PrintWriter;
7 import java.net.Socket;
8 import java.net.UnknownHostException;
9 import java.util.List;
10 import java.util.Map;
11
12 /**
13 * <p>
14 * A client of the {@link LGService} when it is run in server mode. The main
15 * method to call is {@link parse} which produces a {@link ParseResult}. At
16 * a minimum, the <code>hostname</code> and <code>port</code> properties
17 * must be set beforehand. Configuration settings of the remote parser itself
18 * are specified with the <code>config</code> property.
19 * </p>
20 *
21 * <p>
22 * This client is persistent in its attempts to perform a parse. By default
23 * it will keep trying to connect to a server indefinitely (unless the host is
24 * unknown). To change that,
25 * set the <code>connectRetryCount</code> property. Also, if call to the server
26 * fails for whatever reason, it will retry at least once. The increase the number
27 * of retries, set the <code>parseRetryCount</code> property.
28 * </p>
29 *
30 * @author Borislav Iordanov
31 *
32 */
33 public class LGRemoteClient
34 {
35 private LGConfig config = new LGConfig();
36 private String parserVersion;
37 private String hostname = "localhost";
38 private int port = 9000;
39 private int parseRetryCount = 2;
40 private int connectRetryCount = Integer.MAX_VALUE;
41 private long connectRetryWait = 1000l;
42
43 @SuppressWarnings({"unchecked"})
44 private ParseResult jsonToParseResult(String json)
45 {
46 JSONReader reader = new JSONReader();
47 Map top = (Map)reader.read(json);
48 ParseResult result = new ParseResult();
49 result.setParserVersion((String)top.get("version"));
50 result.setNumSkippedWords(((Number)top.get("numSkippedWords")).intValue());
51 for (Map x : (List<Map>)top.get("linkages"))
52 {
53 Linkage linkage = new Linkage();
54 linkage.setDisjunctCost(((Number)x.get("disjunctCost")).doubleValue());
55 linkage.setLinkCost(((Number)x.get("linkageCost")).doubleValue());
56 linkage.setNumViolations(((Number)x.get("numViolations")).intValue());
57 linkage.setWords(((List<String>)(x.get("words"))).toArray(new String[0]));
58 linkage.setDisjuncts(((List<String>)(x.get("disjuncts"))).toArray(new String[0]));
59 linkage.setLinkedWordCount(linkage.getWords().length); // TODO?? is this right?
60 for (Map y : (List<Map>)x.get("links"))
61 {
62 Link link = new Link();
63 link.setLabel((String)y.get("label"));
64 link.setLeftLabel((String)y.get("leftLabel"));
65 link.setRightLabel((String)y.get("rightLabel"));
66 link.setLeft(((Number)y.get("left")).intValue());
67 link.setRight(((Number)y.get("right")).intValue());
68 linkage.getLinks().add(link);
69 }
70 if (config.isStoreConstituentString())
71 linkage.setConstituentString((String)x.get("constituentString"));
72 result.getLinkages().add(linkage);
73 }
74 return result;
75 }
76
77 private String makeLGRequest(String text)
78 {
79 if (config != null)
80 return "storeConstituentString:" + config.isStoreConstituentString() + "\0" +
81 "maxCost:" + config.getMaxCost() + "\0" +
82 "maxLinkages:" + config.getMaxLinkages() + "\0" +
83 "maxParseSeconds:" + config.getMaxParseSeconds() + "\0" +
84 "text:" + text + "\0";
85 else
86 return "text:" + text + "\0";
87 }
88
89 private String readResponse(BufferedReader in, int size) throws IOException
90 {
91 char [] buf = new char[size];
92 for (int count = 0; count < size; )
93 count += in.read(buf, count, size-count);
94 return new String(buf, 0, size);
95 }
96
97 private String callParser(String request) throws InterruptedException, IOException
98 {
99 if (hostname == null || hostname.length() == 0 || port <= 1024)
100 throw new RuntimeException("No hostname for remote parser or invalid port number < 1024");
101
102 //
103 // Connect:
104 //
105 Socket socket = null;
106
107 for (int i = 0; i < connectRetryCount && socket == null; i++)
108 {
109 try
110 {
111 socket = new Socket(hostname, port);
112 }
113 catch (UnknownHostException ex)
114 {
115 throw new RuntimeException("Host '" + hostname + "' not found.");
116 }
117 catch (IOException ex)
118 {
119 // ignore, retry...
120 }
121 if (socket == null)
122 Thread.sleep(connectRetryWait);
123 }
124
125 if (socket == null)
126 throw new RuntimeException("Failed to connect to " + hostname + ":" + port);
127
128 //
129 // Call parser:
130 //
131 PrintWriter out = null;
132 BufferedReader in = null;
133 try
134 {
135 out = new PrintWriter(socket.getOutputStream(), true);
136 in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
137 out.print(request);
138 out.print('\n');
139 out.flush();
140 String size = in.readLine();
141 if (size == null)
142 throw new RuntimeException("Parser returned no response.");
143 return readResponse(in, Integer.parseInt(size));
144 }
145 finally
146 {
147 if (out != null) try { out.close(); } catch (Throwable t) { }
148 if (in != null) try { in.close(); } catch (Throwable t) { }
149 try { socket.close(); } catch (Throwable t) { }
150 }
151 }
152
153 /**
154 * <p>Return the link grammar version. A call to the server is made to
155 * obtain the version which is henceforth cached.</p>
156 */
157 @SuppressWarnings("unchecked")
158 public String getVersion()
159 {
160 if (parserVersion == null)
161 {
162 try
163 {
164 String json = callParser("get:version\0");
165 JSONReader reader = new JSONReader();
166 Map top = (Map)reader.read(json);
167 parserVersion = (String)top.get("version");
168 }
169 catch (IOException ex)
170 {
171 parserVersion = "unavailable";
172 }
173 catch (InterruptedException ex)
174 {
175 throw new RuntimeException("Thread interrupted.", ex);
176 }
177 }
178 return parserVersion;
179 }
180
181 public ParseResult parse(String sentence) throws InterruptedException
182 {
183 String parserResponse = null;
184 for (int i = 0; i < parseRetryCount && parserResponse == null; i++)
185 try { parserResponse = callParser(makeLGRequest(sentence)); }
186 catch (IOException ex)
187 {
188 if (i == 0) // Trace exception only on the first failure.
189 {
190 System.err.println("Link grammar called failed on '" +
191 sentence + "'" + ", will retry " +
192 Integer.toString(parseRetryCount - 1) +
193 " more time.");
194 ex.printStackTrace();
195 }
196 }
197 if (parserResponse == null)
198 return null;
199 ParseResult parseResult = jsonToParseResult(parserResponse);
200 parseResult.setText(sentence);
201 return parseResult;
202 }
203
204 public LGConfig getConfig()
205 {
206 return config;
207 }
208
209 public void setConfig(LGConfig config)
210 {
211 this.config = config;
212 }
213
214 public String getHostname()
215 {
216 return hostname;
217 }
218
219 public void setHostname(String hostname)
220 {
221 this.hostname = hostname;
222 }
223
224 public int getPort()
225 {
226 return port;
227 }
228
229 public void setPort(int port)
230 {
231 this.port = port;
232 }
233
234 public int getParseRetryCount()
235 {
236 return parseRetryCount;
237 }
238
239 public void setParseRetryCount(int parseRetryCount)
240 {
241 this.parseRetryCount = parseRetryCount;
242 }
243
244 public int getConnectRetryCount()
245 {
246 return connectRetryCount;
247 }
248
249 public void setConnectRetryCount(int connectRetryCount)
250 {
251 this.connectRetryCount = connectRetryCount;
252 }
253
254 public long getConnectRetryWait()
255 {
256 return connectRetryWait;
257 }
258
259 public void setConnectRetryWait(long connectRetryWait)
260 {
261 this.connectRetryWait = connectRetryWait;
262 }
263 }