Advertisement
Guest User

elasticsearch_servlet

a guest
Apr 25th, 2017
580
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 109.94 KB | None | 0 0
  1. package net.cfday.rwise.sstservlet;
  2.  
  3. import java.io.BufferedReader;
  4. import net.cfday.rwise.Exporter;
  5. import net.cfday.rwise.dataconversion.ConversionException;
  6. import net.cfday.rwise.db.utils.s3.S3Extractor;
  7. import net.cfday.rwise.s3datascavenger.UserCreator;
  8. import net.cfday.rwise.sst_servlet_backend.HbaseTablesFacetModifer.Modifier;
  9. import org.apache.logging.log4j.LogManager;
  10. import org.apache.logging.log4j.Logger;
  11. import org.apache.solr.client.solrj.SolrQuery;
  12. import org.apache.solr.client.solrj.SolrQuery.SortClause;
  13. import org.apache.solr.client.solrj.SolrServerException;
  14. import org.apache.solr.client.solrj.impl.CloudSolrClient;
  15. import org.apache.solr.client.solrj.request.LukeRequest;
  16. import org.apache.solr.client.solrj.response.FacetField;
  17. import org.apache.solr.client.solrj.response.FacetField.Count;
  18. import org.apache.solr.client.solrj.response.LukeResponse;
  19. import org.apache.solr.client.solrj.response.LukeResponse.FieldInfo;
  20. import org.apache.solr.client.solrj.response.QueryResponse;
  21. import org.apache.solr.common.SolrDocument;
  22. import org.apache.solr.common.SolrDocumentList;
  23. import org.apache.solr.common.SolrInputDocument;
  24. import org.apache.solr.common.params.CursorMarkParams;
  25. import org.codehaus.jettison.json.JSONArray;
  26. import org.codehaus.jettison.json.JSONException;
  27. import org.codehaus.jettison.json.JSONObject;
  28. import org.joda.time.DateTime;
  29. import org.joda.time.format.DateTimeFormatter;
  30. import org.joda.time.format.ISODateTimeFormat;
  31. import org.springframework.context.ApplicationContext;
  32. import org.springframework.context.support.ClassPathXmlApplicationContext;
  33.  
  34. import javax.mail.*;
  35. import javax.mail.internet.InternetAddress;
  36. import javax.mail.internet.MimeMessage;
  37. import javax.servlet.ServletException;
  38. import javax.servlet.http.HttpServlet;
  39. import javax.servlet.http.HttpServletRequest;
  40. import javax.servlet.http.HttpServletResponse;
  41. import java.io.File;
  42. import java.io.IOException;
  43. import java.io.InputStreamReader;
  44. import java.io.PrintWriter;
  45. import java.net.URL;
  46. import java.net.URLDecoder;
  47. import java.util.*;
  48. import java.util.Map.Entry;
  49. import java.util.logging.Level;
  50. import javax.servlet.ServletConfig;
  51. import net.cfday.rwise.db.utils.esearch.ElasticSearchConnection;
  52. import net.cfday.rwise.db.utils.esearch.ElasticSearchConnector;
  53. import org.apache.http.client.methods.HttpPost;
  54. import org.json.simple.parser.ParseException;
  55. import rwise.database.DataService;
  56. import rwise.database.Datum;
  57.  
  58. public class ElasticSearch_Servlet extends HttpServlet {
  59. ElasticSearchConnection elasticSearchConnection;
  60.  
  61. private static final Logger logger = LogManager.getLogger(Servlet.class);
  62.  
  63. public static JSONArray parsePostResponse(String responseFromQuery) throws JSONException {
  64. JSONObject responseJson = new JSONObject(responseFromQuery);
  65. // System.out.println(responseJson);
  66. // for (Object key : responseJson.keySet()){
  67. // Object value = responseJson.get(key);
  68. // System.out.println(key + " <:> " + value);
  69. // }
  70.  
  71. JSONObject hitsJsonObject = (JSONObject) responseJson.get("hits");
  72. JSONArray hitsJsonArray = (JSONArray) hitsJsonObject.get("hits");
  73. JSONArray databaseRows = new JSONArray();
  74. for (int i = 0; i < hitsJsonArray.length(); i++) {
  75. JSONObject hitJsonObject = (JSONObject) hitsJsonArray.get(i);
  76. // System.out.println(hitObject);
  77. /*
  78. The information that we actually write ourselves into the database is stored under the _source field.
  79. I'm bringing that information out and sticking it into the outer level where the _* fields are at.
  80. Basically i'm getting rid of the extra JSONObject and just lumping it all together.
  81. */
  82. JSONObject databaseRow = (JSONObject) hitJsonObject.get("_source");
  83. hitJsonObject.remove("_source");
  84. Iterator databaseRowKeysIterator = databaseRow.keys();
  85. while (databaseRowKeysIterator.hasNext()) {
  86. String key = (String) databaseRowKeysIterator.next();
  87. Object value = databaseRow.get(key);
  88. hitJsonObject.put(key, value);
  89. }
  90.  
  91. databaseRows.put(hitJsonObject);
  92. // System.out.println(hitJsonObject);
  93. databaseRowKeysIterator = databaseRow.keys();
  94. while (databaseRowKeysIterator.hasNext()) {
  95. String databaseRowKey = (String) databaseRowKeysIterator.next();
  96. Object databaseRowValue = databaseRow.get(databaseRowKey);
  97. // System.out.println(databaseRowKeyString + "<:>" + databaseRowValue);
  98. }
  99. // System.out.println("\n\n");
  100. Iterator hitJsonObjectIterator = hitJsonObject.keys();
  101. while (hitJsonObjectIterator.hasNext()) {
  102. String hitKey = (String) hitJsonObjectIterator.next();
  103. Object hitValue = hitJsonObject.get(hitKey);
  104. // System.out.println(hitKeyString + " <:> " + hitValueObject);
  105. }
  106. // System.out.println("\n\n");
  107. }
  108. hitsJsonObject = null;
  109. hitsJsonArray = null;
  110.  
  111. return databaseRows;
  112. }
  113.  
  114. public static void printClassTypesForParsedPostResponseFieldsAndValues(JSONArray parsedPostResponse) throws JSONException {
  115. for (int i = 0; i < parsedPostResponse.length(); i++) {
  116. JSONObject databaseRowJsonObject = (JSONObject) parsedPostResponse.get(i);
  117. Iterator databaseRowIterator = databaseRowJsonObject.keys();
  118. while (databaseRowIterator.hasNext()) {
  119. String databaseRowKeyObject = (String) databaseRowIterator.next();
  120. Object databaseRowValueObject = databaseRowJsonObject.get(databaseRowKeyObject);
  121. System.out.println(databaseRowKeyObject.getClass() + " {" + databaseRowKeyObject + "} <:> " + databaseRowValueObject.getClass() + " {" + databaseRowValueObject + "}");
  122. }
  123. System.out.println("\n");
  124. }
  125. }
  126.  
  127. @Override
  128. public void init(ServletConfig config) throws ServletException {
  129. super.init(config);
  130. elasticSearchConnection = (ElasticSearchConnection) new ElasticSearchConnector().connect();
  131. elasticSearchConnection.setIndex("artifact");
  132. elasticSearchConnection.setType("data");
  133. }
  134.  
  135. private static List<String> getStrs(String key, SolrDocument doc) {
  136. List<String> out = new ArrayList<>();
  137. List<String> tmpList = (List) doc.get(key);
  138. if (tmpList == null) {
  139. return null;
  140. }
  141. Set<String> tmpSet = new HashSet<>();
  142. tmpSet.addAll(tmpList);
  143. out.addAll(tmpSet);
  144. return out;
  145. }
  146.  
  147. private static String getStr(String key, SolrDocument doc) {
  148. String out;
  149. Object valueObj = doc.get(key);
  150. if (valueObj == null) {
  151. return null;
  152. }
  153. if (valueObj.getClass().toString().toLowerCase().contains("array")
  154. || valueObj.getClass().toString().toLowerCase().contains("list")) {
  155. out = (String) ((List) valueObj).get(0);
  156. } else {
  157. out = (String) doc.get(key);
  158. }
  159. return out;
  160. }
  161.  
  162. private static void printOutHttpServletRequest(HttpServletRequest request) {
  163. Enumeration params = request.getParameterNames();
  164. while (params.hasMoreElements()) {
  165. String paramName = (String) params.nextElement();
  166. String[] parameterValues = request.getParameterValues(paramName);
  167. System.out.println("Parameter Name - " + paramName);
  168. System.out.print("\tValue - {");
  169. for (String parameterValue : parameterValues) {
  170. System.out.print(parameterValue + " <:> ");
  171. }
  172. System.out.print("}\n");
  173. }
  174. }
  175.  
  176. public String unescapeJsonToStringString(String jsonToString) {
  177. //These cases I got from json.org
  178. jsonToString = jsonToString.replace("\\\\", "\\"); //replace escaped backslash with single backslash
  179. jsonToString = jsonToString.replace("\\/", "/"); //replace escaped forwardslash with a single forwardslash
  180. jsonToString = jsonToString.replaceAll("\\\\u[0-9]{4}", "");//removes hex coded things
  181. jsonToString = jsonToString.replace("\\b", ""); //remove break
  182. jsonToString = jsonToString.replace("\\f", ""); //remove next page
  183. jsonToString = jsonToString.replace("\\n", ""); //remove new line
  184. jsonToString = jsonToString.replace("\\r", ""); //remove carriage return
  185. jsonToString = jsonToString.replace("\\t", ""); //remove tab
  186. return jsonToString;
  187. }
  188.  
  189. public String findNameAlternatives(JSONObject databaseRow, String art_name_str) throws JSONException {
  190. String s3FilePath = databaseRow.getString("art_s3FilePath_pth");
  191. File docAsFile = new File(s3FilePath);
  192. if (art_name_str == null) {
  193. if (databaseRow.isNull("art_title_str")) {
  194. if (databaseRow.isNull("art_subject_str")) {
  195. if (databaseRow.isNull("ind_author_str")) {
  196. if (databaseRow.isNull("art_fileName_str")){
  197. art_name_str = docAsFile.getName();
  198. } else {
  199. art_name_str = databaseRow.getString("art_fileName_str");
  200. }
  201. } else {
  202. art_name_str = databaseRow.getString("ind_author_str");
  203. }
  204. } else {
  205. art_name_str = databaseRow.getString("art_subject_str");
  206. }
  207. } else {
  208. art_name_str = databaseRow.getString("art_title_str");
  209. }
  210. }
  211.  
  212. if (art_name_str == null || art_name_str.equals("null")) {
  213. art_name_str = databaseRow.getString("id"); //utter last resort
  214. }
  215. return art_name_str;
  216. }
  217.  
  218. public void addAdditionalDataForSidePanelToJsonResponseForDatabaseRow(JSONObject jsonResponseForThisDatabaseRow, JSONObject databaseRow) throws JSONException {
  219. String id = databaseRow.getString("id");
  220. try {
  221. String fileType = jsonResponseForThisDatabaseRow.getString("fileType");
  222. if (fileType.startsWith("rtf") || fileType.startsWith("email")) {
  223. try {
  224. if (!databaseRow.isNull("ind_sender_strs")) {
  225. JSONArray sender = databaseRow.getJSONArray("ind_sender_strs");
  226. jsonResponseForThisDatabaseRow.put("sender", sender);
  227. } else {
  228. }
  229. if (!databaseRow.isNull("ind_recipient_strs")) {
  230. JSONArray recepient = databaseRow.getJSONArray("ind_recipient_strs");
  231. jsonResponseForThisDatabaseRow.put("recipients", recepient);
  232. } else {
  233. }
  234. if (!databaseRow.isNull("art_date_dte")) {
  235. Object sentDate = (Date) databaseRow.get("art_date_dte");
  236. jsonResponseForThisDatabaseRow.put("sentDate", sentDate);
  237. } else {
  238. }
  239. } catch (Throwable th) {
  240. // System.out.println("WARNING:Failed to add additional information fields for this email solr document with id " + id);
  241. }
  242. } else if (fileType.startsWith("zip")) {
  243. try {
  244. int zippedFileCount = databaseRow.getInt("art_attachmentIndex_int");
  245. jsonResponseForThisDatabaseRow.put("zippedFilesCount", zippedFileCount);
  246. if (!databaseRow.isNull("ind_author_str")) {
  247. String createdBy = databaseRow.getString("ind_author_str");
  248. jsonResponseForThisDatabaseRow.put("createdBy", createdBy);
  249. } else {
  250. }
  251. if (!databaseRow.isNull("art_creationTime_dte")) {
  252. Object creationDate = databaseRow.get("art_creationTime_dte");
  253. jsonResponseForThisDatabaseRow.put("creationDate", creationDate);
  254. } else {
  255. }
  256. } catch (Throwable th) {
  257. // System.out.println("WARNING:Failed to add additional information fields for this zip solr document with id " + id);
  258. }
  259. } else if (fileType.startsWith("html")) {
  260. if (!databaseRow.isNull("art_artifactType_str") && databaseRow.getString("art_artifactType_str").equals("p3 web")) {
  261. String art_artifactType_str = databaseRow.getString("art_artifactType_str");
  262. if (!databaseRow.isNull("art_question_str")) {
  263. String art_question_str = databaseRow.getString("art_question_str");
  264. jsonResponseForThisDatabaseRow.put("p3Question", art_question_str);
  265. }
  266. if (!databaseRow.isNull("art_url_str")) {
  267. String art_url_str = databaseRow.getString("art_url_str");
  268. jsonResponseForThisDatabaseRow.put("URL", art_url_str);
  269. }
  270. }
  271. } else {
  272. try {
  273. if (!databaseRow.isNull("art_creationTime_dte")) {
  274. Object creationDate = databaseRow.get("art_creationTime_dte");
  275. jsonResponseForThisDatabaseRow.put("creationDate", creationDate);
  276. } else {
  277. }
  278. if (!databaseRow.isNull("ind_author_str")) {
  279. String createdBy = databaseRow.getString("ind_author_str");
  280. jsonResponseForThisDatabaseRow.put("createdBy", createdBy);
  281. } else {
  282. }
  283. } catch (Throwable th) {
  284. // System.out.println("WARNING:Failed to add additional information fields for this solr document with id " + id);
  285. }
  286. }
  287. } catch (Throwable th) {
  288. // System.out.println("WARNING:Failed to add additional infomration at all for this solr document with id " + id);
  289. }
  290. }
  291.  
  292. public ArrayList<String> parseFoldersString(String folderPath, String userId) {
  293. // TODO: Do you really want to modify the folderPath parameter or are you just reusing a variable?
  294. if (!folderPath.startsWith("/")) {
  295. folderPath = "/" + folderPath;
  296. }
  297.  
  298. if (folderPath.startsWith("/P3/" + userId + "/P3")) {
  299. folderPath = folderPath.replaceFirst("/P3/" + userId + "/P3", "/P3");
  300. } else if (folderPath.startsWith("/" + userId + "/P3")) {
  301. folderPath = folderPath.replaceFirst("/" + userId + "/P3", "/P3"); //not sure this case ever exists
  302. } else if (folderPath.startsWith("/" + userId)) {
  303. folderPath = folderPath.replaceFirst("/" + userId, "");
  304. }
  305.  
  306.  
  307. ArrayList<String> listOfFolders = new ArrayList<>();
  308. File folder = new File(folderPath);
  309. String folderName = folder.getName();
  310.  
  311. if (folderName.equals("cfday-demo") || folderName.equals("enronDemo"))//SUPER HACKISH!
  312. {
  313. return listOfFolders;
  314. }
  315.  
  316. File parentFolder = folder.getParentFile();
  317. if (parentFolder != null) {
  318. String parentFolderName = parentFolder.getName();
  319. String parentFolderPath = parentFolder.getPath();
  320. listOfFolders.addAll(parseFoldersString(parentFolderPath, userId));
  321. }
  322. if (!folderName.isEmpty()) {
  323. listOfFolders.add(folderName);
  324. }
  325. return listOfFolders;
  326. }
  327.  
  328. public JSONObject editQuery(HttpServletRequest request, String requestType) throws JSONException, SolrServerException, IOException {
  329. JSONObject response = new JSONObject();
  330. String visibility = request.getParameter("private");
  331. String creator_name = request.getParameter("creator_name");
  332. String action = request.getParameter("action");
  333. CloudSolrClient queriesServer = new CloudSolrClient("localhost:11093");
  334. queriesServer.setDefaultCollection("facetted_queries");
  335. /*
  336. Nothing crazy here, just need somethign to put stuff into and get queries that arleady exist by id. Delete them b id too.
  337. */
  338.  
  339. if (action.equals("saveTarget")) {
  340. DateTimeFormatter dtf = ISODateTimeFormat.dateTimeNoMillis();
  341. String creation_date = dtf.print(DateTime.now());
  342. SolrInputDocument sdoc = new SolrInputDocument();
  343. sdoc.setField("art_visibility_str", visibility);
  344. sdoc.setField("art_creationDate_dte", creation_date);
  345. sdoc.setField("ind_creatorName_str", creator_name);
  346.  
  347. String name = request.getParameter("name");
  348. String description = request.getParameter("description");
  349. String data = request.getParameter("facetData");
  350. String id = creator_name + "|" + name;
  351. sdoc.setField("id", id);
  352. sdoc.setField("art_targetName_str", name);
  353. sdoc.setField("art_targetDescription_str", description);
  354. sdoc.setField("art_dataBlob_str", data);
  355.  
  356. queriesServer.add(sdoc);
  357. } else if (action.equals("deleteTarget")) {
  358. String id = request.getParameter("id");
  359. SolrDocument solrDocument = queriesServer.getById(id);
  360. String requesterName = request.getParameter("username");
  361. String creatorFromSolr = getStr("ind_creatorName_str", solrDocument);
  362. if (creatorFromSolr.equals(requesterName)) {
  363. queriesServer.deleteById(id);
  364. } else {
  365. JSONArray errors = new JSONArray();
  366. errors.put(new JSONObject().put("statusCode", "409"));
  367. errors.put(new JSONObject().put("errorMessage", "User does not have permission to delete this row. Creator name in database does not match user name!"));
  368. response.put("errors", errors);
  369. }
  370. }
  371. queriesServer.commit();
  372. queriesServer.close(); // TODO: Use SolrConnection or at least use try-with-resources. (Hey, Java 8 is out now, might start using Java 7 features before we are totally out of date.)
  373.  
  374. response.put("status", "complete");
  375. return response;
  376. }
  377.  
  378. public JSONArray parseFolderFacetFieldForFileNavTojson(JSONObject databaseRow, String baseFolderPath, String userId) throws JSONException {
  379. /*
  380. I don't seem to do anythin with the solr client dspite passing it in.
  381. */
  382. LinkedHashMap<String, Integer> uniqueFolderPaths = new LinkedHashMap<>();
  383. JSONArray response = new JSONArray();
  384. JSONArray buckets = databaseRow.getJSONObject("aggregations").getJSONObject("art_s3FileParentFolderPath_pth").getJSONArray("buckets");
  385. logger.debug("Found " + buckets.length() + " different values of facet information");
  386. for (int i = 0; i < buckets.length(); i++) {
  387. JSONObject bucket = buckets.getJSONObject(i);
  388. int fileCount = bucket.getInt("doc_count");
  389. if (fileCount < 1)
  390. continue;
  391. String filePath = bucket.getString("key");
  392. if (filePath.startsWith("P3/")) {
  393. filePath = filePath.replaceFirst("P3/", "");
  394. }
  395. if (!filePath.startsWith("/")) {
  396. filePath = "/" + filePath;
  397. }
  398.  
  399. File folderFile = new File(filePath);
  400. if (!baseFolderPath.startsWith("/")) {
  401. // TODO: Do you really want to modify the parameter baseFolderPath or are you just reusing a variable?
  402. baseFolderPath = "/" + baseFolderPath;
  403. }
  404.  
  405. ArrayList<File> folderHierarchy = new ArrayList<File>(); //break it up into a hiearchy. so take something lke /folder1/folder2/folder and turn it into /folder1, /folder1/folder2, /folder1/folder2/folder3
  406. while (folderFile.getParentFile()!=null){
  407. folderHierarchy.add(folderFile);
  408. folderFile = folderFile.getParentFile();
  409. }
  410. File baseFolderFile = new File(baseFolderPath);
  411. for (File folder : folderHierarchy) {
  412. if (folder.getParentFile().compareTo(baseFolderFile) == 0) //If the parent of this folder is the same as the base folder, then we know it's only 1 level out
  413. {
  414. Integer count = uniqueFolderPaths.get(folder.getAbsolutePath());
  415. if (count == null)
  416. uniqueFolderPaths.put(folder.getAbsolutePath(), fileCount);
  417. else
  418. uniqueFolderPaths.put(folder.getAbsolutePath(), fileCount + count);
  419. }
  420. }
  421. }
  422.  
  423. for (Map.Entry<String, Integer> folderInfo : uniqueFolderPaths.entrySet()) {
  424. Integer fileCount = folderInfo.getValue();
  425. String folderPath = folderInfo.getKey();
  426. File folder = new File(folderPath);
  427. String filename = folder.getName();
  428. File parentFolder = folder.getParentFile();
  429. String parentFolderPath = parentFolder.getPath();
  430.  
  431. JSONObject folderJsonObject = new JSONObject();
  432. folderJsonObject.put("id", folderPath);
  433. folderJsonObject.put("fileType", "dir");
  434. folderJsonObject.put("name", filename);
  435. folderJsonObject.put("fileCount", fileCount);
  436. folderJsonObject.put("path", folderPath);
  437. ArrayList<String> parsedFolders = parseFoldersString(parentFolderPath, userId);
  438. parsedFolders.removeIf(Objects::isNull);
  439. folderJsonObject.put("parentFolders", parsedFolders);
  440. folderJsonObject.put("viewable", "false");
  441. response.put(folderJsonObject);
  442. }
  443. return response;
  444. }
  445.  
  446. public JSONObject parseEmailAsFolderForFileNavToJson(JSONObject databaseRow, String userId) throws JSONException {
  447. String s3FilePath = databaseRow.getString("art_s3FilePath_pth");
  448. if (!s3FilePath.startsWith("/")) {
  449. s3FilePath = "/" + s3FilePath; //Adding an initial "/" incase the solr field value doesn't start with one.
  450. }
  451. String id = databaseRow.getString("id");
  452. String name = null;
  453. if (databaseRow.isNull("art_title_str")) {
  454. name = findNameAlternatives(databaseRow, name);
  455. } else {
  456. name = databaseRow.getString("art_title_str");
  457. }
  458. name = name + ".email";
  459. Integer art_numAttachments_int = 0;
  460. if (databaseRow.has("art_numAttachments_int") && databaseRow.get("art_numAttachments_int") != null)
  461. art_numAttachments_int = databaseRow.getInt("art_numAttachments_int");
  462. String art_s3FileParentFolderPath_pth = databaseRow.getString("art_s3FileParentFolderPath_pth");
  463.  
  464. JSONObject response = new JSONObject();
  465. response.put("id", id);
  466. response.put("fileType", "email");
  467. response.put("name", name);
  468. response.put("fileCount", art_numAttachments_int);
  469. response.put("path", s3FilePath);
  470. ArrayList<String> parentFoldersArrayList = parseFoldersString(art_s3FileParentFolderPath_pth, userId);
  471. parentFoldersArrayList.removeIf(Objects::isNull);
  472. JSONArray parentFoldersJSONArray = new JSONArray(parentFoldersArrayList);
  473. response.put("parentFolders", parentFoldersJSONArray);
  474. response.put("viewable", "false");
  475. return response;
  476. }
  477.  
  478. public JSONObject parseForFileNavToJson(JSONObject databaseRow, String userId) throws JSONException {
  479. /*
  480. Again not using the facettedServer thing, whaaaat was i doin with my life that I made these decisiions.
  481. */
  482. String id = databaseRow.getString("id");
  483. String art_fileType_str = databaseRow.getString("art_fileType_str");
  484. String art_isViewable_bool = databaseRow.getString("art_isViewable_str");
  485. String art_contentHash_str = databaseRow.getString("art_contentHash_str");
  486.  
  487. String s3FilePath = databaseRow.getString("art_s3FilePath_pth");
  488. if (!s3FilePath.startsWith("/")) {
  489. s3FilePath = "/" + s3FilePath; //Adding an initial "/" incase the solr field value doesn't start with one.
  490. }
  491. String art_s3FileParentFolderPath_pth = databaseRow.getString("art_s3FileParentFolderPath_pth");
  492.  
  493. String art_artifactType_str = databaseRow.getString("art_artifactType_str");
  494. if (!art_artifactType_str.equals("attachment") && art_fileType_str.equals("pst")) {
  495. return null;
  496. }
  497.  
  498. String art_name_str = null;
  499. if (databaseRow.isNull("art_title_str")) {
  500. art_name_str = findNameAlternatives(databaseRow, art_name_str);
  501. } else {
  502. art_name_str = databaseRow.getString("art_title_str");
  503. }
  504.  
  505. int art_fileSize_int;
  506. if (!databaseRow.isNull("art_fileSize_int")) {
  507. art_fileSize_int = databaseRow.getInt("art_fileSize_int");
  508. } else {
  509. art_fileSize_int = 0;
  510. }
  511. String art_fileSize_str = String.valueOf(art_fileSize_int);
  512.  
  513. JSONObject jsonResponseForThisDatabaseRow = new JSONObject();
  514. jsonResponseForThisDatabaseRow.put("id", id);
  515. jsonResponseForThisDatabaseRow.put("fileType", art_fileType_str);
  516. jsonResponseForThisDatabaseRow.put("name", art_name_str);
  517. jsonResponseForThisDatabaseRow.put("path", s3FilePath);
  518. ArrayList<String> parsedFolders = parseFoldersString(art_s3FileParentFolderPath_pth, userId);
  519. parsedFolders.removeIf(Objects::isNull);
  520. jsonResponseForThisDatabaseRow.put("parentFolders", parsedFolders);
  521. jsonResponseForThisDatabaseRow.put("viewable", art_isViewable_bool);
  522. jsonResponseForThisDatabaseRow.put("fileSize", art_fileSize_str);
  523. jsonResponseForThisDatabaseRow.put("contentHash", art_contentHash_str);
  524. return jsonResponseForThisDatabaseRow;
  525. }
  526.  
  527. public JSONObject parseAttachmentDatabaseRowForFileNavToJson(JSONObject databaseRow, String emailName, String userId) throws JSONException {
  528. /*
  529. Not using the connnnnecttttttionnn to solrrrrrrrrrr
  530. */
  531. String id = databaseRow.getString("id");
  532. String art_isViewable_bool = databaseRow.getString("art_isViewable_str");
  533. String art_fileType_str = "file";
  534. if (databaseRow.has("art_fileType_str") && databaseRow.get("art_fileType_str") != null)
  535. art_fileType_str = databaseRow.getString("art_fileType_str");
  536. String art_contentHash_str = "000";
  537. if (databaseRow.has("art_contentHash_str") && databaseRow.get("art_contentHash_str") != null)
  538. art_contentHash_str = databaseRow.getString("art_contentHash_str");
  539.  
  540. String s3FilePath = databaseRow.getString("art_s3FilePath_pth");
  541. String art_s3FileParentFolderPath_pth = databaseRow.getString("art_s3FileParentFolderPath_pth");
  542. if (!s3FilePath.startsWith("/")) {
  543. s3FilePath = "/" + s3FilePath; //Adding an initial "/" incase the solr field value doesn't start with one.
  544. }
  545. File docAsFile = new File(s3FilePath);
  546. String docAsFileName = docAsFile.getName();
  547. String pathToFileAsIfItWereInTheCorrectFolderStructureAndNotLikeItIsWhereItIsPlacedInsideAPstThatIsOnTheRootFolderWhereInRealityThePstCouldBeWithinASeriesOfFolders = art_s3FileParentFolderPath_pth + "/" + docAsFileName;
  548. docAsFile = new File(pathToFileAsIfItWereInTheCorrectFolderStructureAndNotLikeItIsWhereItIsPlacedInsideAPstThatIsOnTheRootFolderWhereInRealityThePstCouldBeWithinASeriesOfFolders);
  549.  
  550. String art_artifactType_str = databaseRow.getString("art_artifactType_str");
  551. if (!art_artifactType_str.equals("attachment") && art_fileType_str.equals("pst")) {
  552. return null;
  553. }
  554.  
  555. String art_name_str = null;
  556. if (databaseRow.isNull("art_title_str")) {
  557. art_name_str = findNameAlternatives(databaseRow, art_name_str);
  558. } else {
  559. art_name_str = databaseRow.getString("art_title_str");
  560. }
  561. if (art_artifactType_str.equals("email")) {
  562. art_name_str = art_name_str + ".email";
  563. }
  564.  
  565. long art_fileSize_int;
  566. if (!databaseRow.isNull("art_fileSize_int")) {
  567. art_fileSize_int = databaseRow.getInt("art_fileSize_int");
  568. } else {
  569. art_fileSize_int = 0;
  570. }
  571. String art_fileSize_str = String.valueOf(art_fileSize_int);
  572.  
  573. JSONObject jsonResponseForThisDatabaseRow = new JSONObject();
  574. jsonResponseForThisDatabaseRow.put("id", id);
  575. jsonResponseForThisDatabaseRow.put("fileType", art_fileType_str);
  576. jsonResponseForThisDatabaseRow.put("name", art_name_str);
  577. jsonResponseForThisDatabaseRow.put("path", s3FilePath);
  578. ArrayList<String> parentFoldersArrayList = parseFoldersString(art_s3FileParentFolderPath_pth, userId);
  579. parentFoldersArrayList.removeIf(Objects::isNull);
  580. parentFoldersArrayList.add(emailName);
  581. jsonResponseForThisDatabaseRow.put("parentFolders", new JSONArray(parentFoldersArrayList));
  582. jsonResponseForThisDatabaseRow.put("viewable", art_isViewable_bool);
  583. jsonResponseForThisDatabaseRow.put("fileSize", art_fileSize_str);
  584. addAdditionalDataForSidePanelToJsonResponseForDatabaseRow(jsonResponseForThisDatabaseRow, databaseRow);
  585. jsonResponseForThisDatabaseRow.put("contentHash", art_contentHash_str);
  586. return jsonResponseForThisDatabaseRow;
  587. }
  588.  
  589. public class FacetEdittingWorkerThread extends Thread {
  590.  
  591. String oldFacetValue, newFacetValue, oldFacetField, newFacetField, solrCollectionDbName, username;
  592. Map<String, ArrayList<String>> facetFieldToSourceFieldsMapping;
  593. Map<String, String> facetFieldToSuffixMapping;
  594. ArrayList<String> sourceFieldsList = new ArrayList<>();
  595. int rows;
  596.  
  597. public FacetEdittingWorkerThread(String oldFacetValue, String newFacetValue, String oldFacetField, String newFacetField, String solrCollectionDbName, String username, Map<String, ArrayList<String>> facetFieldToSourceFieldsMapping, Map<String, String> facetFieldToSuffixMapping, int rows) {
  598. this.oldFacetValue = oldFacetValue;
  599. this.newFacetValue = newFacetValue;
  600. this.oldFacetField = oldFacetField;
  601. this.newFacetField = newFacetField;
  602. this.solrCollectionDbName = solrCollectionDbName;
  603. this.username = username;
  604. this.facetFieldToSourceFieldsMapping = facetFieldToSourceFieldsMapping;
  605. this.facetFieldToSuffixMapping = facetFieldToSuffixMapping;
  606. for (ArrayList<String> sourceFields : this.facetFieldToSourceFieldsMapping.values()) {
  607. sourceFieldsList.addAll(sourceFields);
  608. }
  609. this.rows = rows;
  610. }
  611.  
  612. @Override
  613. public void run() {
  614. // TODO: Modularize this code and then use SolrConnection. At least use try-with-resources!
  615. CloudSolrClient facettedServer = new CloudSolrClient("localhost:11093");
  616. facettedServer.setDefaultCollection((solrCollectionDbName));
  617. String cursorMark = CursorMarkParams.CURSOR_MARK_START;
  618. SolrQuery query = new SolrQuery(oldFacetField + ":\"" + oldFacetValue + "\"");
  619. query.setRows(rows);
  620. query.setFields(oldFacetField, facettedServer.getIdField(), "_version_");
  621. for (String field : sourceFieldsList) {
  622. query.addField(field);
  623. }
  624. query.setSort(SortClause.asc("id"));
  625. query.addSort(SortClause.asc("_version_"));
  626. query.addFilterQuery("art_username_str:\"" + username + "\"");
  627. try {
  628. boolean done = false;
  629. ArrayList<SolrInputDocument> sdocs = new ArrayList<>();
  630. while (!done) {
  631. query.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark);
  632. System.out.println("Querying solr with " + query);
  633. QueryResponse response = facettedServer.query(query);
  634. String nextCursorMark = response.getNextCursorMark();
  635. SolrDocumentList docs = response.getResults();
  636.  
  637. System.out.println("Docsize is " + docs.size() + " NumFound is " + docs.getNumFound());
  638. for (SolrDocument doc : docs) {
  639. String id = getStr(facettedServer.getIdField(), doc);
  640. Map<String, Object> fieldModifier;
  641. SolrInputDocument sdoc = new SolrInputDocument();
  642. sdoc.setField(facettedServer.getIdField(), id);
  643. if (!newFacetValue.equals(oldFacetValue) && !newFacetValue.equals("")) {
  644. //The facet values are different, so we are changing the values. Check to see if we are also changing the facet field.
  645. if (!newFacetField.equals(oldFacetField) && !newFacetField.equals("")) {
  646. //The facet fields are also different, so we are changing both the facet values AND the facet fields
  647. //Go through every possible source field, for the particular copy field destination that is oldFacetField.
  648. //For every source, see if it has the oldFacetValue we are looking for
  649. //If it does, remove the old value
  650. //an additional check has to be made to see if we are dealing with a multi valued list. If we are, check each value for the old facet value
  651. //If it is a multi valued list, grab the whole list, remove the unwanted value, and then do a set.
  652. ArrayList<String> oldFacetFieldSourceFields = facetFieldToSourceFieldsMapping.get(oldFacetField);
  653. for (String oldFacetFieldSourceField : oldFacetFieldSourceFields) {
  654. if (oldFacetFieldSourceField.endsWith("strs")) {
  655. ArrayList<String> solrDocOldFacetFieldSourceFieldValue = (ArrayList) (doc.getFieldValue(oldFacetFieldSourceField));
  656. if (solrDocOldFacetFieldSourceFieldValue != null && solrDocOldFacetFieldSourceFieldValue.contains(oldFacetValue)) {
  657. while (solrDocOldFacetFieldSourceFieldValue.contains(oldFacetValue)) {
  658. solrDocOldFacetFieldSourceFieldValue.remove(oldFacetValue);//remove ALL occurances of it
  659. }
  660. fieldModifier = new HashMap<>();
  661. fieldModifier.put("set", solrDocOldFacetFieldSourceFieldValue);
  662. sdoc.addField(oldFacetFieldSourceField, fieldModifier);
  663. fieldModifier = new HashMap();
  664. sdocs.add(sdoc);
  665.  
  666. }
  667. } else {
  668. String solrDocOldFacetFieldSourceFieldValue = getStr(oldFacetFieldSourceField, doc);
  669. if (solrDocOldFacetFieldSourceFieldValue != null && solrDocOldFacetFieldSourceFieldValue.equals(oldFacetValue)) {
  670. fieldModifier = new HashMap<>();
  671. fieldModifier.put("set", null);
  672. sdoc.addField(oldFacetFieldSourceField, fieldModifier);
  673. fieldModifier = new HashMap();
  674. sdocs.add(sdoc);
  675.  
  676. }
  677. }
  678. }
  679. //Add the newFacetValue to some newFacetFieldDestination that will comply with the schema we have, and be picked up by the newFacetField copyField
  680. //THOUGHT: Potential improvement. If the new facet field is a multi valued, it might be faster if instead of atomically adding the new facet value to this list,
  681. //we instead got the list of values in the new facet field, wrote the value in, and then set the whole thing with the value in there.
  682. //THERE was a significant improvement in time when we did this same technique for deleting stuff, so I wonder if here there would be something as well.
  683. //Though the idea of changing facet fields is rarely used so maybe it's not a huge thing.
  684. String newFacetFieldDestinationField = facetFieldToSuffixMapping.get(newFacetField);
  685. fieldModifier = new HashMap<>();
  686. fieldModifier.put("add", newFacetValue);
  687. sdoc.addField(newFacetFieldDestinationField, fieldModifier);
  688. fieldModifier = new HashMap();
  689. sdocs.add(sdoc);
  690.  
  691. } else {
  692. ArrayList<String> oldFacetFieldSourceFields = facetFieldToSourceFieldsMapping.get(oldFacetField);
  693. //The facet field is not different, so we are changing the value, but NOT the field.
  694. //Go through every possible source field, for the particular copy field destination that is oldFacetField.
  695. //For every source, see if it has the oldFacetValue we are looking for
  696. //If it does, remove the old value and add the new one
  697. //an additional check has to be made to see if we are dealing with a multi valued list. If we are, check each value for the old facet value
  698. //If it is a multi valued list, grab the whole list, remove the unwanted value, and then do a set.
  699. for (String oldFacetFieldSourceField : oldFacetFieldSourceFields) {
  700. if (oldFacetFieldSourceField.endsWith("strs")) {
  701. ArrayList<String> solrDocOldFacetFieldSourceFieldValue = (ArrayList) (doc.getFieldValue(oldFacetFieldSourceField));
  702. if (solrDocOldFacetFieldSourceFieldValue != null && solrDocOldFacetFieldSourceFieldValue.contains(oldFacetValue)) {
  703. while (solrDocOldFacetFieldSourceFieldValue.contains(oldFacetValue)) {
  704. solrDocOldFacetFieldSourceFieldValue.remove(oldFacetValue);//remove ALL occurances of it
  705. }
  706. solrDocOldFacetFieldSourceFieldValue.add(newFacetValue);
  707. fieldModifier = new HashMap<>();
  708. fieldModifier.put("set", solrDocOldFacetFieldSourceFieldValue);
  709. sdoc.addField(oldFacetFieldSourceField, fieldModifier);
  710. fieldModifier = new HashMap();
  711. sdocs.add(sdoc);
  712.  
  713. }
  714. } else {
  715. String solrDocOldFacetFieldSourceFieldValue = getStr(oldFacetFieldSourceField, doc);
  716. if (solrDocOldFacetFieldSourceFieldValue != null && solrDocOldFacetFieldSourceFieldValue.equals(oldFacetValue)) {
  717. fieldModifier = new HashMap<>();
  718. fieldModifier.put("set", newFacetValue);
  719. sdoc.addField(oldFacetFieldSourceField, fieldModifier);
  720. fieldModifier = new HashMap();
  721. sdocs.add(sdoc);
  722.  
  723. } else {
  724. }
  725. }
  726. }
  727. }
  728. } else //The facet values are not different, so we are not changing those. The fields may be different, we must check.
  729. {
  730. if (!newFacetField.equals(oldFacetField) && !newFacetField.equals("")) {
  731. //The facet fields are different, so we are changing them, but NOT the values.
  732. //Go through every possible source field, for the particular copy field destination that is oldFacetField.
  733. //For every source, see if it has the oldFacetValue we are looking for
  734. //If it does, remove it.
  735. //an additional check has to be made to see if we are dealing with a multi valued list. If we are, check each value for the old facet value
  736. ArrayList<String> oldFacetFieldSourceFields = facetFieldToSourceFieldsMapping.get(oldFacetField);
  737. for (String oldFacetFieldSourceField : oldFacetFieldSourceFields) {
  738. if (oldFacetFieldSourceField.endsWith("strs")) {
  739. ArrayList<String> solrDocOldFacetFieldSourceFieldValue = (ArrayList) (doc.getFieldValue(oldFacetFieldSourceField));
  740. if (solrDocOldFacetFieldSourceFieldValue != null && solrDocOldFacetFieldSourceFieldValue.contains(oldFacetValue)) {
  741. while (solrDocOldFacetFieldSourceFieldValue.contains(oldFacetValue)) {
  742. solrDocOldFacetFieldSourceFieldValue.remove(oldFacetValue);//remove ALL occurances of it
  743. }
  744. fieldModifier = new HashMap<>();
  745. fieldModifier.put("set", solrDocOldFacetFieldSourceFieldValue);
  746. sdoc.addField(oldFacetFieldSourceField, fieldModifier);
  747. fieldModifier = new HashMap();
  748. sdocs.add(sdoc);
  749.  
  750. }
  751. } else {
  752. String solrDocOldFacetFieldSourceFieldValue = getStr(oldFacetFieldSourceField, doc);
  753. if (solrDocOldFacetFieldSourceFieldValue != null && solrDocOldFacetFieldSourceFieldValue.equals(oldFacetValue)) {
  754. fieldModifier = new HashMap<>();
  755. fieldModifier.put("set", null);
  756. sdoc.addField(oldFacetFieldSourceField, fieldModifier);
  757. fieldModifier = new HashMap();
  758. sdocs.add(sdoc);
  759.  
  760. }
  761. }
  762. }
  763.  
  764. //Add the oldFacetValue to some newFacetFieldDestination that will comply with the schema we have, and be picked up by the newFacetField copyField
  765. String newFacetFieldDestinationField = facetFieldToSuffixMapping.get(newFacetField);
  766. fieldModifier = new HashMap<>();
  767. fieldModifier.put("add", oldFacetValue);
  768. sdoc.addField(newFacetFieldDestinationField, fieldModifier);
  769. fieldModifier = new HashMap();
  770. sdocs.add(sdoc);
  771.  
  772. } else {
  773. //The facet fields are not different, neither are the values. Do nothing.
  774. }
  775. }
  776. }
  777.  
  778. if (sdocs.size() >= rows) {
  779. System.out.println("Adding batch of " + rows + " documents to solr");
  780. facettedServer.add(sdocs);
  781. System.out.println("Committing");
  782. facettedServer.commit();
  783. sdocs.clear();
  784. }
  785.  
  786. if (cursorMark.equals(nextCursorMark)) {
  787. done = true;
  788. }
  789. cursorMark = nextCursorMark;
  790. }
  791. if (sdocs.size() > 0) {
  792. System.out.println("Adding final batch of " + sdocs.size() + " documents to solr");
  793. facettedServer.add(sdocs);
  794. System.out.println("Committing");
  795. facettedServer.commit();
  796. sdocs.clear();
  797. }
  798. } catch (Throwable th) {
  799. System.out.println("Something went wrong.");
  800. th.printStackTrace();
  801. try {
  802. facettedServer.close();
  803. } catch (IOException ex) {
  804. logger.error("ERROR", ex);
  805. }
  806. }
  807. try {
  808. facettedServer.close();
  809. } catch (IOException ex) {
  810. logger.error("ERROR", ex);
  811. }
  812.  
  813. try {
  814. //now modify the back end values as well using Joosep's Modifier class.
  815. Modifier modifier = new Modifier("CleanedTagsDb", "ParsedDb");
  816. modifier.modify(oldFacetValue, newFacetValue);
  817. } catch (Throwable ex) {
  818. System.out.println("WARNING: FAILED TO MODIFY THE VALUES IN THE BACK END");
  819. }
  820. return;
  821. }
  822. }
  823.  
  824. public class FacetDeletingWorkerThread extends Thread {
  825.  
  826. String facetField, facetFieldValue, solrCollectionDbName, username;
  827. boolean plural;
  828. Map<String, ArrayList<String>> facetFieldToSourceFieldsMapping;
  829. Map<String, String> facetFieldToSuffixMapping;
  830. ArrayList<String> sourceFieldsList = new ArrayList<>();
  831. int rows;
  832.  
  833. public FacetDeletingWorkerThread(String facetField, String facetFieldValue, String solrCollectionDbName, String username, Map<String, ArrayList<String>> facetFieldToSourceFieldsMapping, Map<String, String> facetFieldToSuffixMapping, int rows) {
  834. this.facetField = facetField;
  835. this.facetFieldValue = facetFieldValue;
  836. this.solrCollectionDbName = solrCollectionDbName;
  837. this.username = username;
  838. this.facetFieldToSourceFieldsMapping = facetFieldToSourceFieldsMapping;
  839. this.facetFieldToSuffixMapping = facetFieldToSuffixMapping;
  840. for (ArrayList<String> sourceFields : this.facetFieldToSourceFieldsMapping.values()) {
  841. sourceFieldsList.addAll(sourceFields);
  842. }
  843. this.rows = rows;
  844. }
  845.  
  846. @Override
  847. public void run() {
  848. CloudSolrClient facettedServer = new CloudSolrClient("localhost:11093");
  849. facettedServer.setDefaultCollection(solrCollectionDbName);
  850. String cursorMark = CursorMarkParams.CURSOR_MARK_START;
  851. SolrQuery query = new SolrQuery(facetField + ":\"" + facetFieldValue + "\"");
  852. query.setRows(rows);
  853. query.setFields(facetField, facettedServer.getIdField(), "_version_");
  854. for (String field : sourceFieldsList) {
  855. query.addField(field);
  856. }
  857. query.setSort(SortClause.asc("id"));
  858. query.addSort(SortClause.asc("_version_"));
  859. query.addFilterQuery("art_username_str:\"" + username + "\"");
  860. try {
  861. boolean done = false;
  862. ArrayList<SolrInputDocument> sdocs = new ArrayList<>();
  863. while (!done) {
  864. query.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark);
  865. System.out.println("Querying solr with " + query);
  866. QueryResponse response = facettedServer.query(query);
  867. String nextCursorMark = response.getNextCursorMark();
  868. SolrDocumentList docs = response.getResults();
  869.  
  870. System.out.println("Docsize is " + docs.size() + " NumFound is " + docs.getNumFound());
  871. for (SolrDocument doc : docs) {
  872. String id = getStr(facettedServer.getIdField(), doc);
  873. Map<String, Object> fieldModifier;
  874. SolrInputDocument sdoc = new SolrInputDocument();
  875. sdoc.setField(facettedServer.getIdField(), id);
  876. ArrayList<String> facetFieldSourceFields = facetFieldToSourceFieldsMapping.get(facetField);
  877. //The facet field is not different, so we are changing the value, but NOT the field.
  878. //Go through every possible source field, for the particular copy field destination that is facetField.
  879. //For every source, see if it has the facetFieldValue we are looking for
  880. //If it does, remove the old value
  881. //an additional check has to be made to see if we are dealing with a multi valued list. If we are, check each value for the old facet value
  882. //If it is a multi valued list, grab the whole list, remove the unwanted value, and then do a set.
  883. for (String facetFieldSourceField : facetFieldSourceFields) {
  884. if (facetFieldSourceField.endsWith("strs")) {
  885. ArrayList<String> solrDocOldFacetFieldSourceFieldValue = (ArrayList) (doc.getFieldValue(facetFieldSourceField));
  886. if (solrDocOldFacetFieldSourceFieldValue != null && solrDocOldFacetFieldSourceFieldValue.contains(facetFieldValue)) {
  887. while (solrDocOldFacetFieldSourceFieldValue.contains(facetFieldValue)) {
  888. solrDocOldFacetFieldSourceFieldValue.remove(facetFieldValue);//remove ALL occurances of it
  889. }
  890. fieldModifier = new HashMap<>();
  891. fieldModifier.put("set", solrDocOldFacetFieldSourceFieldValue);
  892. sdoc.addField(facetFieldSourceField, fieldModifier);
  893. fieldModifier = new HashMap();
  894. sdocs.add(sdoc);
  895. }
  896. } else {
  897. String solrDocOldFacetFieldSourceFieldValue = getStr(facetFieldSourceField, doc);
  898. if (solrDocOldFacetFieldSourceFieldValue != null && solrDocOldFacetFieldSourceFieldValue.equals(facetFieldValue)) {
  899. fieldModifier = new HashMap<>();
  900. fieldModifier.put("set", null);
  901. sdoc.addField(facetFieldSourceField, fieldModifier);
  902. fieldModifier = new HashMap();
  903. sdocs.add(sdoc);
  904. }
  905. }
  906. }
  907. }
  908.  
  909. if (sdocs.size() >= rows) {
  910. System.out.println("Adding batch of " + rows + " documents to solr");
  911. facettedServer.add(sdocs);
  912. System.out.println("Committing");
  913. facettedServer.commit();
  914. sdocs.clear();
  915. }
  916.  
  917. if (cursorMark.equals(nextCursorMark)) {
  918. done = true;
  919. }
  920. cursorMark = nextCursorMark;
  921. }
  922. if (sdocs.size() > 0) {
  923. System.out.println("Adding final batch of " + sdocs.size() + " documents to solr");
  924. facettedServer.add(sdocs);
  925. System.out.println("Committing");
  926. facettedServer.commit();
  927. sdocs.clear();
  928. }
  929. } catch (Throwable th) {
  930. System.out.println("Something bad happened.");
  931. th.printStackTrace();
  932. try {
  933. facettedServer.close();
  934. } catch (IOException ex) {
  935. logger.error("ERROR", ex);
  936. }
  937. }
  938. try {
  939. facettedServer.close();
  940. } catch (IOException ex) {
  941. logger.error("ERROR", ex);
  942. }
  943.  
  944. try {
  945. //now delete form back end using Joosep's Modifier class.
  946. Modifier modifier = new Modifier("CleanedTagsDb", "ParsedDb");
  947. modifier.delete(facetFieldValue);
  948. } catch (Throwable ex) {
  949. System.out.println("WARNING: FAILED TO DELETE FROM BACK END");
  950. }
  951. return;
  952. }
  953. }
  954.  
  955. public String[] cleanUpOldFacetValues(String[] oldFacetValuesParam) {
  956. String[] oldFacetValues = null;
  957. if (oldFacetValuesParam != null) {
  958. if (oldFacetValuesParam.length > 1) {
  959. oldFacetValues = oldFacetValuesParam; //if for some reason we have more than one paramter, it must be because we got the thing working correctly so im assuming it's safe to just call it done here
  960. } else if (oldFacetValuesParam.length == 1) {
  961. //The string in question , in the first index of this, should look like : ['value1','value2','value3']
  962. //OR if it's a single value it'll look like : ['value1'];
  963. //Either way lets get rid of the braces by doing a substring
  964. //We gotta parse that out into an array, so see if there is a split that can be made with "','" and if there isn't, then we know it's just one value.
  965. String valueStringToParse = oldFacetValuesParam[0];
  966. System.out.println("Old values with brackets and apostrophes -> " + valueStringToParse);
  967. valueStringToParse = valueStringToParse.substring(1, valueStringToParse.length() - 1); //gets ride of the braces
  968. //We should now have something like this : 'value1','value2','value3'
  969. System.out.println("Cleaned up, no brackets, still apostrophes -> " + valueStringToParse);
  970. String[] possibleValues = valueStringToParse.split("', '");
  971. if (possibleValues.length == 1) {
  972. //So we split and it still stayed at size one, meaning we only have one entry in the area which looks like : 'value1'.
  973. //So we'll clean it up and put it in it's own new shiny array. Do another substring to remove the apostrophes
  974. String value = possibleValues[0];
  975. System.out.println("Single value of -> " + value);
  976. value = value.substring(1, value.length() - 1);
  977. System.out.println("Single value with no apostrophes of -> " + value);
  978. oldFacetValues = new String[]{value};
  979. } else {
  980. //So we split and we actually got more than one thing, the array should look like this : ["'value1", "value2", "value3'"]
  981. //So again I think we're good by just cleaning up the apostrophes,which should only exist in the first and last value of the array, but we'll check each one anyways;
  982. ArrayList<String> cleanedUpValues = new ArrayList<>();
  983. System.out.println("Multiple values found in!");
  984. for (String possibleValue : possibleValues) {
  985. System.out.println("One of the values, no braces still apostrophoes maybe -> " + possibleValue);
  986. System.out.println(possibleValue);
  987. if (possibleValue.charAt(0) == '\'') {
  988. possibleValue = possibleValue.substring(1, possibleValue.length()); //gets rid of the first character if it is an apostrophe (can't do regex to remove all as there might be valid apostrophes in the tag)
  989. }
  990. if (possibleValue.charAt(possibleValue.length() - 1) == '\'') {
  991. possibleValue = possibleValue.substring(0, possibleValue.length() - 1);//gets rid of the last character if it is an apostrophe
  992. }
  993. System.out.println("One of the values, no more apostrophes (if there were any) -> " + possibleValue);
  994. cleanedUpValues.add(possibleValue);
  995. oldFacetValues = cleanedUpValues.toArray(new String[]{});
  996. }
  997. }
  998. }
  999. }
  1000. return oldFacetValues;
  1001. }
  1002.  
  1003. public JSONObject modifyFacet(HttpServletRequest request) throws SolrServerException, IOException, JSONException {
  1004. JSONObject response = new JSONObject();
  1005. String nameOfContextFile = "context_" + this.getClass().getSimpleName() + ".xml";
  1006. ApplicationContext applicationContext = new ClassPathXmlApplicationContext(nameOfContextFile);
  1007. String solrCollectionDbName = applicationContext.getBean("solrCollectionDbName", String.class);
  1008. CloudSolrClient facettedServer = new CloudSolrClient("localhost:11093");
  1009. facettedServer.setDefaultCollection((solrCollectionDbName));
  1010.  
  1011. ArrayList<String> specificFacetFieldSourceValues;
  1012. Map<String, ArrayList<String>> facetFieldToSourceFieldsMapping = new HashMap<>();
  1013. facetFieldToSourceFieldsMapping.put("person_display", new ArrayList<String>()); //These 4 are copy fields that have multiple sources.
  1014. facetFieldToSourceFieldsMapping.put("geography_display", new ArrayList<String>());
  1015. facetFieldToSourceFieldsMapping.put("concept_display", new ArrayList<String>());
  1016. facetFieldToSourceFieldsMapping.put("organization_display", new ArrayList<String>());
  1017. specificFacetFieldSourceValues = new ArrayList<String>(1); //The ones below here just have 1 specific source so I'll make the mapping here
  1018. specificFacetFieldSourceValues.add("clusterName");
  1019. facetFieldToSourceFieldsMapping.put("clusterName_display", specificFacetFieldSourceValues);
  1020. specificFacetFieldSourceValues = new ArrayList<String>(1); //The ones below here just have 1 specific source so I'll make the mapping here
  1021. specificFacetFieldSourceValues.add("ind_author_str");
  1022. facetFieldToSourceFieldsMapping.put("ind_author_str", specificFacetFieldSourceValues);
  1023. specificFacetFieldSourceValues = new ArrayList<String>(1);
  1024. specificFacetFieldSourceValues.add("ind_sender_strs");
  1025. facetFieldToSourceFieldsMapping.put("ind_sender_strs", specificFacetFieldSourceValues);
  1026. specificFacetFieldSourceValues = new ArrayList<String>(1);
  1027. specificFacetFieldSourceValues.add("ind_recipient_strs");
  1028. facetFieldToSourceFieldsMapping.put("ind_recipient_strs", specificFacetFieldSourceValues);
  1029. specificFacetFieldSourceValues = new ArrayList<String>(1);
  1030. specificFacetFieldSourceValues.add("art_type_strs");
  1031. facetFieldToSourceFieldsMapping.put("art_type_strs", specificFacetFieldSourceValues);
  1032. specificFacetFieldSourceValues = new ArrayList<String>();
  1033.  
  1034. Map<String, String> facetFieldToSuffixMapping = new HashMap<String, String>();
  1035. facetFieldToSuffixMapping.put("person_display", "ind_facetEdittedInd_strs");
  1036. facetFieldToSuffixMapping.put("geography_display", "geo_facetEdittedGeo_strs");
  1037. facetFieldToSuffixMapping.put("concept_display", "con_facetEdittedCon_strs");
  1038. facetFieldToSuffixMapping.put("organization_display", "org_facetEdittedOrg_strs");
  1039. facetFieldToSuffixMapping.put("clusterName_display", "clusterName");
  1040. facetFieldToSuffixMapping.put("ind_author_str", "ind_author_str");
  1041. facetFieldToSuffixMapping.put("ind_sender_strs", "ind_sender_strs");
  1042. facetFieldToSuffixMapping.put("ind_recipient_strs", "ind_recipient_strs");
  1043. facetFieldToSuffixMapping.put("art_type_strs", "art_type_strs");
  1044.  
  1045. /*
  1046. I know which destionation fields stuff goes into so using the lukeRequest to get back all the fields, I look at the prefix and create a mapping
  1047. that will tell me what destionation field they go to.
  1048. */
  1049. LukeRequest lukeRequest = new LukeRequest();
  1050. lukeRequest.setNumTerms(0);
  1051. LukeResponse lukeResponse = lukeRequest.process(facettedServer);
  1052. Map<String, FieldInfo> fieldInfoMap = lukeResponse.getFieldInfo();
  1053. for (Entry<String, FieldInfo> entry : fieldInfoMap.entrySet()) {
  1054. String fieldName = entry.getKey();
  1055. //Place each source field for the _display facetFields, into the mapping
  1056. if (fieldName.startsWith("ind_")) {
  1057. facetFieldToSourceFieldsMapping.get("person_display").add(fieldName);
  1058. } else if (fieldName.startsWith("org_")) {
  1059. facetFieldToSourceFieldsMapping.get("organization_display").add(fieldName);
  1060. } else if (fieldName.startsWith("con_")) {
  1061. facetFieldToSourceFieldsMapping.get("concept_display").add(fieldName);
  1062. } else if (fieldName.startsWith("geo_")) {
  1063. facetFieldToSourceFieldsMapping.get("geography_display").add(fieldName);
  1064. }
  1065. }
  1066. facettedServer.close();
  1067.  
  1068. for (Entry<String, ArrayList<String>> facetFieldsToSourceFieldsMapping : facetFieldToSourceFieldsMapping.entrySet()) {
  1069. String facetField = facetFieldsToSourceFieldsMapping.getKey();
  1070. ArrayList<String> sourceFields = facetFieldsToSourceFieldsMapping.getValue();
  1071. System.out.println(facetField + " -> " + sourceFields);
  1072. }
  1073.  
  1074. String username = request.getParameter("username");
  1075. String action = request.getParameter("action");
  1076. String rows = request.getParameter("rows");
  1077. int rowsInt;
  1078. if (rows != null) {
  1079. rowsInt = Integer.valueOf(rows);
  1080. } else {
  1081. rowsInt = 1000;
  1082. }
  1083. if (action.equals("modify")) {
  1084. System.out.println("Running modify");
  1085.  
  1086. String[] oldFacetValuesParam = request.getParameterValues("values");
  1087. String[] oldFacetValues = cleanUpOldFacetValues(oldFacetValuesParam);
  1088. if (oldFacetValues == null | oldFacetValues.length < 1) {
  1089. System.out.println("No facet value was detected, error");
  1090. return (new JSONObject().put("ERROR", "NO FACET VALUE DETECTED"));
  1091. }
  1092.  
  1093. String newFacetValue = request.getParameter("editValue");
  1094. String oldFacetField = request.getParameter("field");
  1095. String newFacetField = request.getParameter("editField");
  1096. for (String oldFacetValue : oldFacetValues) {
  1097. FacetEdittingWorkerThread facetEdittingWorkerThread = new FacetEdittingWorkerThread(oldFacetValue, newFacetValue, oldFacetField, newFacetField, solrCollectionDbName, username, facetFieldToSourceFieldsMapping, facetFieldToSuffixMapping, rowsInt);
  1098. facetEdittingWorkerThread.start();
  1099. }
  1100.  
  1101. } else if (action.equals("delete")) {
  1102. System.out.println("Running delete");
  1103. String facetField = request.getParameter("field");
  1104.  
  1105. String[] oldFacetValuesParam = request.getParameterValues("values");
  1106. String[] oldFacetValues = cleanUpOldFacetValues(oldFacetValuesParam);
  1107. if (oldFacetValues == null | oldFacetValues.length < 1) {
  1108. System.out.println("No facet value was detected, error");
  1109. return (new JSONObject().put("ERROR", "NO FACET VALUE DETECTED"));
  1110. }
  1111.  
  1112. for (String oldFacetValue : oldFacetValues) {
  1113. FacetDeletingWorkerThread facetDeletingWorkerThread = new FacetDeletingWorkerThread(facetField, oldFacetValue, solrCollectionDbName, username, facetFieldToSourceFieldsMapping, facetFieldToSuffixMapping, rowsInt);
  1114. facetDeletingWorkerThread.start();
  1115. }
  1116. }
  1117. response.put("success", "Successfully processed and completed the modify facet request");
  1118. return response;
  1119. }
  1120.  
  1121. private JSONObject fileNavigationRequest(HttpServletRequest request) throws JSONException, SolrServerException, IOException, ParseException {
  1122. JSONObject response = new JSONObject();
  1123. String nameOfContextFile = "context_" + this.getClass().getSimpleName() + ".xml";
  1124. ApplicationContext applicationContext = new ClassPathXmlApplicationContext(nameOfContextFile);
  1125.  
  1126. /*
  1127. OK!!! When given a forward slash ("/") as a filePath here's what I have to do.
  1128. Find out what the user's root folder is (for testing right now it's just jjones)
  1129. put that behidn all fildpaths i use to be able to get stuff at S3 (So dont query s3 for /blah.txt but jjones/blah.txt
  1130. DO NOT SHOW jjones to james, when I respond back he's just gonna see "/blah.txt"
  1131. */
  1132. String name = request.getParameter("name");
  1133. String user_id = request.getParameter("user_id");
  1134. String filepath = request.getParameter("filepath");
  1135. if (filepath.equals("/")) {
  1136. filepath = user_id;
  1137. } else {
  1138. filepath = user_id + filepath;
  1139. }
  1140.  
  1141. String artifactId = request.getParameter("id");
  1142. if (artifactId == null) {
  1143. artifactId = filepath;
  1144. }
  1145.  
  1146. //P3 hoops!
  1147. String q = request.getParameter("query");
  1148. JSONObject queryFromJames = new JSONObject(q);
  1149. JSONArray mustJSONArray = queryFromJames.getJSONObject("query").getJSONObject("function_score").getJSONObject("query").getJSONObject("bool").getJSONObject("filter").getJSONObject("bool").getJSONArray("must");
  1150. if (!filepath.endsWith(".email")) { //emails don't need this extra match, they just go straight for id or parent email id
  1151. JSONObject matchForPath = new JSONObject();
  1152. if (filepath.contains(user_id + "/P3")) {
  1153. matchForPath.put("match", new JSONObject().put("art_s3FileParentFolderPath_pth.keyword", "P3/" + filepath));
  1154. } else {
  1155. matchForPath.put("match", new JSONObject().put("art_s3FileParentFolderPath_pth.keyword", filepath));
  1156. }
  1157. mustJSONArray.put(matchForPath);
  1158. }
  1159.  
  1160.  
  1161. JSONArray jsonResponseForOutputArray = new JSONArray();
  1162. JSONArray jsonResponseForFolderOutputArray = new JSONArray();
  1163.  
  1164. if (filepath.endsWith(".email")) {
  1165. //only show files as emails cannot contain folder attachments that aren't zips, which are files.
  1166. JSONObject matchForParentEmailId = new JSONObject().put("match", new JSONObject().put("art_parentEmailId_str", artifactId));
  1167. JSONObject matchForId = new JSONObject().put("match", new JSONObject().put("id", artifactId));
  1168. JSONArray orMatches = new JSONArray();
  1169. orMatches.put(matchForParentEmailId);
  1170. orMatches.put(matchForId);
  1171. JSONObject boolForOrMatches = new JSONObject();
  1172. boolForOrMatches.put("bool", new JSONObject().put("should", orMatches));
  1173. mustJSONArray.put(boolForOrMatches);
  1174.  
  1175.  
  1176. //Query it once to get just the number of things found, then update size in the query to be that number
  1177. HttpPost queryPost = elasticSearchConnection.getHttpPostQueryFromJsonString(queryFromJames.toString());
  1178. JSONObject postResponseJsonObject = new JSONObject(elasticSearchConnection.postToDb(queryPost));
  1179. int hits = postResponseJsonObject.getJSONObject("hits").getInt("total");
  1180. queryFromJames.put("size", hits);
  1181. queryPost = elasticSearchConnection.getHttpPostQueryFromJsonString(queryFromJames.toString());
  1182. String postResponse = elasticSearchConnection.postToDb(queryPost);
  1183. JSONArray parsedResults = parsePostResponse(postResponse);
  1184. logger.debug("@@@@@@@@@@@@@@@@@@@@ Found " + hits + " results for attachments in the email with the filepath of " + filepath + ". \n\n@@@@@@@@@@@@@@@@@@@@ Query Object used was : " + queryFromJames);
  1185. for (int i = 0; i < parsedResults.length(); i++) {
  1186. JSONObject parsedResult = parsedResults.getJSONObject(i);
  1187. JSONObject jsonResponseForThisDatabaseRow = parseAttachmentDatabaseRowForFileNavToJson(parsedResult, name, user_id);
  1188. if (jsonResponseForThisDatabaseRow != null) {
  1189. jsonResponseForOutputArray.put(jsonResponseForThisDatabaseRow);
  1190. logger.trace("EMAIL RESPONSE -> " + jsonResponseForThisDatabaseRow);
  1191. }
  1192. }
  1193.  
  1194. //sort files in the folder based on filename.....
  1195. jsonResponseForOutputArray = this.sortOnFileName(jsonResponseForOutputArray);
  1196. response.put("from", "");
  1197. } else {
  1198. //folders and files that aren't coming from a parent email or parent pst
  1199. //this setup for the query is just to get the list of all folders with that user. Later, the query is changed to what the user gave
  1200. JSONObject facetQuery = new JSONObject(q);
  1201. JSONArray mustJSONArrayForFacet = facetQuery.getJSONObject("query").getJSONObject("function_score").getJSONObject("query").getJSONObject("bool").getJSONObject("filter").getJSONObject("bool").getJSONArray("must");
  1202. JSONObject wildCardForPath = new JSONObject();
  1203. if (filepath.contains(user_id + "/P3")) {
  1204. wildCardForPath.put("wildcard", new JSONObject().put("art_s3FileParentFolderPath_pth.keyword", "P3/" + filepath + "*"));
  1205. } else {
  1206. wildCardForPath.put("wildcard", new JSONObject().put("art_s3FileParentFolderPath_pth.keyword", filepath + "*"));
  1207. }
  1208. mustJSONArrayForFacet.put(wildCardForPath);
  1209. JSONObject countSortDesc = new JSONObject().put("_count", "desc");
  1210. JSONObject terms = new JSONObject();
  1211. terms.put("field", "art_s3FileParentFolderPath_pth.keyword");
  1212. terms.put("order", countSortDesc);
  1213. terms.put("min_doc_count", 1);
  1214. terms.put("size", Integer.MAX_VALUE);//wholllllleeeee lottttaaa facets
  1215. JSONObject facet = new JSONObject();
  1216. facet.put("terms", terms);
  1217. JSONObject aggs = new JSONObject();
  1218. aggs.put("art_s3FileParentFolderPath_pth", facet);
  1219. facetQuery.put("aggs", aggs);
  1220.  
  1221. //SO just getting facet inforation for the sake of folders
  1222. logger.debug("The query used to get the facet information for folders is " + facetQuery);
  1223. HttpPost queryPost = elasticSearchConnection.getHttpPostQueryFromJsonString(facetQuery.toString());
  1224. JSONObject postResponseJsonObject = new JSONObject(elasticSearchConnection.postToDb(queryPost));
  1225. JSONArray jsonArrayResponseForThisFacetField = parseFolderFacetFieldForFileNavTojson(postResponseJsonObject, filepath, user_id);
  1226. jsonResponseForFolderOutputArray = (jsonArrayResponseForThisFacetField);
  1227. logger.trace("INITIAL FOLDER RESPONSE -> " + jsonArrayResponseForThisFacetField);
  1228.  
  1229. //now the actual query with data and whatnot
  1230. int from = queryFromJames.getInt("from");
  1231. int rows = 100;
  1232. queryFromJames.put("size", rows);
  1233. queryPost = elasticSearchConnection.getHttpPostQueryFromJsonString(queryFromJames.toString());
  1234. String postResponse = elasticSearchConnection.postToDb(queryPost);
  1235. JSONArray parsedResults = parsePostResponse(postResponse);
  1236. Integer numFound = parsedResults.length();
  1237.  
  1238. logger.debug("@@@@@@@@@@@@@@@@@@@@ Found " + numFound + " results. \n@@@@@@@@@@@@@@@@@@@@ Query Object used was : " + queryFromJames);
  1239. for (int i = 0; i < parsedResults.length(); i++) {
  1240. JSONObject databaseRow = parsedResults.getJSONObject(i);
  1241. String isEmail;
  1242. if (databaseRow.isNull("art_isEmail_str")) {
  1243. isEmail = null;
  1244. } else {
  1245. isEmail = databaseRow.getString("art_isEmail_str");
  1246. }
  1247. String artifactType = databaseRow.getString("art_artifactType_str");
  1248. if (isEmail != null && isEmail.equals("true")) { //add the emails as additional folders to the folder output array
  1249. JSONObject jsonResponseForThisDatabaseRow = parseEmailAsFolderForFileNavToJson(databaseRow, user_id);
  1250. addAdditionalDataForSidePanelToJsonResponseForDatabaseRow(jsonResponseForThisDatabaseRow, databaseRow);
  1251. if (jsonResponseForThisDatabaseRow != null) {
  1252. jsonResponseForFolderOutputArray.put(jsonResponseForThisDatabaseRow);
  1253. logger.trace("EMAIL AS FOLDER RESPONSE -> " + jsonResponseForThisDatabaseRow);
  1254. }
  1255. } else if (artifactType.equals("attachment")) {
  1256. /*
  1257. Grab the parent id of the attachment
  1258. Query for that document
  1259. parseEmailDocAsFolderForFileNavToJson on that email thing
  1260. add it to the jsonResponseForFolderOutputArray
  1261. */
  1262. String parentEmailId = databaseRow.getString("art_parentEmailId_str");
  1263. JSONObject miniQuery = new JSONObject().put("query", new JSONObject().put("match", new JSONObject().put("id", parentEmailId)));
  1264. logger.trace("The query used to get the email thing is " + miniQuery);
  1265. queryPost = elasticSearchConnection.getHttpPostQueryFromJsonString(miniQuery.toString());
  1266. postResponseJsonObject = new JSONObject(elasticSearchConnection.postToDb(queryPost));
  1267. parsedResults = parsePostResponse(postResponse);
  1268. //Should only be 1 response so!
  1269. JSONObject emailThing = parsedResults.getJSONObject(0);
  1270. JSONObject jsonResponseForThisDatabaseRow = parseEmailAsFolderForFileNavToJson(emailThing, user_id);
  1271. addAdditionalDataForSidePanelToJsonResponseForDatabaseRow(jsonResponseForThisDatabaseRow, emailThing);
  1272. if (jsonResponseForThisDatabaseRow != null) {
  1273. jsonResponseForFolderOutputArray.put(jsonResponseForThisDatabaseRow);
  1274. logger.trace("ATTACHMENT FOLDER RESPONSE -> " + jsonResponseForThisDatabaseRow);
  1275. }
  1276.  
  1277. } else {
  1278. JSONObject jsonResponseForThisDatabaseRow = parseForFileNavToJson(databaseRow, user_id);
  1279. addAdditionalDataForSidePanelToJsonResponseForDatabaseRow(jsonResponseForThisDatabaseRow, databaseRow);
  1280. if (jsonResponseForThisDatabaseRow != null) {
  1281. jsonResponseForOutputArray.put(jsonResponseForThisDatabaseRow);
  1282. logger.trace("JUST A FILE RESPONSE -> " + jsonResponseForThisDatabaseRow);
  1283. }
  1284. }
  1285. }
  1286.  
  1287. //sort files in the folder based on filename.....
  1288. jsonResponseForOutputArray = this.sortOnFileName(jsonResponseForOutputArray);
  1289.  
  1290. if (rows > numFound){
  1291. response.put("from", "");
  1292. } else {
  1293. response.put("from", from + rows);
  1294. }
  1295. }
  1296.  
  1297. response.put("files", jsonResponseForOutputArray);
  1298. logger.trace("FINAL JSON RESPONSE -> " + jsonResponseForOutputArray);
  1299. response.put("folders", jsonResponseForFolderOutputArray);
  1300. logger.trace("FINAL JSON FOLDER RESPONSE -> " + jsonResponseForFolderOutputArray);
  1301. return response;
  1302. }
  1303.  
  1304. private static boolean skipBlankFiles(SolrDocument doc) {
  1305. String art_xParsedBy_str = (String) doc.get("art_xParsedBy_str");
  1306. if (art_xParsedBy_str != null && art_xParsedBy_str.equals("org.apache.tika.parser.EmptyParser")) {
  1307. Long fileSize = (Long) doc.get("art_fileSize_int");
  1308. if (fileSize != null && fileSize == 8) {
  1309. //skip the empty files of size 8 that come from emails
  1310. return true;
  1311. }
  1312. }
  1313. return false;
  1314. }
  1315.  
  1316. Comparator<JSONObject> fileNameComparator = new Comparator<JSONObject>() {
  1317. @Override
  1318. public int compare(JSONObject o1, JSONObject o2) {
  1319. if (o1 instanceof JSONObject && o2 instanceof JSONObject) {
  1320. String s1 = "", s2 = "";
  1321. try {
  1322. s1 = (String) ((JSONObject) o1).get("name");
  1323. s2 = (String) ((JSONObject) o2).get("name");
  1324. return s1.compareTo(s2);
  1325. } catch (JSONException ex) {
  1326. ex.printStackTrace();
  1327. }
  1328. return 0;
  1329. } else {
  1330. return 0;
  1331. }
  1332. }
  1333. };
  1334.  
  1335. private JSONArray sortOnFileName(JSONArray files) {
  1336. JSONArray out = new JSONArray();
  1337. List<JSONObject> tmp = new ArrayList<>();
  1338. for (int i = 0; i < files.length(); i++) {
  1339. try {
  1340. JSONObject file = (JSONObject) files.get(i);
  1341. tmp.add(file);
  1342. } catch (JSONException ex) {
  1343. ex.printStackTrace();
  1344. }
  1345. }
  1346.  
  1347. Collections.sort(tmp, fileNameComparator);
  1348.  
  1349. for (JSONObject file : tmp) {
  1350. out.put(file);
  1351. }
  1352.  
  1353. return out;
  1354. }
  1355.  
  1356. public class TagEdittingWorkerThread extends Thread {
  1357.  
  1358. String fq, q, tagField, tagValue, user_id, action, solrCollectionDbName, dataBlob;
  1359. int rows = 2500;
  1360.  
  1361. public TagEdittingWorkerThread(String q, String tagField, String tagValue, String user_id, String action, String solrCollectionDbName, String dataBlob) {
  1362. this.q = q;
  1363. this.tagField = tagField;
  1364. this.tagField = this.tagField.replace("art_", "");
  1365. this.tagField = this.tagField.replace("_strs","");
  1366. this.tagValue = tagValue;
  1367. this.user_id = user_id;
  1368. this.action = action;
  1369. this.solrCollectionDbName = solrCollectionDbName;
  1370. this.dataBlob = dataBlob;
  1371. }
  1372.  
  1373. @Override
  1374. public void run() {
  1375. elasticSearchConnection.setIndex("queries");
  1376. String queryId = user_id + "_" + tagValue;
  1377. /*
  1378. As a first step, attempt to add or delete the query this tag used in the facetted_queries collection
  1379. */
  1380. try {
  1381. if (action.equals("add")) {
  1382. // DateTimeFormatter dtf = ISODateTimeFormat.dateTimeNoMillis();
  1383. // String creation_date = dtf.print(DateTime.now());
  1384. // JSONObject dataBlobJson = new JSONObject(dataBlob);
  1385. //
  1386. // Datum querySave = new Datum(queryId);
  1387. // querySave.add(DataService.CONTENT_TYPE.artifact, "visibility", DataService.DATA_TYPE.string, false, "private");
  1388. // querySave.add(DataService.CONTENT_TYPE.artifact, "creationDate", DataService.DATA_TYPE.date, false, creation_date);
  1389. // querySave.add(DataService.CONTENT_TYPE.individual, "creatorName", DataService.DATA_TYPE.string, false, user_id);
  1390. // querySave.add(DataService.CONTENT_TYPE.artifact, "targetName", DataService.DATA_TYPE.string, false, "AUTO : {" + tagValue + "} by user {" + user_id + "}");
  1391. // querySave.add(DataService.CONTENT_TYPE.artifact, "targetDescription", DataService.DATA_TYPE.string, false, "This is the query that was used by " + user_id + " to get the subset of documents that were tagged with the tag " + tagValue + ". The tagging was performed and saved on " + creation_date);
  1392. // querySave.add(DataService.CONTENT_TYPE.artifact, "dataBlob", DataService.DATA_TYPE.string, false, unescapeJsonToStringString(dataBlobJson.toString()));
  1393. // elasticSearchConnection.updateOrCreate(queryId, querySave, false);
  1394. } else if (action.equals("remove")) {
  1395. // elasticSearchConnection.deleteById(queryId);
  1396. }
  1397. } catch (Throwable th) {
  1398. System.err.println("An error occured while attempting to save/delete the query that was used to generate this tag");
  1399. th.printStackTrace();
  1400. }
  1401.  
  1402. elasticSearchConnection.setIndex("artifact");
  1403. JSONObject query = new JSONObject();
  1404. try {
  1405. query = new JSONObject(q);
  1406. } catch (JSONException ex) {
  1407. java.util.logging.Logger.getLogger(ElasticSearch_Servlet.class.getName()).log(Level.SEVERE, null, ex);
  1408. }
  1409.  
  1410. int from = 0;
  1411. int rows = 500;
  1412. boolean done = false;
  1413. while (!done) {
  1414. try {
  1415. query.put("from", from);
  1416. query.put("size", rows);
  1417. HttpPost queryPost = elasticSearchConnection.getHttpPostQueryFromJsonString(query.toString());
  1418. String postResponse = elasticSearchConnection.postToDb(queryPost);
  1419. JSONArray parsedResults = parsePostResponse(postResponse);
  1420. int numFound = parsedResults.length();
  1421. System.out.println("Tagging batch of rows starting from number " + from + " out of " + numFound);
  1422.  
  1423. for (int i = 0; i < parsedResults.length(); i++) {
  1424. JSONObject parsedResult = parsedResults.getJSONObject(i);
  1425. String id = parsedResult.getString("id");
  1426. JSONArray tagFieldValues = null;
  1427. if (parsedResult.has(tagField) && parsedResult.get(tagField) != null) {
  1428. tagFieldValues = parsedResult.getJSONArray(tagField);
  1429. } else {
  1430. tagFieldValues = new JSONArray();
  1431. }
  1432. System.out.println("GOT TAG ARRAY OF -> " + parsedResult);
  1433.  
  1434. Datum datum = new Datum(id);
  1435. if (action.equals("add")) {
  1436. datum.add(DataService.CONTENT_TYPE.artifact, tagField, DataService.DATA_TYPE.string, true, tagValue);
  1437. elasticSearchConnection.updateOrCreate(id, datum, false);
  1438. } else if (action.equals("remove")) {
  1439. System.out.println("Removing " + tagValue + " from " + tagFieldValues);
  1440. JSONArray forPrintOut = new JSONArray();
  1441. for (int j = 0; j < tagFieldValues.length(); j++) {
  1442. String tagFieldValue = tagFieldValues.getString(j);
  1443. if (tagFieldValue.equals(tagValue)){
  1444. continue; //Do not add if it's the one we are trying to remove.
  1445. }
  1446. else {
  1447. forPrintOut.put(tagFieldValue);
  1448. datum.add(DataService.CONTENT_TYPE.artifact, tagField, DataService.DATA_TYPE.string, true, tagFieldValue);
  1449. }
  1450. }
  1451. System.out.println("New JSONArray of tags is " + forPrintOut);
  1452. elasticSearchConnection.updateOrCreate(id, datum, true); //Have to overwrite multi-valued field becuase i'm giving it less than what it has.
  1453. }
  1454. }
  1455.  
  1456. if (rows > numFound) {
  1457. done = true;
  1458. } else {
  1459. from = from + rows;
  1460. done = false;
  1461. }
  1462. } catch (JSONException ex) {
  1463. java.util.logging.Logger.getLogger(ElasticSearch_Servlet.class.getName()).log(Level.SEVERE, null, ex);
  1464. } catch (ParseException ex) {
  1465. java.util.logging.Logger.getLogger(ElasticSearch_Servlet.class.getName()).log(Level.SEVERE, null, ex);
  1466. }
  1467. }
  1468. }
  1469. }
  1470.  
  1471. public JSONObject editTag(HttpServletRequest request) throws JSONException {
  1472. JSONObject response = new JSONObject();
  1473. String q = request.getParameter("query");
  1474. String tagField = request.getParameter("tagField");
  1475. String tagValue = request.getParameter("tagValue");
  1476. String user_id = request.getParameter("user_id");
  1477. String action = request.getParameter("action");
  1478. String dataBlob = request.getParameter("facetData");
  1479.  
  1480. String nameOfContextFile = "context_" + this.getClass().getSimpleName() + ".xml";
  1481. ApplicationContext applicationContext = new ClassPathXmlApplicationContext(nameOfContextFile);
  1482. String solrCollectionDbName = applicationContext.getBean("solrCollectionDbName", String.class);
  1483.  
  1484. TagEdittingWorkerThread tagEdittingWorkerThread = new TagEdittingWorkerThread(q, tagField, tagValue, user_id, action, solrCollectionDbName, dataBlob);
  1485. tagEdittingWorkerThread.start();
  1486. response.put("success", "Done with the tag editting requesting.");
  1487. return response;
  1488. }
  1489.  
  1490. public class UserActionWorkerThread extends Thread {
  1491.  
  1492. String action, username, userId, type, userMappingCollectionName, newUserBucketName, sampleFilesBucketName, sampleFilesFolderPath;
  1493. int rows = 2500;
  1494.  
  1495. public UserActionWorkerThread(String action, String username, String userId, String type, String userMappingCollectionName, String newUserBucketName, String sampleFilesBucketName, String sampleFilesFolderPath) {
  1496. this.action = action;
  1497. this.username = username;
  1498. this.userId = userId;
  1499. this.type = type;
  1500. this.userMappingCollectionName = userMappingCollectionName;
  1501. this.newUserBucketName = newUserBucketName;
  1502. this.sampleFilesBucketName = sampleFilesBucketName;
  1503. this.sampleFilesFolderPath = sampleFilesFolderPath;
  1504. }
  1505.  
  1506. @Override
  1507. public void run() {
  1508. String success;
  1509. JSONObject response = new JSONObject();
  1510. System.out.println("Connecting to solr");
  1511. CloudSolrClient facettedServer = new CloudSolrClient("localhost:11093");
  1512. System.out.println("Setting default collection to {" + userMappingCollectionName + "}");
  1513. facettedServer.setDefaultCollection(userMappingCollectionName);
  1514.  
  1515. if (username == null) {
  1516. success = "Failed. No username provided.";
  1517. } else if (action == null) {
  1518. success = "Failed. No action provided.";
  1519. } else {
  1520. boolean isDemo = false;
  1521. if (type != null && type.equals("demo")) {
  1522. isDemo = true;
  1523. }
  1524. switch (action) {
  1525. case "create": {
  1526. DateTime now = DateTime.now();
  1527. System.out.println("User creation started at " + now);
  1528. System.out.println("Creating SolrInputDocument for the new user to be put into " + userMappingCollectionName);
  1529. SolrInputDocument sdoc = new SolrInputDocument();
  1530. sdoc.setField("art_sstUserId_str", username);
  1531. if (userId != null) {
  1532. sdoc.setField("art_s3UserFolder_str", "MBS-" + userId);
  1533. } else {
  1534. sdoc.setField("art_s3UserFolder_str", username);
  1535. }
  1536. sdoc.setField("art_type_str", type);
  1537. String id = String.valueOf(sdoc.toString().hashCode());
  1538. sdoc.setField("id", id);
  1539. System.out.println("Document was created, here it is \n" + sdoc);
  1540. System.out.println("Adding said document");
  1541. try {
  1542. facettedServer.add(sdoc);
  1543. System.out.println("Committing said document");
  1544. facettedServer.commit();
  1545. } catch (SolrServerException | IOException ex) {
  1546. java.util.logging.Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex);
  1547. }
  1548.  
  1549. System.out.println("Moving over sample data");
  1550. String query = "art_username_str:enronDemo";
  1551. String bucket = "sst-test.output";
  1552. UserCreator userCreator = new UserCreator();
  1553. userCreator.createNewUserByQueryNoFileCopy(query, username, bucket);
  1554. userCreator.close();
  1555. System.out.println("Finished moving over sample data, and correcting the data.");
  1556. DateTime then = DateTime.now();
  1557. System.out.println("User creation finished at " + then);
  1558. Long timeSpent = then.getMillis() - now.getMillis();
  1559. System.out.println("User creation took " + (timeSpent / 1000) + " seconds OR " + ((timeSpent / 1000) / 60) + " minutes");
  1560.  
  1561. }
  1562. success = "Created " + username + (isDemo ? " as demo account" : "");
  1563. break;
  1564. case "modify": {
  1565. //To be determined what to switch it to.
  1566. SolrInputDocument sdoc = new SolrInputDocument();
  1567. System.out.println("Flipping user type for user " + username);
  1568. sdoc.setField("id", username);
  1569. Map<String, Object> fieldModifier = new HashMap<>();
  1570. if (isDemo) {
  1571. fieldModifier.put("set", "not-demo");
  1572. } else {
  1573. fieldModifier.put("set", "demo");
  1574. }
  1575. sdoc.setField("art_type_str", fieldModifier);
  1576. System.out.println("Adding and committing");
  1577. try {
  1578. facettedServer.add(sdoc);
  1579. facettedServer.commit();
  1580. } catch (SolrServerException | IOException ex) {
  1581. java.util.logging.Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex);
  1582. }
  1583. }
  1584. success = "Modified " + username + (isDemo ? " to be a demo account" : " to not be a demo account");
  1585. break;
  1586. case "delete": {
  1587. System.out.println("Deleting user by calling deleteById in solr for user " + username);
  1588. try {
  1589. facettedServer.deleteById(username);
  1590. System.out.println("Committing delete");
  1591. facettedServer.commit();
  1592. } catch (SolrServerException | IOException ex) {
  1593. java.util.logging.Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex);
  1594. }
  1595.  
  1596. //Add the bit to delete the stuff from their s3 folder.
  1597. S3Extractor s3Utils = new S3Extractor();
  1598. s3Utils.deleteFileOrFolder(newUserBucketName, username + "/");
  1599. }
  1600. success = "Deleted " + username;
  1601. break;
  1602. default:
  1603. success = "Failed. Unrecognized action '" + action + "'";
  1604. }
  1605. }
  1606. System.out.println("Closing connection to solr");
  1607. try {
  1608. facettedServer.close();
  1609. } catch (IOException ex) {
  1610. java.util.logging.Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex);
  1611. }
  1612. }
  1613. }
  1614.  
  1615. /**
  1616. * @param request
  1617. * @return
  1618. */
  1619. public JSONObject userAction(HttpServletRequest request) throws JSONException, SolrServerException, IOException {
  1620. String nameOfContextFile = "context_" + this.getClass().getSimpleName() + ".xml";
  1621. ApplicationContext applicationContext = new ClassPathXmlApplicationContext(nameOfContextFile);
  1622. String userMappingCollectionName = applicationContext.getBean("solrUserMappingCollectionDbName", String.class);
  1623. String newUserBucketName = applicationContext.getBean("newUserBucketName", String.class);
  1624. String sampleFilesBucketName = applicationContext.getBean("sampleFilesBucketName", String.class);
  1625. String sampleFilesFolderPath = applicationContext.getBean("sampleFilesFolderPath", String.class);
  1626.  
  1627. String action = request.getParameter("command");
  1628. String username = request.getParameter("username");
  1629. String type = request.getParameter("type");
  1630. String userId = request.getParameter("userId");
  1631. UserActionWorkerThread userActionWorkerThread = new UserActionWorkerThread(action, username, userId, type, userMappingCollectionName, newUserBucketName, sampleFilesBucketName, sampleFilesFolderPath);
  1632. userActionWorkerThread.start();
  1633.  
  1634. JSONObject response = new JSONObject();
  1635. response.put("success", "Successfully took in the request for user action");
  1636. logger.debug("RESPONSE: " + response);
  1637. return response;
  1638. }
  1639.  
  1640. public JSONObject exportFiles(HttpServletRequest request) throws JSONException, ConversionException {
  1641. String tagField = request.getParameter("tagField");
  1642. String tag = request.getParameter("tagValue");
  1643. String userName = request.getParameter("user_id");
  1644. String folderName = request.getParameter("folderName");
  1645. String email = request.getParameter("email");
  1646.  
  1647. logger.info("Exporting tag '" + tag + "'");
  1648. String nameOfContextFile = "context_" + this.getClass().getSimpleName() + ".xml";
  1649. ApplicationContext applicationContext = new ClassPathXmlApplicationContext(nameOfContextFile);
  1650. Exporter exporter = applicationContext.getBean("exporter", Exporter.class);
  1651. exporter.setTag(tag);
  1652. URL presignedURL = null;
  1653. try {
  1654. presignedURL = exporter.export(userName, folderName);
  1655. if (presignedURL == null) {
  1656. logger.error("Could not convert & upload documents for '" + tag + "'");
  1657. JSONObject failure = new JSONObject();
  1658. failure.put("status", "failed to convert and upload documents for tag {" + tag + "}");
  1659. return failure;
  1660. } else {
  1661. System.out.println(tag + "\t" + presignedURL);
  1662. }
  1663. } catch (ConversionException e) {
  1664. logger.error("Error setting up pdf conversion.", e);
  1665. }
  1666.  
  1667. logger.info("Sending email");
  1668. String messageSubject = "Your tag has been exported. Here is the link to where you can download the files.";
  1669. String messageBody = "Click on the link below to be able to download the files that have been exported using the tag of {" + tag + "}"
  1670. + "\n" + presignedURL;
  1671. sendEmail(email, messageSubject, messageBody);
  1672.  
  1673. JSONObject success = new JSONObject();
  1674. success.put("status", "success");
  1675. return success;
  1676. }
  1677.  
  1678. public void sendEmail(String toEmail, String messageSubject, String messageBody) {
  1679. String username = "donotreply@cfday.net";
  1680. final String password = "1966GTO!";
  1681.  
  1682. // Get system properties
  1683. Properties props = new Properties();
  1684. props.put("mail.smtp.auth", "true");
  1685. props.put("mail.smtp.starttls.enable", "true");
  1686. props.put("mail.smtp.host", "smtp.office365.com");//email-smtp.us-east-1.amazonaws.com");
  1687. props.put("mail.smtp.port", "587");
  1688.  
  1689. Session session = Session.getInstance(props,
  1690. new javax.mail.Authenticator() {
  1691. protected PasswordAuthentication getPasswordAuthentication() {
  1692. return new PasswordAuthentication(username, password);
  1693. }
  1694. });
  1695.  
  1696. try {
  1697.  
  1698. Message message = new MimeMessage(session);
  1699. message.setFrom(new InternetAddress("DoNotReply@cfday.net"));
  1700. message.setRecipients(Message.RecipientType.TO,
  1701. InternetAddress.parse(toEmail));
  1702. message.setSubject(messageSubject);
  1703. message.setText(messageBody);
  1704.  
  1705. Transport.send(message);
  1706.  
  1707. System.out.println("Done");
  1708.  
  1709. } catch (MessagingException e) {
  1710. throw new RuntimeException(e);
  1711. }
  1712. }
  1713.  
  1714. public JSONObject showEmailChain(HttpServletRequest request) throws SolrServerException, IOException {
  1715. String emailId = request.getParameter("emailId");
  1716. String username = request.getParameter("usernName");
  1717. String whatToGiveBack = request.getParameter("whatToGiveBack");
  1718. String nameOfContextFile = "context_" + this.getClass().getSimpleName() + ".xml";
  1719. ApplicationContext applicationContext = new ClassPathXmlApplicationContext(nameOfContextFile);
  1720. String solrCollectionDbName = applicationContext.getBean("solrCollectionDbName", String.class);
  1721.  
  1722. JSONObject response = new JSONObject();
  1723. System.out.println("Connecting to solr");
  1724. CloudSolrClient facettedServer = new CloudSolrClient("localhost:11093");
  1725. System.out.println("Setting default collection to {" + solrCollectionDbName + "}");
  1726. facettedServer.setDefaultCollection(solrCollectionDbName);
  1727.  
  1728. String queryString;
  1729. if (whatToGiveBack.equals("OnlyEmails")) {
  1730. queryString = "+id:\"" + emailId + "\" +art_messageClass_str:\"IPM.Note\"";
  1731. } else {
  1732. queryString = "+id:\"" + emailId + "\"";
  1733. }
  1734. SolrQuery solrQuery = new SolrQuery(queryString);
  1735. solrQuery.setFields("id", "_version_", "art_threadIndex_str", "art_threadTopic_str", "art_messageClass_str");
  1736. QueryResponse qp = facettedServer.query(solrQuery);
  1737. SolrDocumentList solrDocumentList = qp.getResults(); //should only have one thing in it, the one email
  1738. SolrDocument solrDocumentOfThatEmail = solrDocumentList.get(0);
  1739. String threadIndex = getStr("art_threadIndex_str", solrDocumentOfThatEmail);
  1740. String threadTopic = getStr("art_threadTopic_str", solrDocumentOfThatEmail);
  1741. /*
  1742. Now that we have the threadIndex and topic, use Joosep's code to get back a list of SolrDocuments that represents that email chain.
  1743. */
  1744. ArrayList<SolrDocument> emailChain = null; //Call Joosep's code.
  1745. return response;
  1746. }
  1747.  
  1748. public JSONObject caseAndCustodian(HttpServletRequest request) throws JSONException {
  1749. JSONObject response = new JSONObject();
  1750.  
  1751. String email = request.getParameter("email");
  1752. String userName = request.getParameter("user_id");
  1753. String caseString = request.getParameter("case");
  1754. String custodianString = request.getParameter("custodian");
  1755. String fileName = request.getParameter("fileName");
  1756. if (fileName == null) {
  1757. fileName = "TestFile";
  1758. }
  1759. String pathForUpload = userName + "/" + caseString + "/" + custodianString + "/" + fileName;
  1760.  
  1761. logger.info("Generating upload url for path '" + pathForUpload + "'");
  1762. String nameOfContextFile = "context_" + this.getClass().getSimpleName() + ".xml";
  1763. ApplicationContext applicationContext = new ClassPathXmlApplicationContext(nameOfContextFile);
  1764. Exporter exporter = applicationContext.getBean("exporter", Exporter.class);
  1765. URL presignedURL = null;
  1766. try {
  1767. presignedURL = exporter.generateUploadUrl(pathForUpload);
  1768. } catch (Throwable e) {
  1769. logger.error("Error generating url or uploading to path " + pathForUpload, e);
  1770. }
  1771.  
  1772. // logger.info("Sending email");
  1773. // String messageSubject = "URL for uploading to S3";
  1774. // String messageBody = "Click on the link below to upload a file to the path {" + pathForUpload + "}"
  1775. // + "\n" + presignedURL;
  1776. // sendEmail(email, messageSubject, messageBody);
  1777. response.put("URL", presignedURL);
  1778. return response;
  1779. }
  1780.  
  1781. public String processPutRequest(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException {
  1782. /*
  1783. You can't get stuff out of Put's like you can with POSTs so here's a bit of code to take the data and put it into a map.
  1784. */
  1785. BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
  1786. String data = br.readLine();
  1787. String[] keyValuesArray = data.split("&");
  1788. Map<String, String> keyValuesMap = new HashMap<>();
  1789. for (String keyValue : keyValuesArray) {
  1790. String[] keyValueArray = keyValue.split("=");
  1791. String key = URLDecoder.decode(keyValueArray[0], "UTF-8");
  1792. String value = URLDecoder.decode(keyValueArray[1], "UTF-8");
  1793. keyValuesMap.put(key, value);
  1794. }
  1795. System.out.println(keyValuesMap);
  1796.  
  1797. String requestType = keyValuesMap.get("requestType");
  1798. JSONObject responseObject = new JSONObject();
  1799. String status = "no response";
  1800.  
  1801. if (requestType == null) {
  1802. responseObject.put("response", "ERROR : Response type is not set.");
  1803. } else {
  1804. responseObject.put("requestType", requestType);
  1805. try {
  1806. switch (requestType) {
  1807. default:
  1808. responseObject.put("response", "PUTs are not supported as of yet.");
  1809. }
  1810. } catch (Throwable th) {
  1811. logger.error("Error while processing " + requestType + " request.", th);
  1812. responseObject.put("error", th.getMessage());
  1813. }
  1814. }
  1815. String encodedResponseString = responseObject.toString();
  1816. encodedResponseString = unescapeJsonToStringString(encodedResponseString);
  1817. logger.trace("RESPONSE: " + encodedResponseString);
  1818. System.gc();
  1819. return encodedResponseString;
  1820.  
  1821. }
  1822.  
  1823. public String processRequest(HttpServletRequest request, HttpServletResponse response) throws SolrServerException, IOException, JSONException {
  1824. String requestType = request.getParameter("requestType");
  1825. JSONObject responseObject = new JSONObject();
  1826. String status = "no response";
  1827. printOutHttpServletRequest(request);
  1828.  
  1829. if (requestType == null) {
  1830. responseObject.put("response", "ERROR : Response type is not set.");
  1831. } else {
  1832. responseObject.put("requestType", requestType);
  1833. try {
  1834. switch (requestType) {
  1835. case "fileNav":
  1836. responseObject.put("response", fileNavigationRequest(request));
  1837. break;
  1838. case "editQuery":
  1839. responseObject.put("response", editQuery(request, requestType));
  1840. break;
  1841. case "modifyFacet":
  1842. responseObject.put("response", modifyFacet(request));
  1843. break;
  1844. case "editTag":
  1845. responseObject.put("response", editTag(request));
  1846. break;
  1847. case "userAction":
  1848. responseObject.put("response", userAction(request));
  1849. break;
  1850. case "exportFiles":
  1851. responseObject.put("response", exportFiles(request));
  1852. break;
  1853. case "showEmailChain":
  1854. responseObject.put("response", showEmailChain(request));
  1855. break;
  1856. case "uploadLegalFiles":
  1857. responseObject.put("response", caseAndCustodian(request));
  1858. break;
  1859. default:
  1860. responseObject.put("response", "ERROR : Unrecognized request type '" + requestType + "'");
  1861. }
  1862. } catch (Throwable th) {
  1863. logger.error("Error while processing " + requestType + " request.", th);
  1864. responseObject.put("error", th.getMessage());
  1865. }
  1866. }
  1867. String encodedResponseString = responseObject.toString();
  1868. encodedResponseString = unescapeJsonToStringString(encodedResponseString);
  1869. logger.trace("RESPONSE: " + encodedResponseString);
  1870. System.gc();
  1871. return encodedResponseString;
  1872. }
  1873.  
  1874. // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  1875. /**
  1876. * Handles the HTTP <code>GET</code> method.
  1877. *
  1878. * @param request servlet request
  1879. * @param response servlet response
  1880. * @throws ServletException if a servlet-specific error occurs
  1881. * @throws IOException if an I/O error occurs
  1882. */
  1883. @Override
  1884. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  1885. throws ServletException, IOException {
  1886. request.setCharacterEncoding("UTF-8");
  1887. response.setContentType("text/html;charset=UTF-8");
  1888. try {
  1889. String encodedString = processRequest(request, response);
  1890. try (PrintWriter out = response.getWriter()) {
  1891. out.println(encodedString);
  1892. }
  1893. } catch (Throwable ex) {
  1894. logger.error("Error while handling Get request.", ex);
  1895. response.sendError(409, "Failed to process your get request. Check the back end logs for the stack trace");
  1896. // TODO: { "message":"OK, why not use an actual JSON parser????", "background":"delirious screaming", "category":"mindless reinventing of stone age wheels." }
  1897. String errorMessage = "{\n"
  1898. + " \"errors\":\n"
  1899. + " [{\"statusCode\":\"409\",\n"
  1900. + " \"errorMessage\":\"Failed to process your get request. Check the back end logs for the stack trace.\"}]\n"
  1901. + " }";
  1902. try (PrintWriter out = response.getWriter()) {
  1903. out.println(errorMessage);
  1904. }
  1905. }
  1906. System.gc();
  1907. }
  1908.  
  1909. @Override
  1910. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  1911. throws ServletException, IOException {
  1912. request.setCharacterEncoding(("UTF-8"));
  1913. response.setContentType("text/html;charset=UTF-8");
  1914. try {
  1915. String encodedString = processRequest(request, response);
  1916. try (PrintWriter out = response.getWriter()) {
  1917. out.println(encodedString);
  1918. }
  1919. } catch (Throwable ex) {
  1920. logger.error("Error while handling Post request.", ex);
  1921. response.sendError(409, "Failed to process your Post request. Check the back end logs for the stack trace");
  1922. String errorMessage = "{\n"
  1923. + " \"errors\":\n"
  1924. + " [{\"statusCode\":\"409\",\n"
  1925. + " \"errorMessage\":\"Failed to process your Post request. Check the back end logs for the stack trace.\"}]\n"
  1926. + " }";
  1927. try (PrintWriter out = response.getWriter()) {
  1928. out.println(errorMessage);
  1929. }
  1930. }
  1931. System.gc();
  1932. }
  1933.  
  1934. @Override
  1935. protected void doPut(HttpServletRequest request, HttpServletResponse response)
  1936. throws ServletException, IOException {
  1937. request.setCharacterEncoding(("UTF-8"));
  1938. response.setContentType("text/html;charset=UTF-8");
  1939. try {
  1940. String encodedString = processPutRequest(request, response);
  1941. try (PrintWriter out = response.getWriter()) {
  1942. out.println(encodedString);
  1943. }
  1944. } catch (Throwable ex) {
  1945. logger.error("Error while handling Put request.", ex);
  1946. response.sendError(409, "Failed to process your Put request. Check the back end logs for the stack trace");
  1947. String errorMessage = "{\n"
  1948. + " \"errors\":\n"
  1949. + " [{\"statusCode\":\"409\",\n"
  1950. + " \"errorMessage\":\"Failed to process your Put request. Check the back end logs for the stack trace.\"}]\n"
  1951. + " }";
  1952. try (PrintWriter out = response.getWriter()) {
  1953. out.println(errorMessage);
  1954. }
  1955. }
  1956. System.gc();
  1957. }
  1958.  
  1959. /**
  1960. * Returns a short description of the Servlet.
  1961. *
  1962. * @return a String containing Servlet description
  1963. */
  1964. @Override
  1965. public String getServletInfo() {
  1966. return "Main SST Servlet that will handle facet-value modifications as well as saving targets, queries, and tags. Will likely do other stuff in the future as well.";
  1967. }// </editor-fold>
  1968. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement