source: other-projects/hathitrust/wcsa/vol-checker/src/org/hathitrust/extractedfeatures/VolumeCheck.java@ 31355

Last change on this file since 31355 was 31355, checked in by davidb, 7 years ago

Changed to using containsKey rather than get to avoid null pointer cast problem

  • Property svn:executable set to *
File size: 10.8 KB
Line 
1package org.hathitrust.extractedfeatures;
2
3import java.io.BufferedInputStream;
4import java.io.BufferedOutputStream;
5import java.io.BufferedReader;
6import java.io.DataOutputStream;
7import java.io.FileInputStream;
8import java.io.IOException;
9import java.io.InputStream;
10import java.io.InputStreamReader;
11import java.io.OutputStream;
12import java.io.PrintWriter;
13import java.net.HttpURLConnection;
14import java.net.URL;
15import java.nio.charset.StandardCharsets;
16import java.util.HashMap;
17
18import javax.servlet.ServletConfig;
19import javax.servlet.ServletException;
20import javax.servlet.annotation.WebServlet;
21import javax.servlet.http.HttpServlet;
22import javax.servlet.http.HttpServletRequest;
23import javax.servlet.http.HttpServletResponse;
24
25
26/**
27 * Servlet implementation class VolumeCheck
28 */
29@WebServlet("/VolumeCheck")
30public class VolumeCheck extends HttpServlet {
31 private static final long serialVersionUID = 1L;
32
33 protected static int HASHMAP_INIT_SIZE = 13800000;
34 protected static HashMap<String,Boolean> id_check_ = null;
35
36 protected static final String file_ext = ".json.bz2";
37 protected static final String ht_col_url = "https://babel.hathitrust.org/cgi/mb";
38
39 public VolumeCheck()
40 {}
41
42 protected static String full_filename_to_tail(String full_filename)
43 {
44 String filename_tail = full_filename.substring(full_filename.lastIndexOf("/")+1);
45 return filename_tail;
46 }
47
48 protected static String filename_tail_to_id(String filename_tail)
49 {
50 String id = null;
51 if (filename_tail.endsWith(file_ext)) {
52 id = filename_tail.substring(0,filename_tail.lastIndexOf(file_ext));
53 }
54 else {
55 id = filename_tail;
56 }
57
58 id = id.replaceAll("\\+", ":").replaceAll("=", "/");
59
60 return id;
61 }
62
63 protected static String id_to_pairtree_filename(String id) {
64 // Example :-
65 // id: miun.adx6300.0001.001
66 // pairtree filename: miun/pairtree_root/ad/x6/30/0,/00/01/,0/01/adx6300,0001,001/miun.adx6300,0001,001.json.bz2
67
68 // 1. Map 'difficult' chars:
69 // . => ,
70 // : => +
71 // / => =
72
73 // 2. Process resulting string:
74 // split on first dot
75 // add "pairtree_root"
76 // then split everything else 2 chars at a time
77
78 // 3. Finally add in the (safely transformed) id:
79 // append directory that is prefix-removed id (transformed to be safe)
80 // further append 'id-safe'.json.bz
81
82 int id_dot_pos = id.indexOf(".");
83 String id_prefix = id.substring(0,id_dot_pos);
84 String id_tail = id.substring(id_dot_pos+1);
85 String id_tail_safe = id_tail.replaceAll("\\.", ",").replaceAll(":", "+").replaceAll("/", "=");
86
87 String [] pairs = id_tail_safe.split("(?<=\\G..)");
88 String joined_pairs = String.join("/", pairs);
89
90 String id_safe = id_prefix + "." + id_tail_safe;
91 String main_dir = id_prefix + "/pairtree_root/" + joined_pairs;
92 String filename = main_dir + "/" + id_tail_safe + "/" + id_safe + file_ext;
93
94 return filename;
95 }
96
97 protected void storeIDs(BufferedReader br)
98 {
99 long line_num = 1;
100 String line;
101
102 try {
103
104 System.err.print("Loading hashmap: ");
105 while ((line = br.readLine()) != null) {
106
107 String full_json_filename = line;
108 String json_filename_tail = full_filename_to_tail(full_json_filename);
109 String id = filename_tail_to_id(json_filename_tail);
110
111 id_check_.put(id, true);
112
113 if ((line_num % 100000) == 0) {
114 //System.err.println("sample id = " + id);
115 //System.err.println("Passed line: " + line_num);
116 System.err.print(".");
117 }
118 line_num++;
119
120 }
121 System.err.println(" => done.");
122 }
123 catch (Exception e) {
124 e.printStackTrace();
125 }
126
127 }
128 /**
129 * @see Servlet#init(ServletConfig)
130 */
131 public void init(ServletConfig config) throws ServletException {
132 super.init(config);
133
134 if (id_check_ == null) {
135 id_check_ = new HashMap<String,Boolean>(HASHMAP_INIT_SIZE);
136
137 String htrc_list_file = "htrc-ef-all-files.txt";
138 InputStream is = getServletContext().getResourceAsStream("/WEB-INF/" + htrc_list_file);
139
140 try {
141 System.err.println("INFO: Loading in volume IDS: " + htrc_list_file);
142
143 InputStreamReader isr = new InputStreamReader(is, "UTF-8");
144 BufferedReader br = new BufferedReader(isr);
145
146 storeIDs(br);
147 br.close();
148 }
149 catch (Exception e) {
150 e.printStackTrace();
151 }
152 }
153 }
154
155 protected BufferedInputStream doRsyncDownload(String full_json_filename)
156 {
157 String json_filename_tail = full_filename_to_tail(full_json_filename);
158
159 BufferedInputStream bis = null;
160
161 Runtime runtime = Runtime.getRuntime();
162 String[] rsync_command = {"rsync","-av","data.analytics.hathitrust.org::features/" + full_json_filename, "."};
163
164 try {
165 Process proc = runtime.exec(rsync_command);
166 proc.waitFor();
167 //System.err.println("*** Rsync finished");
168
169 FileInputStream fis = new FileInputStream(json_filename_tail);
170 bis = new BufferedInputStream(fis);
171
172 }
173 catch (Exception e) {
174 e.printStackTrace();
175 }
176
177 return bis;
178
179 }
180
181 protected void doCollectionToWorkset(HttpServletResponse response, String c, String a, String format) throws IOException
182 {
183 String post_url_params = "c="+c+"&a="+a+"&format="+format;
184
185 byte[] post_data = post_url_params.getBytes(StandardCharsets.UTF_8);
186 int post_data_len = post_data.length;
187
188 try {
189
190 URL post_url = new URL(ht_col_url);
191 HttpURLConnection conn = (HttpURLConnection) post_url.openConnection();
192 conn.setDoOutput(true);
193 conn.setInstanceFollowRedirects(false);
194 conn.setRequestMethod("POST");
195 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
196 conn.setRequestProperty("charset", "utf-8");
197 conn.setRequestProperty("Content-Length", Integer.toString(post_data_len));
198 conn.setUseCaches(false);
199
200 try(DataOutputStream dos = new DataOutputStream(conn.getOutputStream())) {
201 dos.write(post_data);
202 }
203 // try-resource auto-closes stream
204
205 InputStream is = conn.getInputStream();
206 InputStreamReader isr = new InputStreamReader(is);
207 BufferedReader reader = new BufferedReader(isr);
208
209 StringBuilder workset_friendly_sb = new StringBuilder();
210 StringBuilder workset_unfriendly_sb = new StringBuilder();
211
212 String line = null;
213 int ci = 0;
214 while ((line = reader.readLine()) != null)
215 {
216 if (ci==0) {
217 workset_friendly_sb.append("#" + line + "\n");
218 }
219 else {
220 int first_tab_pos=line.indexOf("\t");
221 String id = (first_tab_pos>0) ? line.substring(0, first_tab_pos) : line;
222
223 if (id_check_.containsKey(id)) {
224 workset_friendly_sb.append(line + "\n");
225 }
226 else {
227 workset_unfriendly_sb.append("#" + line + "\n");
228 }
229 }
230
231 ci++;
232 }
233
234 response.setContentType("text/plain");
235 PrintWriter pw = response.getWriter();
236 pw.append(workset_friendly_sb.toString());
237 pw.append("## The following volumes are not in the HTRC Extracted Feature dataset\n");
238 pw.append(workset_unfriendly_sb.toString());
239 }
240 catch (Exception e) {
241 e.printStackTrace();
242 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Failed to convert HT collection to HTRC workset");
243 }
244
245 }
246 /**
247 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
248 */
249 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
250 {
251
252
253 String cgi_ids = request.getParameter("ids");
254 String cgi_id = request.getParameter("id");
255 String cgi_download_id = request.getParameter("download-id");
256 String cgi_convert_col = request.getParameter("convert-col");
257
258 if (cgi_ids != null) {
259 response.setContentType("application/json");
260 PrintWriter pw = response.getWriter();
261
262 String[] ids = cgi_ids.split(",");
263 int ids_len = ids.length;
264
265 pw.append("{");
266
267 for (int i=0; i<ids_len; i++) {
268 String id = ids[i];
269
270 boolean exists = id_check_.containsKey(id);
271
272 if (i>0) {
273 pw.append(",");
274 }
275 pw.append("\"" + id + "\":" + exists );
276 }
277 pw.append("}");
278
279 }
280 else if (cgi_id != null) {
281 response.setContentType("application/json");
282 PrintWriter pw = response.getWriter();
283
284 String id = cgi_id;
285 boolean exists = id_check_.containsKey(id);
286 pw.append("{'" + id + "':" + exists + "}");
287 }
288 else if (cgi_download_id != null) {
289 String download_id = cgi_download_id;
290 boolean exists = id_check_.containsKey(download_id);
291 if (!exists) {
292 // Error
293 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "The requested volume id does not exist.");
294 }
295 else {
296 // rsync -av data.analytics.hathitrust.org::features/{PATH-TO-FILE} .
297 String full_json_filename = id_to_pairtree_filename(download_id);
298
299 BufferedInputStream bis = doRsyncDownload(full_json_filename);
300
301 if (bis == null) {
302 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Rsync failed");
303 }
304 else {
305 String json_filename_tail = full_filename_to_tail(full_json_filename);
306
307 response.setContentType("application/x-bzip2");
308 response.setHeader("Content-Disposition", "attachment; filename=\"" + json_filename_tail + "\"");
309
310 OutputStream os=response.getOutputStream();
311 BufferedOutputStream bos = new BufferedOutputStream(os);
312
313 byte[] buf = new byte[1024];
314
315 while (true) {
316 int num_bytes = bis.read(buf);
317 if (num_bytes == -1) {
318 break;
319 }
320 bos.write(buf,0,num_bytes);
321 //total_num_bytes += num_bytes;
322 }
323
324 bis.close();
325 bos.close();
326 }
327 }
328 }
329 else if (cgi_convert_col != null) {
330 // c=464226859&a=download&format=text
331 //String cgi_c = request.getParameter("c");
332 String cgi_a = request.getParameter("a");
333 String cgi_format = request.getParameter("format");
334
335 if ((cgi_a == null) || (cgi_format == null)) {
336 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed arguments. Need 'a', and 'format'");
337 }
338 else {
339 doCollectionToWorkset(response,cgi_convert_col,cgi_a,cgi_format);
340 }
341
342 }
343 else {
344 PrintWriter pw = response.getWriter();
345
346 pw.append("General Info: Number of HTRC Volumes in check-list = " + id_check_.size());
347
348 }
349 //pw.close();
350
351 }
352
353 /**
354 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
355 */
356 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
357 doGet(request, response);
358 }
359
360}
Note: See TracBrowser for help on using the repository browser.