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

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

Make workset download save as file

  • Property svn:executable set to *
File size: 11.1 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("\\+", ":").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.print(".");
115 }
116 line_num++;
117
118 }
119 System.err.println(" => done.");
120 }
121 catch (Exception e) {
122 e.printStackTrace();
123 }
124
125 }
126 /**
127 * @see Servlet#init(ServletConfig)
128 */
129 public void init(ServletConfig config) throws ServletException {
130 super.init(config);
131
132 if (id_check_ == null) {
133 id_check_ = new HashMap<String,Boolean>(HASHMAP_INIT_SIZE);
134
135 String htrc_list_file = "htrc-ef-all-files.txt";
136 InputStream is = getServletContext().getResourceAsStream("/WEB-INF/" + htrc_list_file);
137
138 try {
139 System.err.println("INFO: Loading in volume IDS: " + htrc_list_file);
140
141 InputStreamReader isr = new InputStreamReader(is, "UTF-8");
142 BufferedReader br = new BufferedReader(isr);
143
144 storeIDs(br);
145 br.close();
146 }
147 catch (Exception e) {
148 e.printStackTrace();
149 }
150 }
151 }
152
153 protected BufferedInputStream doRsyncDownload(String full_json_filename)
154 {
155 String json_filename_tail = full_filename_to_tail(full_json_filename);
156
157 BufferedInputStream bis = null;
158
159 Runtime runtime = Runtime.getRuntime();
160 String[] rsync_command = {"rsync","-av","data.analytics.hathitrust.org::features/" + full_json_filename, "."};
161
162 try {
163 Process proc = runtime.exec(rsync_command);
164 proc.waitFor();
165
166 FileInputStream fis = new FileInputStream(json_filename_tail);
167 bis = new BufferedInputStream(fis);
168
169 }
170 catch (Exception e) {
171 e.printStackTrace();
172 }
173
174 return bis;
175
176 }
177
178 protected void doCollectionToWorkset(HttpServletResponse response, String col_title,
179 String c, String a, String format) throws IOException
180 {
181 String post_url_params = "c="+c+"&a="+a+"&format="+format;
182
183 byte[] post_data = post_url_params.getBytes(StandardCharsets.UTF_8);
184 int post_data_len = post_data.length;
185
186 try {
187
188 URL post_url = new URL(ht_col_url);
189 HttpURLConnection conn = (HttpURLConnection) post_url.openConnection();
190 conn.setDoOutput(true);
191 conn.setInstanceFollowRedirects(false);
192 conn.setRequestMethod("POST");
193 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
194 conn.setRequestProperty("charset", "utf-8");
195 conn.setRequestProperty("Content-Length", Integer.toString(post_data_len));
196 conn.setUseCaches(false);
197
198 try(DataOutputStream dos = new DataOutputStream(conn.getOutputStream())) {
199 dos.write(post_data);
200 }
201 // try-resource auto-closes stream
202
203 InputStream is = conn.getInputStream();
204 InputStreamReader isr = new InputStreamReader(is);
205 BufferedReader reader = new BufferedReader(isr);
206
207 StringBuilder workset_friendly_sb = new StringBuilder();
208 StringBuilder workset_unfriendly_sb = new StringBuilder();
209
210 String line = null;
211 int ci = 0;
212 while ((line = reader.readLine()) != null)
213 {
214 if (ci==0) {
215 workset_friendly_sb.append("#" + line + "\n");
216 }
217 else {
218 int first_tab_pos=line.indexOf("\t");
219 String id = (first_tab_pos>0) ? line.substring(0, first_tab_pos) : line;
220
221 if (id_check_.containsKey(id)) {
222 workset_friendly_sb.append(line + "\n");
223 }
224 else {
225 workset_unfriendly_sb.append("#" + line + "\n");
226 }
227 }
228
229 ci++;
230 }
231
232 String col_title_filename = col_title + ".txt";
233 response.setContentType("text/plain");
234 response.setHeader("Content-Disposition", "attachment; filename=\"" + col_title_filename + "\"");
235
236 PrintWriter pw = response.getWriter();
237 pw.append(workset_friendly_sb.toString());
238
239 if (workset_unfriendly_sb.length()>0) {
240 pw.append("## The following volumes were listed in the HT collection, but have been omitted as they are not in the HTRC Extracted Feature dataset\n");
241 pw.append(workset_unfriendly_sb.toString());
242 }
243 pw.flush();
244 }
245 catch (Exception e) {
246 e.printStackTrace();
247 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Failed to convert HT collection to HTRC workset");
248 }
249
250 }
251 /**
252 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
253 */
254 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
255 {
256 String cgi_ids = request.getParameter("ids");
257 String cgi_id = request.getParameter("id");
258 String cgi_download_id = request.getParameter("download-id");
259 String cgi_convert_col = request.getParameter("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_.containsKey(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_.containsKey(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_.containsKey(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
334 String cgi_col_title = request.getParameter("col-title");
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 if (cgi_col_title == null) {
343 cgi_col_title = "htrc-workset-" + cgi_convert_col;
344 }
345
346 doCollectionToWorkset(response,cgi_col_title,cgi_convert_col,cgi_a,cgi_format);
347 }
348
349 }
350 else {
351 PrintWriter pw = response.getWriter();
352
353 pw.append("General Info: Number of HTRC Volumes in check-list = " + id_check_.size());
354
355 }
356 //pw.close();
357
358 }
359
360 /**
361 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
362 */
363 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
364 doGet(request, response);
365 }
366
367}
Note: See TracBrowser for help on using the repository browser.