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

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

import tidy-up

  • Property svn:executable set to *
File size: 10.9 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 System.err.println("**** cgi_ids = '" + cgi_ids + "'");
259 System.err.println("**** cgi_convert_col = '" + cgi_convert_col + "'");
260
261 if (cgi_ids != null) {
262 response.setContentType("application/json");
263 PrintWriter pw = response.getWriter();
264
265 String[] ids = cgi_ids.split(",");
266 int ids_len = ids.length;
267
268 pw.append("{");
269
270 for (int i=0; i<ids_len; i++) {
271 String id = ids[i];
272
273 boolean exists = id_check_.get(id);
274
275 if (i>0) {
276 pw.append(",");
277 }
278 pw.append("\"" + id + "\":" + exists );
279 }
280 pw.append("}");
281
282 }
283 else if (cgi_id != null) {
284 response.setContentType("application/json");
285 PrintWriter pw = response.getWriter();
286
287 String id = cgi_id;
288 boolean exists = id_check_.get(id);
289 pw.append("{'" + id + "':" + exists + "}");
290 }
291 else if (cgi_download_id != null) {
292 String download_id = cgi_download_id;
293 boolean exists = id_check_.get(download_id);
294 if (!exists) {
295 // Error
296 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "The requested volume id does not exist.");
297 }
298 else {
299 // rsync -av data.analytics.hathitrust.org::features/{PATH-TO-FILE} .
300 String full_json_filename = id_to_pairtree_filename(download_id);
301
302 BufferedInputStream bis = doRsyncDownload(full_json_filename);
303
304 if (bis == null) {
305 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Rsync failed");
306 }
307 else {
308 String json_filename_tail = full_filename_to_tail(full_json_filename);
309
310 response.setContentType("application/x-bzip2");
311 response.setHeader("Content-Disposition", "attachment; filename=\"" + json_filename_tail + "\"");
312
313 OutputStream os=response.getOutputStream();
314 BufferedOutputStream bos = new BufferedOutputStream(os);
315
316 byte[] buf = new byte[1024];
317
318 while (true) {
319 int num_bytes = bis.read(buf);
320 if (num_bytes == -1) {
321 break;
322 }
323 bos.write(buf,0,num_bytes);
324 //total_num_bytes += num_bytes;
325 }
326
327 bis.close();
328 bos.close();
329 }
330 }
331 }
332 else if (cgi_convert_col != null) {
333 // c=464226859&a=download&format=text
334 //String cgi_c = request.getParameter("c");
335 String cgi_a = request.getParameter("a");
336 String cgi_format = request.getParameter("format");
337
338 if ((cgi_a == null) || (cgi_format == null)) {
339 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed arguments. Need 'a', and 'format'");
340 }
341 else {
342 doCollectionToWorkset(response,cgi_convert_col,cgi_a,cgi_format);
343 }
344
345 }
346 else {
347 PrintWriter pw = response.getWriter();
348
349 pw.append("General Info: Number of HTRC Volumes in check-list = " + id_check_.size());
350
351 }
352 //pw.close();
353
354 }
355
356 /**
357 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
358 */
359 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
360 doGet(request, response);
361 }
362
363}
Note: See TracBrowser for help on using the repository browser.