source: other-projects/hathitrust/solr-extracted-features/trunk/src/main/java/org/hathitrust/PagedJSON.java@ 30973

Last change on this file since 30973 was 30973, checked in by davidb, 8 years ago

Changed to saving Solr JSON file for debugging purposes

  • Property svn:executable set to *
File size: 8.9 KB
Line 
1package org.hathitrust;
2
3import java.io.BufferedReader;
4import java.io.BufferedWriter;
5import java.io.IOException;
6import java.io.OutputStream;
7import java.net.HttpURLConnection;
8import java.net.URL;
9import java.util.ArrayList;
10import java.util.Iterator;
11import java.util.Set;
12
13import org.apache.commons.compress.compressors.CompressorException;
14import org.apache.spark.api.java.function.FlatMapFunction;
15import org.json.JSONArray;
16import org.json.JSONObject;
17
18/*
19class PagedJSON implements Function<String, Boolean> {
20
21 private static final long serialVersionUID = 1L;
22
23 public Boolean call(String s) { return s.contains("a"); }
24}
25 */
26
27
28class PagedJSON implements FlatMapFunction<String, String>
29{
30 private static final long serialVersionUID = 1L;
31
32 protected String _input_dir;
33 protected String _output_dir;
34 protected int _verbosity;
35
36 public PagedJSON(String input_dir, String output_dir, int verbosity)
37 {
38 _input_dir = input_dir;
39 _output_dir = output_dir;
40 _verbosity = verbosity;
41 }
42
43 protected JSONObject readJSONFile(String filename)
44 {
45 StringBuilder sb = new StringBuilder();
46
47 try {
48
49 String str;
50 BufferedReader br = ClusterFileIO.getBufferedReaderForCompressedFile(_input_dir + "/" + filename);
51 while ((str = br.readLine()) != null) {
52 sb.append(str);
53 }
54
55 br.close();
56 }
57 catch (Exception e) {
58 e.printStackTrace();
59 }
60
61 JSONObject json_obj = new JSONObject(sb.toString());
62
63
64 return json_obj;
65 }
66
67 protected String generateSolrText(JSONObject ef_token_pos_count)
68 {
69 StringBuilder sb = new StringBuilder();
70
71 Iterator<String> token_iter = ef_token_pos_count.keys();
72 while (token_iter.hasNext()) {
73 String token = token_iter.next();
74
75 sb.append(token);
76 if (token_iter.hasNext()) {
77 sb.append(" ");
78 }
79 }
80
81 /*
82 Set<String> token_keys = ef_token_pos_count.keySet();
83 for (String token : token_keys) {
84 sb.append(token + " ");
85 }
86*/
87
88 return sb.toString();
89 }
90
91 protected JSONObject generateSolrDocJSON(String volume_id, String page_id, JSONObject ef_page)
92 {
93 JSONObject solr_add_json = null;
94
95 if (ef_page != null) {
96 JSONObject ef_body = ef_page.getJSONObject("body");
97 if (ef_body != null) {
98 JSONObject ef_token_pos_count = ef_body.getJSONObject("tokenPosCount");
99 if (ef_token_pos_count != null) {
100
101 solr_add_json = new JSONObject();
102
103 String text = generateSolrText(ef_token_pos_count);
104
105
106
107 JSONObject solr_doc_json = new JSONObject();
108 solr_doc_json.put("id", page_id);
109 solr_doc_json.put("volumeid_s", volume_id);
110 solr_doc_json.put("_text_", text);
111 solr_doc_json.put("commitWithin", 5000);
112
113 solr_add_json.put("add", solr_doc_json);
114 }
115 else {
116 System.err.println("Warning: empty tokenPosCount field for '" + page_id + "'");
117 }
118 }
119 else {
120 System.err.println("Warning: empty body field for '" + page_id + "'");
121 }
122
123 }
124 else {
125 System.err.println("Warning: null page for '" + page_id + "'");
126 }
127
128
129 /*
130
131 /update/json/docs
132 */
133
134 // For Reference ...
135 // Example documentation on Solr JSON syntax:
136 // https://cwiki.apache.org/confluence/display/solr/Uploading+Data+with+Index+Handlers
137 // #UploadingDatawithIndexHandlers-JSONFormattedIndexUpdates
138
139 /*
140 curl -X POST -H 'Content-Type: application/json' 'http://localhost:8983/solr/my_collection/update' --data-binary '
141 {
142 "add": {
143 "doc": {
144 "id": "DOC1",
145 "my_boosted_field": { use a map with boost/value for a boosted field
146 "boost": 2.3,
147 "value": "test"
148 },
149 "my_multivalued_field": [ "aaa", "bbb" ] Can use an array for a multi-valued field
150 }
151 },
152 "add": {
153 "commitWithin": 5000, commit this document within 5 seconds
154 "overwrite": false, don't check for existing documents with the same uniqueKey
155 "boost": 3.45, a document boost
156 "doc": {
157 "f1": "v1", Can use repeated keys for a multi-valued field
158 "f1": "v2"
159 }
160 },
161
162 "commit": {},
163 "optimize": { "waitSearcher":false },
164
165 "delete": { "id":"ID" }, delete by ID
166 "delete": { "query":"QUERY" } delete by query
167 }'
168 */
169
170 //return solr_doc_json;
171 return solr_add_json;
172 }
173
174 protected void saveSolrDoc(JSONObject solr_add_doc_json, String output_file_json_bz2)
175 {
176 try {
177 BufferedWriter bw = ClusterFileIO.getBufferedWriterForCompressedFile(_output_dir + "/" + output_file_json_bz2);
178 bw.write(solr_add_doc_json.toString());
179 bw.close();
180 } catch (IOException e) {
181 e.printStackTrace();
182 } catch (CompressorException e) {
183 e.printStackTrace();
184 }
185 }
186
187 protected void postSolrDoc(JSONObject solr_add_doc_json)
188 {
189 // "http://10.11.0.53:8983/solr/"
190 String post_url = "http://10.11.0.53:8983/solr/htrc-pd-ef/update";
191
192 //String curl_popen = "curl -X POST -H 'Content-Type: application/json'";
193 //curl_popen += " 'http://10.11.0.53:8983/solr/htrc-pd-ef/update'";
194 //curl_popen += " --data-binary '";
195 //curl_popen += "'"
196
197
198 try {
199 HttpURLConnection httpcon = (HttpURLConnection) ((new URL(post_url).openConnection()));
200 httpcon.setDoOutput(true);
201 httpcon.setRequestProperty("Content-Type", "application/json");
202 httpcon.setRequestProperty("Accept", "application/json");
203 httpcon.setRequestMethod("POST");
204 httpcon.connect();
205
206 byte[] outputBytes = solr_add_doc_json.toString().getBytes("UTF-8");
207 OutputStream os = httpcon.getOutputStream();
208 os.write(outputBytes);
209 os.close();
210 }
211 catch (Exception e) {
212 e.printStackTrace();
213 }
214
215 }
216 public Iterator<String> call(String json_file_in)
217 {
218 JSONObject extracted_feature_record = readJSONFile(json_file_in);
219
220 // Check output directory for volume exists, and create it if not
221
222
223 String volume_id = extracted_feature_record.getString("id");
224
225 //JSONObject ef_metadata = extracted_feature_record.getJSONObject("metadata");
226 //String title= ef_metadata.getString("title");
227
228 JSONObject ef_features = extracted_feature_record.getJSONObject("features");
229
230
231 int ef_page_count = ef_features.getInt("pageCount");
232
233 if (_verbosity >= 1) {
234 System.out.println("Processing: " + json_file_in);
235 System.out.println(" pageCount = " + ef_page_count);
236 }
237
238 JSONArray ef_pages = ef_features.getJSONArray("pages");
239 int ef_num_pages = ef_pages.length();
240
241 // Make directory for page-level JSON output
242 String json_dir = ClusterFileIO.removeSuffix(json_file_in,".json.bz2");
243 String page_json_dir = json_dir + "/pages";
244 ClusterFileIO.createDirectoryAll(_output_dir + "/" + page_json_dir);
245
246 ArrayList<String> ids = new ArrayList<String>(ef_num_pages);
247 for (int i = 0; i < ef_page_count; i++) {
248 String formatted_i = String.format("page-%06d", i);
249 String page_id = volume_id + "." + formatted_i;
250
251 if (_verbosity >= 2) {
252 System.out.println(" Page: " + page_id);
253 }
254
255 String output_json_bz2 = page_json_dir +"/" + formatted_i + ".json.bz2";
256 ids.add(output_json_bz2);
257
258 if (i==0) {
259 System.out.println("Sample output JSON page file: " + output_json_bz2);
260 }
261
262 JSONObject ef_page = ef_pages.getJSONObject(i);
263
264 if (ef_page != null) {
265 // Convert to Solr add form
266 JSONObject solr_add_doc_json = generateSolrDocJSON(volume_id, page_id, ef_page);
267
268 if (i==20) {
269 System.out.println("Sample output Solr add JSON [page 20]: " + solr_add_doc_json.toString());
270 System.out.println("==================");
271 //System.out.println("Sample text [page 20]: " + solr_add_doc_json.getString("_text_"));
272 }
273
274 // create JSON obj of just the page (for now), and write it out
275 // write out the JSONOBject as a bz2 compressed file
276 /*
277 try {
278 BufferedWriter bw = ClusterFileIO.getBufferedWriterForCompressedFile(_output_dir + "/" + output_json_bz2);
279 bw.write(ef_page.toString());
280 bw.close();
281 } catch (IOException e) {
282 e.printStackTrace();
283 } catch (CompressorException e) {
284 e.printStackTrace();
285 }
286 */
287
288 saveSolrDoc(solr_add_doc_json,output_json_bz2);
289 //postSolrDoc(solr_add_doc_json);
290
291 }
292 else {
293 System.err.println("Skipping: " + page_id);
294 }
295
296 }
297
298 /*
299 for (int i = 0; i < ef_num_pages; i++)
300 {
301 //String post_id = ef_pages.getJSONObject(i).getString("post_id");
302 //......
303 }
304 */
305 //String pageName = json_obj.getJSONObject("pageInfo").getString("pageName");
306/*
307 JSONArray arr = obj.getJSONArray("posts");
308 for (int i = 0; i < arr.length(); i++)
309 {
310 String post_id = arr.getJSONObject(i).getString("post_id");
311 ......
312 }
313*/
314
315
316 ids.add(volume_id);
317
318 return ids.iterator();
319 }
320}
321
Note: See TracBrowser for help on using the repository browser.