List of usage examples for javax.servlet.http HttpServletRequest getReader
public BufferedReader getReader() throws IOException;
BufferedReader
. From source file:servlets.Analysis_servlets.java
private void delete_analysis_handler(HttpServletRequest request, HttpServletResponse response) throws IOException { try {// w w w . j av a 2s. c o m boolean ROLLBACK_NEEDED = false; DAO daoInstance = null; boolean removable = true; String loggedUser = null; String analysisID = null; try { /** * ******************************************************* * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF * ERROR --> throws exception if not valid session, GO TO STEP * ELSE --> GO TO STEP 2 * ******************************************************* */ JsonParser parser = new JsonParser(); JsonObject requestData = (JsonObject) parser.parse(request.getReader()); loggedUser = requestData.get("loggedUser").getAsString(); String sessionToken = requestData.get("sessionToken").getAsString(); if (!checkAccessPermissions(loggedUser, sessionToken)) { throw new AccessControlException("Your session is invalid. User or session token not allowed."); } String loggedUserID = requestData.get("loggedUserID").getAsString(); String experimentID = requestData.get("currentExperimentID").getAsString(); analysisID = requestData.get("analysis_id").getAsString(); /** * ******************************************************* * STEP 2 Get THE ANALYSIS Object from DB. IF ERROR --> throws * MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3 * ******************************************************* */ boolean loadRecursive = true; Object[] params = { loadRecursive }; daoInstance = DAOProvider.getDAOByName("Analysis"); Analysis analysis = (Analysis) daoInstance.findByID(analysisID, params); if (!analysis.isOwner(loggedUserID) && !loggedUserID.equals("admin")) { throw new AccessControlException( "Cannot remove selected Analysis. Current user has not privileges over this element."); } /** * ******************************************************* * STEP 3 Check if the user + the users in the remove_requests * list are the owners for all the steps. If at least one of the * steps has an user not in the list and the step is not * imported, then we add the user to the remove_requests. * Otherwise, we can remove the steps (or unlink) and the * analysis. * ******************************************************* */ Set<String> users = new HashSet<String>(Arrays.asList(analysis.getRemoveRequests())); users.add(loggedUserID); //TODO: add admin user !loggedUserID.equalsIgnoreCase("admin") for (Step step : analysis.getNonProcessedData()) { if (step.getAnalysisID().equalsIgnoreCase(analysisID)) { //If not imported step boolean isOwner = false; for (String user : users) { //Check if at least one of the users that want to remove is owner isOwner = isOwner || step.isOwner(user); } if (!isOwner) { removable = false; break; } } } if (removable) { for (Step step : analysis.getProcessedData()) { if (step.getAnalysisID().equalsIgnoreCase(analysisID)) { //If not imported step boolean isOwner = false; for (String user : users) { //Check if at least one of the users that want to remove is owner isOwner = isOwner || step.isOwner(user); } if (!isOwner) { removable = false; break; } } } } /** * ******************************************************* * STEP 4 If the analysis is removable, then we proceed to * remove the analysis (includes unlinking shared steps). * Otherwise, we update the list of remove_requests * ******************************************************* */ daoInstance = DAOProvider.getDAOByName("Analysis"); daoInstance.disableAutocommit(); ROLLBACK_NEEDED = true; if (removable) { ((Analysis_JDBCDAO) daoInstance).remove(analysis); //DELETE THE DATA DIRECTORY File file = new File( DATA_LOCATION + IMAGE_FILES_LOCATION.replaceAll("<experiment_id>", experimentID) + analysisID + "_prev.jpg"); if (file.exists()) { file.delete(); } file = new File(DATA_LOCATION + IMAGE_FILES_LOCATION.replaceAll("<experiment_id>", experimentID) + analysisID + ".png"); if (file.exists()) { file.delete(); } } else { ((Analysis_JDBCDAO) daoInstance).updateRemoveRequests(analysisID, users.toArray(new String[] {})); } /** * ******************************************************* * STEP 5 COMMIT CHANGES TO DATABASE. throws SQLException IF * ERROR --> throws SQL Exception, GO TO STEP ? ELSE --> GO TO * STEP 6 * ******************************************************* */ daoInstance.doCommit(); } catch (Exception e) { ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "remove_analysis_handler", e.getMessage()); } finally { /** * ******************************************************* * STEP 7b CATCH ERROR, CLEAN CHANGES. throws SQLException * ******************************************************* */ if (ServerErrorManager.errorStatus()) { response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); if (ROLLBACK_NEEDED) { daoInstance.doRollback(); } } else { JsonObject obj = new JsonObject(); obj.add("success", new JsonPrimitive(true)); obj.add("removed", new JsonPrimitive(removable)); response.getWriter().print(obj.toString()); } BlockedElementsManager.getBlockedElementsManager().unlockObject(analysisID, loggedUser); /** * ******************************************************* * STEP 9 Close connection. * ******************************************************** */ if (daoInstance != null) { daoInstance.closeConnection(); } } //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE } catch (Exception e) { ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "remove_analysis_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }
From source file:servlets.Samples_servlets.java
private void get_all_bioconditions_handler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//from w ww.j a v a2 s . c o m DAO dao_instance = null; ArrayList<Object> bioconditionsList = null; try { JsonParser parser = new JsonParser(); JsonObject requestData = (JsonObject) parser.parse(request.getReader()); String loggedUser = requestData.get("loggedUser").getAsString(); String sessionToken = requestData.get("sessionToken").getAsString(); /** * ******************************************************* * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF * ERROR --> throws exception if not valid session, GO TO STEP * 5b ELSE --> GO TO STEP 2 * ******************************************************* */ if (!checkAccessPermissions(loggedUser, sessionToken)) { throw new AccessControlException("Your session is invalid. User or session token not allowed."); } /** * ******************************************************* * STEP 2 Get ALL THE ANALYSIS Object from DB. IF ERROR --> * throws MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3 * ******************************************************* */ dao_instance = DAOProvider.getDAOByName("BioCondition"); boolean loadRecursive = false; if (requestData.has("recursive")) { loadRecursive = requestData.get("recursive").getAsBoolean(); } Object[] params = { loadRecursive }; bioconditionsList = dao_instance.findAll(params); } catch (Exception e) { ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "get_all_bioconditions_handler", e.getMessage()); } finally { /** * ******************************************************* * STEP 3b CATCH ERROR. GO TO STEP 4 * ******************************************************* */ if (ServerErrorManager.errorStatus()) { response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } else { /** * ******************************************************* * STEP 3A WRITE RESPONSE ERROR. GO TO STEP 4 * ******************************************************* */ String bioconditionsJSON = "["; for (int i = 0; i < bioconditionsList.size(); i++) { bioconditionsJSON += ((BioCondition) bioconditionsList.get(i)).toJSON() + ((i < bioconditionsList.size() - 1) ? "," : ""); } bioconditionsJSON += "]"; response.getWriter().print(bioconditionsJSON); } /** * ******************************************************* * STEP 4 Close connection. * ******************************************************** */ if (dao_instance != null) { dao_instance.closeConnection(); } } //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE } catch (Exception e) { ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "get_all_bioconditions_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }
From source file:org.jbpm.designer.web.server.UUIDBasedRepositoryServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String profileName = Utils.getDefaultProfileName(req.getParameter("profile")); String actionParam = req.getParameter("action"); String preProcessingParam = req.getParameter("pp"); if (preProcessingParam == null) { preProcessingParam = "ReadOnlyService"; }/* w w w . j a v a2 s . c o m*/ if (actionParam != null && actionParam.equals("toXML")) { if (profile == null) { profile = _profileService.findProfile(req, profileName); } String json = req.getParameter("data"); String xml = ""; try { xml = _repository.toXML(json, profile, preProcessingParam); } catch (Exception e) { _logger.error("Error transforming to XML: " + e.getMessage()); } StringWriter output = new StringWriter(); output.write(xml); resp.setContentType("application/xml"); resp.setCharacterEncoding("UTF-8"); resp.setStatus(200); resp.getWriter().print(output.toString()); } else if (actionParam != null && actionParam.equals("checkErrors")) { String retValue = "false"; if (profile == null) { profile = _profileService.findProfile(req, profileName); } String json = req.getParameter("data"); try { String xmlOut = profile.createMarshaller().parseModel(json, preProcessingParam); String jsonIn = profile.createUnmarshaller().parseModel(xmlOut, profile, preProcessingParam); if (jsonIn == null || jsonIn.length() < 1) { retValue = "true"; } } catch (Throwable t) { retValue = "true"; _logger.error("Exception parsing process: " + t.getMessage()); } resp.setContentType("text/plain"); resp.setCharacterEncoding("UTF-8"); resp.setStatus(200); resp.getWriter().print(retValue); } else { BufferedReader reader = req.getReader(); StringWriter reqWriter = new StringWriter(); char[] buffer = new char[4096]; int read; while ((read = reader.read(buffer)) != -1) { reqWriter.write(buffer, 0, read); } String data = reqWriter.toString(); try { JSONObject jsonObject = new JSONObject(data); String json = (String) jsonObject.get("data"); String svg = (String) jsonObject.get("svg"); String uuid = (String) jsonObject.get("uuid"); boolean autosave = jsonObject.getBoolean("savetype"); if (profile == null) { profile = _profileService.findProfile(req, profileName); } _repository.save(req, uuid, json, svg, profile, autosave); } catch (JSONException e1) { throw new ServletException(e1); } } }
From source file:servlets.Analysis_servlets.java
private void import_analysis_handler(HttpServletRequest request, HttpServletResponse response) throws IOException { try {//from w w w. j a v a 2 s. c o m String lockedID = null; boolean ROLLBACK_NEEDED = false; DAO daoInstance = null; Analysis analysis = null; try { /** * ******************************************************* * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF * ERROR --> throws exception if not valid session, GO TO STEP * 5b ELSE --> GO TO STEP 2 * ******************************************************* */ Map<String, Cookie> cookies = this.getCookies(request); JsonParser parser = new JsonParser(); JsonObject requestData = (JsonObject) parser.parse(request.getReader()); String loggedUser, loggedUserID = null, sessionToken; if (cookies != null) { loggedUser = cookies.get("loggedUser").getValue(); sessionToken = cookies.get("sessionToken").getValue(); loggedUserID = cookies.get("loggedUserID").getValue(); } else { String apicode = requestData.get("apicode").getAsString(); apicode = new String(Base64.decodeBase64(apicode)); loggedUser = apicode.split(":")[0]; sessionToken = apicode.split(":")[1]; } if (!checkAccessPermissions(loggedUser, sessionToken)) { throw new AccessControlException("Your session is invalid. User or session token not allowed."); } if (loggedUserID == null) { daoInstance = DAOProvider.getDAOByName("User"); loggedUserID = ((User) daoInstance.findByID(loggedUser, new Object[] { null, false, true })) .getUserID(); } String experimentID = requestData.get("experiment_id").getAsString(); String origin = requestData.get("origin").getAsString(); /** * ******************************************************* * STEP 1 CHECK IF THE USER EXISTS AND IF EXPERIMENT IS VALID * ******************************************************* */ daoInstance = DAOProvider.getDAOByName("Experiment"); Experiment experiment = (Experiment) daoInstance.findByID(experimentID, null); if (experiment == null) { throw new AccessControlException(experimentID + " is not a valid experiment identifier."); } else if (!experiment.isOwner(loggedUserID) && !experiment.isMember(loggedUserID)) { throw new AccessControlException("User " + loggedUserID + " is not a valid member of the experiment " + experimentID + "."); } /** * ******************************************************* * STEP 2 Get the new ID for the ANALYSIS. IF ERROR --> throws * SQL Exception, GO TO STEP 5b ELSE --> GO TO STEP 3 * ******************************************************* */ daoInstance = DAOProvider.getDAOByName("Analysis"); lockedID = daoInstance.getNextObjectID(null); requestData.add("analysis_id", new JsonPrimitive(lockedID)); /** * ******************************************************* * STEP 3 Get the ANALYSIS Object by parsing the JSON data. IF * ERROR --> throws JsonParseException, GO TO STEP 5b ELSE --> * GO TO STEP 4 * ******************************************************* */ analysis = Analysis.parseAnalysisData(origin, loggedUserID, requestData); analysis.updateAnalysisID(lockedID); analysis.setAssociated_experiment(experimentID); /** * ******************************************************* * STEP 4 Add the new ANALYSIS Object in the DATABASE. IF ERROR * --> throws SQL Exception, GO TO STEP 5b ELSE --> GO TO STEP 5 * ******************************************************* */ daoInstance.disableAutocommit(); ROLLBACK_NEEDED = true; daoInstance.insert(analysis); /** * ******************************************************* * STEP 4 Add a new message. IF ERROR * --> throws SQL Exception, GO TO STEP 5b ELSE --> GO TO STEP 5 * ******************************************************* */ Message message = new Message(); message.setUserID(loggedUserID); message.setType("info"); message.setSender("STATegraEMS notifications"); message.setTo(loggedUserID); message.setSubject("New analysis imported from " + origin); message.setContent("A new analysis called \"" + analysis.getAnalysisName() + "\" has been created for experiment " + experimentID + " using an external tool (data imported from " + origin + ")."); daoInstance = DAOProvider.getDAOByName("Message"); daoInstance.insert(message); /** * ******************************************************* * STEP 5 COMMIT CHANGES TO DATABASE. throws SQLException IF * ERROR --> throws SQL Exception, GO TO STEP 5b ELSE --> GO TO * STEP 6 * ******************************************************* */ daoInstance.doCommit(); } catch (Exception e) { ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "import_analysis_handler", e.getMessage()); } finally { /** * ******************************************************* * STEP 5b CATCH ERROR, CLEAN CHANGES. throws SQLException * ******************************************************* */ if (ServerErrorManager.errorStatus()) { response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); if (ROLLBACK_NEEDED) { daoInstance.doRollback(); } } else { JsonObject obj = new JsonObject(); obj.add("newID", new JsonPrimitive(lockedID)); response.getWriter().print(obj.toString()); } /** * UNLOCK THE IDS */ if (lockedID != null) { BlockedElementsManager.getBlockedElementsManager().unlockID(lockedID); } /** * ******************************************************* * STEP 6 Close connection. * ******************************************************** */ if (daoInstance != null) { daoInstance.closeConnection(); } } //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE } catch (Exception e) { ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "import_analysis_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }
From source file:servlets.Analysis_servlets.java
private void update_analysis_handler(HttpServletRequest request, HttpServletResponse response) throws IOException { try {//from ww w . ja v a2s .c om ArrayList<String> BLOCKED_IDs = new ArrayList<String>(); boolean ROLLBACK_NEEDED = false; DAO daoInstance1 = null; DAO daoInstance2 = null; try { /** * ******************************************************* * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF * ERROR --> throws exception if not valid session, GO TO STEP * 6b ELSE --> GO TO STEP 2 * ******************************************************* */ JsonParser parser = new JsonParser(); JsonObject requestData = (JsonObject) parser.parse(request.getReader()); Map<String, Cookie> cookies = this.getCookies(request); String loggedUser = cookies.get("loggedUser").getValue(); String sessionToken = cookies.get("sessionToken").getValue(); String loggedUserID = cookies.get("loggedUserID").getValue(); if (!checkAccessPermissions(loggedUser, sessionToken)) { throw new AccessControlException("Your session is invalid. User or session token not allowed."); } /** * ******************************************************* * STEP 3 Get the Object by parsing the JSON data. IF ERROR --> * throws JsonParseException, GO TO STEP 6b ELSE --> GO TO STEP * 4 ******************************************************* */ Analysis analysis = Analysis.fromJSON(requestData.get("analysis_json_data")); daoInstance1 = DAOProvider.getDAOByName("Analysis"); //CHECK IF CURRENT USER IS A VALID OWNER (AVOID HACKING) boolean loadRecursive = true; Analysis analysisAux = (Analysis) daoInstance1.findByID(analysis.getAnalysisID(), new Object[] { loadRecursive }); if (!analysisAux.isOwner(loggedUserID) && !loggedUserID.equals("admin")) { throw new AccessControlException( "Cannot update selected Analysis. Current user has not privileges over this element."); } if ("pending".equalsIgnoreCase(analysis.getStatus())) { analysis.setStatus("open"); } /** * ******************************************************* * STEP 4 READ ALL STEPS AND CREATE THE LIST OF TASKS. * ******************************************************* */ ArrayList<Step> to_be_created_steps = new ArrayList<Step>(); ArrayList<Step> to_be_updated_steps = new ArrayList<Step>(); ArrayList<String> to_be_deleted_steps = new ArrayList<String>(); for (Step step : analysis.getNonProcessedData()) { if ("new_deleted".equals(step.getStatus())) { continue; //ignore } else if ("deleted".equals(step.getStatus()) || "edited_deleted".equals(step.getStatus())) { to_be_deleted_steps.add(step.getStepID()); //DELETES THE STEP } else if ("new".equals(step.getStatus())) { to_be_created_steps.add(step); //CREATES THE STEP } else { if ("edited".equals(step.getStatus())) { to_be_updated_steps.add(step); } } } for (Step step : analysis.getProcessedData()) { if ("new_deleted".equals(step.getStatus())) { continue; //ignore } else if ("deleted".equals(step.getStatus()) || "edited_deleted".equals(step.getStatus())) { to_be_deleted_steps.add(step.getStepID()); //DELETES THE STEP } else if ("new".equals(step.getStatus())) { to_be_created_steps.add(step); //CREATES THE STEP } else { if ("edited".equals(step.getStatus())) { to_be_updated_steps.add(step); } } } /** * ******************************************************* * STEP 5 GET ALL THE IDS FOR THE NEW STEPS AND UPDATE THE * INFORMATION * ******************************************************* */ daoInstance1 = DAOProvider.getDAOByName("Analysis"); daoInstance2 = DAOProvider.getDAOByName("Step"); Collections.sort(to_be_created_steps); for (Step step : to_be_created_steps) { String old_id = step.getStepID(); String new_id = daoInstance2.getNextObjectID(new Object[] { analysis.getAnalysisID() }); BLOCKED_IDs.add(new_id); step.setStepID(new_id); String[] usedData; for (Step stepAux : analysis.getNonProcessedData()) { if (stepAux instanceof IntermediateData) { usedData = ((IntermediateData) stepAux).getUsedData(); int pos = Arrays.asList(usedData).indexOf(old_id); if (pos != -1) { usedData[pos] = new_id; } } } for (Step stepAux : analysis.getProcessedData()) { if (stepAux instanceof ProcessedData) { usedData = ((ProcessedData) stepAux).getUsedData(); int pos = Arrays.asList(usedData).indexOf(old_id); if (pos != -1) { usedData[pos] = new_id; } } } } /** * ******************************************************* * STEP 5 ADD, UPDATE AND REMOVE THE NPD instances IN DATABASE. * Must be in this order because: -- If we change the used data * for a specified step adding a to be created step, must be * inserted first. -- If we change the used data removing an * used step and then we delete this step (the used one), we * must update first (because of foreign keys) With this method, * when an step is removed, the step_id is lost. Because the * "getNextStepID" function is called before removing ADDED * steps must be ordered from less to greater step_number * <p/> * IF ERROR --> throws SQL Exception, GO TO STEP ? ELSE --> GO * TO STEP 6 * ******************************************************* */ daoInstance1.disableAutocommit(); ROLLBACK_NEEDED = true; daoInstance1.update(analysis); /** * ******************************************************* * STEP 6 APPLY THE STEP TASKS IN DATABASE. IF ERROR --> throws * SQL Exception, GO TO STEP ? ELSE --> GO TO STEP 8 * ******************************************************* */ ((Step_JDBCDAO) daoInstance2).insert(to_be_created_steps.toArray(new Step[] {})); ((Step_JDBCDAO) daoInstance2).remove(to_be_deleted_steps.toArray(new String[] {})); ((Step_JDBCDAO) daoInstance2).update(to_be_updated_steps.toArray(new Step[] {})); /** * ******************************************************* * STEP 7 COMMIT CHANGES TO DATABASE. throws SQLException IF * ERROR --> throws SQL Exception, GO TO STEP ? ELSE --> GO TO * STEP 8 * ******************************************************* */ daoInstance1.doCommit(); } catch (Exception e) { if (e.getClass().getSimpleName().equals("MySQLIntegrityConstraintViolationException")) { ServerErrorManager.handleException(null, null, null, "Unable to update the Analysis information."); } else { ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "update_analysis_handler", e.getMessage()); } } finally { /** * ******************************************************* * STEP 7b CATCH ERROR, CLEAN CHANGES. throws SQLException * ******************************************************* */ if (ServerErrorManager.errorStatus()) { response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); for (String BLOCKED_ID : BLOCKED_IDs) { BlockedElementsManager.getBlockedElementsManager().unlockID(BLOCKED_ID); } if (ROLLBACK_NEEDED) { daoInstance1.doRollback(); } } else { JsonObject obj = new JsonObject(); obj.add("success", new JsonPrimitive(true)); response.getWriter().print(obj.toString()); } for (String BLOCKED_ID : BLOCKED_IDs) { BlockedElementsManager.getBlockedElementsManager().unlockID(BLOCKED_ID); } /** * ******************************************************* * STEP 9 Close connection. * ******************************************************** */ if (daoInstance1 != null) { daoInstance1.closeConnection(); } } //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE } catch (Exception e) { ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "update_analysis_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }
From source file:servlets.Samples_servlets.java
private void remove_biocondition_handler(HttpServletRequest request, HttpServletResponse response) throws IOException { try {//from w w w . j a va 2s.c om String biocondition_id = ""; String loggedUser = ""; boolean ROLLBACK_NEEDED = false; DAO dao_instance = null; try { JsonParser parser = new JsonParser(); JsonObject requestData = (JsonObject) parser.parse(request.getReader()); loggedUser = requestData.get("loggedUser").getAsString(); String loggedUserID = requestData.get("loggedUserID").getAsString(); String sessionToken = requestData.get("sessionToken").getAsString(); /** * ******************************************************* * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF * ERROR --> throws exception if not valid session, GO TO STEP * 4b ELSE --> GO TO STEP 2 * ******************************************************* */ if (!checkAccessPermissions(loggedUser, sessionToken)) { throw new AccessControlException("Your session is invalid. User or session token not allowed."); } /** * ******************************************************* * STEP 2 Try to lock the Object . IF FAILED --> throws * exception, GO TO STEP 3b ELSE --> GO TO STEP 3 * ******************************************************* */ biocondition_id = requestData.get("biocondition_id").getAsString(); boolean alreadyLocked = !BlockedElementsManager.getBlockedElementsManager() .lockObject(biocondition_id, loggedUserID); if (alreadyLocked) { String locker_id = BlockedElementsManager.getBlockedElementsManager() .getLockerID(biocondition_id); if (!locker_id.equals(loggedUser)) { throw new Exception( "Sorry but this biological condition is being edited by other user. Please try later."); } } dao_instance = DAOProvider.getDAOByName("Biocondition"); dao_instance.disableAutocommit(); ROLLBACK_NEEDED = true; boolean loadRecursive = true; Object[] params = { loadRecursive }; BioCondition bioCondition = (BioCondition) dao_instance.findByID(biocondition_id, params); //Check if user is member or owner if (bioCondition.isOwner(loggedUserID) || "admin".equals(loggedUserID)) { if (bioCondition.getOwners().length == 1 || "admin".equals(loggedUserID)) { //If is the last owner or the admin, remove the entire experiment dao_instance.remove(biocondition_id); } else { //else just remove the entry in the table of ownerships ((BioCondition_JDBCDAO) dao_instance).removeOwnership(loggedUserID, biocondition_id); } } /** * ******************************************************* * STEP 9 COMMIT CHANGES TO DATABASE. throws SQLException IF * ERROR --> throws SQL Exception, GO TO STEP ? ELSE --> GO TO * STEP 10 * ******************************************************* */ dao_instance.doCommit(); } catch (Exception e) { if (e.getClass().getSimpleName().equals("MySQLIntegrityConstraintViolationException")) { ServerErrorManager.handleException(null, null, null, "Unable to remove the selected Biocondition.</br>This Biocondition contains one or more Analytical samples that are being used by some Raw data.</br>Remove first those Raw data and try again later."); } else if (e.getClass().getSimpleName().equals("AccessControlException")) { ServerErrorManager.handleException(null, null, null, e.getMessage()); } else { ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "remove_biocondition_handler", e.getMessage()); } } finally { /** * ******************************************************* * STEP 4b CATCH ERROR. GO TO STEP 5 * ******************************************************* */ if (ServerErrorManager.errorStatus()) { response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); if (ROLLBACK_NEEDED) { dao_instance.doRollback(); } } else { JsonObject obj = new JsonObject(); obj.add("success", new JsonPrimitive(true)); response.getWriter().print(obj.toString()); } BlockedElementsManager.getBlockedElementsManager().unlockObject(biocondition_id, loggedUser); /** * ******************************************************* * STEP 11 Close connection. * ******************************************************** */ if (dao_instance != null) { dao_instance.closeConnection(); } } //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE } catch (Exception e) { ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "remove_biocondition_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }
From source file:servlets.Samples_servlets.java
/** * * @param request//from ww w. j a va 2 s. c om * @param response * @throws ServletException * @throws IOException */ private void add_biocondition_handler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String BLOCKED_ID = null; boolean ROLLBACK_NEEDED = false; DAO dao_instance = null; try { JsonParser parser = new JsonParser(); JsonObject requestData = (JsonObject) parser.parse(request.getReader()); String loggedUser = requestData.get("loggedUser").getAsString(); String sessionToken = requestData.get("sessionToken").getAsString(); /** * ******************************************************* * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF * ERROR --> throws exception if not valid session, GO TO STEP * 6b ELSE --> GO TO STEP 2 * ******************************************************* */ if (!checkAccessPermissions(loggedUser, sessionToken)) { throw new AccessControlException("Your session is invalid. User or session token not allowed."); } /** * ******************************************************* * STEP 2 Get the new ID for the BIOCONDITION. IF ERROR --> * throws SQL Exception, GO TO STEP 6b ELSE --> GO TO STEP 3 * ******************************************************* */ dao_instance = DAOProvider.getDAOByName("BioCondition"); String newID = dao_instance.getNextObjectID(null); BLOCKED_ID = newID; /** * ******************************************************* * STEP 3 Get the Object by parsing the JSON data. IF ERROR --> * throws JsonParseException, GO TO STEP 6b ELSE --> GO TO STEP * 4 ******************************************************* */ BioCondition biocondition = BioCondition.fromJSON(requestData.get("biocondition_json_data")); /** * ******************************************************* * STEP 4 Set the object and children ID. IF ERROR --> throws * JsonParseException, GO TO STEP 6b ELSE --> GO TO STEP 5 * ******************************************************* */ //TODO: CAMBIAR COMO EN ANALYSIS (CAMBIAR IDs internamente en BioCondition) biocondition.setBioConditionID(newID); if (biocondition.getAssociatedBioreplicates() != null) { ArrayList<Bioreplicate> bioreplicates = new ArrayList<Bioreplicate>(); int nBioReplicate = 1; for (Bioreplicate bioreplicate : biocondition.getAssociatedBioreplicates()) { if (!"new_deleted".equals(bioreplicate.getStatus())) { bioreplicates.add(bioreplicate); if (bioreplicate.getAssociatedAnalyticalReplicates() != null) { ArrayList<AnalyticalReplicate> analyticalReplicates = new ArrayList<AnalyticalReplicate>(); for (AnalyticalReplicate analyticalReplicate : bioreplicate .getAssociatedAnalyticalReplicates()) { if (!"new_deleted".equals(analyticalReplicate.getStatus())) { analyticalReplicates.add(analyticalReplicate); } } bioreplicate.setAssociatedAnalyticalReplicates( analyticalReplicates.toArray(new AnalyticalReplicate[] {})); } bioreplicate.setBioreplicateID(newID, nBioReplicate); nBioReplicate++; } } biocondition.setAssociatedBioreplicates(bioreplicates.toArray(new Bioreplicate[] {})); } /** * ******************************************************* * STEP 5 Add the new Object in the DATABASE. IF ERROR --> * throws SQL Exception, GO TO STEP 6b ELSE --> GO TO STEP 6 * ******************************************************* */ dao_instance.disableAutocommit(); ROLLBACK_NEEDED = true; dao_instance.insert(biocondition); /** * ******************************************************* * STEP 6 COMMIT CHANGES TO DATABASE. throws SQLException IF * ERROR --> throws SQL Exception, GO TO STEP 6b ELSE --> GO TO * STEP 7 * ******************************************************* */ dao_instance.doCommit(); } catch (Exception e) { ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "add_biocondition_handler", e.getMessage()); } finally { /** * ******************************************************* * STEP 6b CATCH ERROR, CLEAN CHANGES. throws SQLException * ******************************************************* */ if (ServerErrorManager.errorStatus()) { response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); if (ROLLBACK_NEEDED) { dao_instance.doRollback(); } } else { JsonObject obj = new JsonObject(); obj.add("newID", new JsonPrimitive(BLOCKED_ID)); response.getWriter().print(obj.toString()); } if (BLOCKED_ID != null) { BlockedElementsManager.getBlockedElementsManager().unlockID(BLOCKED_ID); } /** * ******************************************************* * STEP 8 Close connection. * ******************************************************** */ if (dao_instance != null) { dao_instance.closeConnection(); } } //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE } catch (Exception e) { ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "add_biocondition_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }
From source file:servlets.File_servlets.java
/** * This function sends a file to an external application (e.g. a Galaxy * server)./*from ww w . j ava 2 s. c o m*/ * * @param request * @param response * @throws IOException */ private void send_file_handler(HttpServletRequest request, HttpServletResponse response) throws IOException { try { DAO daoInstance = null; String errors = ""; try { /** * ******************************************************* * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF * ERROR --> throws exception if not valid session, GO TO STEP * 5b ELSE --> GO TO STEP 2 * ******************************************************* */ Map<String, Cookie> cookies = this.getCookies(request); String loggedUser, loggedUserID = null, sessionToken; loggedUser = cookies.get("loggedUser").getValue(); sessionToken = cookies.get("sessionToken").getValue(); loggedUserID = cookies.get("loggedUserID").getValue(); if (!checkAccessPermissions(loggedUser, sessionToken)) { throw new AccessControlException("Your session is invalid. User or session token not allowed."); } /** * ******************************************************* * STEP 2 Get the Experiment Object from DB. IF ERROR --> throws * MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3 * ******************************************************* */ JsonParser parser = new JsonParser(); JsonObject requestData = (JsonObject) parser.parse(request.getReader()); ArrayList<String> files = new ArrayList<String>(); Iterator<JsonElement> it = requestData.get("files").getAsJsonArray().iterator(); while (it.hasNext()) { files.add(it.next().getAsString()); } String source_id = requestData.get("source_id").getAsString(); daoInstance = DAOProvider.getDAOByName("ExternalSource"); ExternalSource externalSource = (ExternalSource) daoInstance.findByID(source_id, null); //CONFIGURE THE DESTINATION SETTINGS HashMap<String, String> destination_settings = new HashMap<String, String>(); destination_settings.put("type", externalSource.getType()); destination_settings.put("host", externalSource.getUrl()); if (requestData.get("credentials") != null && !"".equals(requestData.get("credentials").getAsString())) { String credentials = requestData.get("credentials").getAsString(); credentials = new String(Base64.decodeBase64(credentials)); destination_settings.put("user", credentials.split(":")[0]); destination_settings.put("pass", (credentials.split(":").length > 1 ? credentials.split(":")[1] : "")); } else { String apikey = requestData.get("apikey").getAsString(); destination_settings.put("apikey", apikey); } String experiment_id; if (request.getParameter("experiment_id") != null) { experiment_id = requestData.get("experiment_id").getAsString(); } else { experiment_id = cookies.get("currentExperimentID").getValue(); } /** * ******************************************************* * STEP 3 Check that the user is a valid owner for the * experiment. * ******************************************************* */ daoInstance = DAOProvider.getDAOByName("Experiment"); Experiment experiment = (Experiment) daoInstance.findByID(experiment_id, null); if (!experiment.isOwner(loggedUserID) && !experiment.isMember(loggedUserID) && !loggedUserID.equals("admin")) { throw new AccessControlException( "Cannot get files for selected study. Current user is not a valid member for study " + experiment_id + "."); } /** * ******************************************************* * STEP 3 SEND THE FILES IN THE SERVER. IF ERROR --> throws * exception if not valid session, GO TO STEP 6b ELSE --> GO TO * STEP 3 * ******************************************************* */ for (String file_path : files) { try { FileManager.getFileManager(DATA_LOCATION).sendFile(file_path, experiment.getDataDirectoryInformation(), destination_settings); } catch (Exception e) { errors += "Failed while sending file " + file_path + "\n"; } } } catch (Exception e) { ServerErrorManager.handleException(e, File_servlets.class.getName(), "send_file_handler", e.getMessage()); } finally { /** * ******************************************************* * STEP 5b CATCH ERROR, CLEAN CHANGES. throws SQLException * ******************************************************* */ if (ServerErrorManager.errorStatus()) { response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } else { JsonObject obj = new JsonObject(); obj.add("success", new JsonPrimitive(true)); obj.add("errors", new JsonPrimitive(errors)); response.getWriter().print(obj.toString()); } } } catch (Exception e) { ServerErrorManager.handleException(e, File_servlets.class.getName(), "send_file_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }
From source file:servlets.Samples_servlets.java
private void lock_biocondition_handler(HttpServletRequest request, HttpServletResponse response) throws IOException { boolean alreadyLocked = false; String locker_id = ""; try {/*w ww . j a v a 2s .com*/ /** * ******************************************************* * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF ERROR * --> throws exception if not valid session, GO TO STEP 5b ELSE --> * GO TO STEP 2 * ******************************************************* */ JsonParser parser = new JsonParser(); JsonObject requestData = (JsonObject) parser.parse(request.getReader()); String loggedUser = requestData.get("loggedUser").getAsString(); String sessionToken = requestData.get("sessionToken").getAsString(); /** * ******************************************************* * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF ERROR * --> throws exception if not valid session, GO TO STEP ELSE --> GO * TO STEP 2 ******************************************************* */ if (!checkAccessPermissions(loggedUser, sessionToken)) { throw new AccessControlException("Your session is invalid. User or session token not allowed."); } /** * ******************************************************* * STEP 2 GET THE OBJECT ID AND TRY TO LOCK IT. IF ERROR --> throws * exception, GO TO STEP ELSE --> GO TO STEP 3 * ******************************************************* */ String biocondition_id = requestData.get("biocondition_id").getAsString(); alreadyLocked = !BlockedElementsManager.getBlockedElementsManager().lockObject(biocondition_id, loggedUser); if (alreadyLocked) { locker_id = BlockedElementsManager.getBlockedElementsManager().getLockerID(biocondition_id); } } catch (Exception e) { ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "lock_biocondition_handler", e.getMessage()); } finally { /** * ******************************************************* * STEP 4b CATCH ERROR. GO TO STEP 5 * ******************************************************* */ if (ServerErrorManager.errorStatus()) { response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } else { /** * ******************************************************* * STEP 3A WRITE RESPONSE . * ******************************************************* */ JsonObject obj = new JsonObject(); if (alreadyLocked) { obj.add("success", new JsonPrimitive(false)); obj.add("reason", new JsonPrimitive(BlockedElementsManager.getErrorMessage())); obj.add("user_id", new JsonPrimitive(locker_id)); } else { obj.add("success", new JsonPrimitive(true)); } response.getWriter().print(obj.toString()); } } }
From source file:petascope.PetascopeInterface.java
@Override public void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException { setServletURL(httpRequest);//from w ww. j a va 2 s . co m setCORSHeader(httpResponse); // NOTE: admin can change Service Prodiver, Identification then session *reloadPage* will exist and value is true HttpSession session = httpRequest.getSession(); if (session.getAttribute("reloadMetadata") != null && Boolean.valueOf(session.getAttribute("reloadMetadata").toString()) == true) { try { meta = new DbMetadataSource(ConfigManager.METADATA_DRIVER, ConfigManager.METADATA_URL, ConfigManager.METADATA_USER, ConfigManager.METADATA_PASS, false); // Then remove session as it does not need anymore session.removeAttribute("reloadMetadata"); } catch (Exception e) { log.error("Stack trace: {}", e); throw new ServletException("Error initializing metadata database", e); } } else { // it is just normal query without updating metadata then session is null meta.clearCache(); } String request = null; String requestBody = null; /* Process the request */ try { try { //Check if this is a wms request and handled it accordingly if (wms13Adapter.handleGetRequests(httpRequest, httpResponse)) { //this is a wms13 request, and it was handled in the handleGetRequests //stop further execution return; } meta.ensureConnection(); requestBody = IOUtils.toString(httpRequest.getReader()); log.trace("POST Request length: {}", httpRequest.getContentLength()); log.trace("POST request body : \n------START REQUEST--------\n{}\n------END REQUEST------\n", requestBody); log.trace("GET Query string : {}", httpRequest.getQueryString()); Map<String, String> params = buildParameterDictionary(requestBody); Map<String, String> paramMap = buildParameterMap(httpRequest); log.trace("Request parameters : {}", params); // GET interface processing String service = paramMap.get(KVPSymbols.KEY_SERVICE); // REST interface checks // get the uri contained after the context name i.e after petascope // in example.com/petascope/rest/wcs/... returns [rest,wcs] String pathInfo = httpRequest.getPathInfo(); log.debug("Analyzing path info \"{}\" for REST interface checks.", pathInfo); // Java API: "This method returns null if there was no extra path information." String[] prsUrl = (null == pathInfo) ? new String[0] : pathInfo.substring(1).split("/"); ArrayList<String> splitURI = new ArrayList<String>(Arrays.asList(prsUrl)); if (service == null && splitURI.size() > 1 && (splitURI.get(0).equalsIgnoreCase(RESTProtocolExtension.REST_PROTOCOL_WCS_IDENTIFIER) || splitURI.get(0).equals(RESTProtocolExtension.REST_PROTOCOL_WCPS_IDENTIFIER))) { service = splitURI.get(0).toUpperCase(); } if (service != null) { // Removed WPS support as it doesn't work. Using 52n instead -- DM 2012-may-24 // if (service.equals("WPS")) { // WpsServer wpsServer = new WpsServer(httpResponse, httpRequest); // request = wpsServer.request; // } else if (service.equals(petascope.wcs2.parsers.BaseRequest.SERVICE)) { // extract version String version = null; String operation = paramMap.get(WCPS_REQUEST_GET_PARAMETER); //This might be a REST operation, try to get the operation from the uri if (operation == null && splitURI.size() > 2) { operation = RESTProtocolExtension .mapRestResourcesToCoverageOperation(httpRequest.getRequestURI()); } if (operation.equals(RequestHandler.GET_CAPABILITIES)) { version = paramMap.get(KVPSymbols.KEY_ACCEPTVERSIONS); if (version == null && splitURI.size() > 1) { version = splitURI.get(1); } log.trace(KVPSymbols.KEY_ACCEPTVERSIONS + ": " + version); if (version == null) { version = ConfigManager.WCS_DEFAULT_VERSION; } else { String[] versions = version.split(KVPSymbols.VERSIONS_SEP); version = ""; for (String v : versions) { if (ConfigManager.WCS_VERSIONS.contains(v) && !v.startsWith("1")) { // the WCS 1.1 server doesn't support GET-KVP version = v; break; } } } } else if (operation.equals(RequestHandler.DESCRIBE_COVERAGE) || operation.equals(RequestHandler.PROCESS_COVERAGE) || operation.equals(RequestHandler.GET_COVERAGE) || operation.equals(RequestHandler.INSERT_COVERAGE) || operation.equals(RequestHandler.DELETE_COVERAGE) || operation.equals(RequestHandler.UPDATE_COVERAGE)) { version = paramMap.get(KVPSymbols.KEY_VERSION); if (version == null && splitURI.size() > 1) { version = splitURI.get(1); } } // handle request request = StringUtil.urldecode(httpRequest.getQueryString(), httpRequest.getContentType()); handleWcsRequest(version, paramMap.get(WCPS_REQUEST_GET_PARAMETER), request, httpResponse, httpRequest); return; } } // To preserve compatibility with previous client versions, we allow // GET requests with parameter "query" String request2 = null; request2 = paramMap.get(WCPS_QUERY_GET_PARAMETER); if (request2 == null) { request2 = StringUtil.urldecode(params.get(WCPS_QUERY_GET_PARAMETER), httpRequest.getContentType()); } // splitURI list can be of size 0 if there is not path info in the HTTP request. if (request2 == null && splitURI.size() > 0 && splitURI.get(0).equalsIgnoreCase(RESTProtocolExtension.REST_PROTOCOL_WCPS_IDENTIFIER)) { if (splitURI.size() > 2 && splitURI.get(1).equals(RESTProtocolExtension.REST_PROTOCOL_WCPS_IDENTIFIER)) { String queryDecoded = StringUtil.urldecode(splitURI.get(2), httpRequest.getContentType()); request2 = RasUtil.abstractWCPSToRasql(queryDecoded, wcps); } } else if (request2 != null) { log.debug("Received Abstract Syntax Request via GET: \n\t\t{}", request2); request2 = RasUtil.abstractWCPStoXML(request2); } request = StringUtil.urldecode(params.get(WCPS_REQUEST_GET_PARAMETER), httpRequest.getContentType()); if (request == null && request2 != null) { request = request2; } // Empty request ? if (request == null && (requestBody == null || requestBody.length() == 0)) { if (paramMap.size() > 0) { throw new WCSException(ExceptionCode.NoApplicableCode, "Couldn't understand the recieved request, is the service attribute missing?"); } else { printUsage(httpResponse, request); return; } } // No parameters, just XML in the request body: if (request == null && requestBody != null && requestBody.length() > 0) { request = StringUtil.urldecode(requestBody, httpRequest.getContentType()); } log.debug("Petascope Request: \n------START REQUEST--------\n{}" + "\n------END REQUEST------\n", request); String root = XMLUtil.getRootElementName(request); log.debug("Root Element name: {}", root); if (root == null) { return; } if (root.equals(XMLSymbols.LABEL_ENVELOPE)) { handleWcs2Request(request, httpResponse, httpRequest); } else if (root.endsWith(XMLSymbols.LABEL_PROCESSCOVERAGE_REQUEST)) { /* ProcessCoverages is defined in the WCPS extension to WcsServer */ handleProcessCoverages(request, httpResponse); } else if (root.equals(RequestHandler.GET_CAPABILITIES)) { // extract the version that the client prefers Document doc = XMLUtil.buildDocument(null, request); String version = ""; List<Element> acceptVersions = XMLUtil.collectAll(doc.getRootElement(), XMLSymbols.LABEL_ACCEPT_VERSIONS); if (!acceptVersions.isEmpty()) { List<Element> versions = XMLUtil.collectAll(ListUtil.head(acceptVersions), XMLSymbols.LABEL_VERSION); for (Element v : versions) { String val = XMLUtil.getText(v); if (val != null && ConfigManager.WCS_VERSIONS.contains(val)) { version = val; break; } } } else { version = ConfigManager.WCS_DEFAULT_VERSION; // by default the latest supported by petascope } handleWcsRequest(version, root, request, httpResponse, httpRequest); } else if (root.equals(RequestHandler.DESCRIBE_COVERAGE) || root.equals(RequestHandler.GET_COVERAGE) || root.equals(RequestHandler.PROCESS_COVERAGE) || root.equals(RequestHandler.INSERT_COVERAGE) || root.equals(RequestHandler.DELETE_COVERAGE) || root.equals(RequestHandler.UPDATE_COVERAGE)) { Document doc = XMLUtil.buildDocument(null, request); String version = doc.getRootElement().getAttributeValue(KVPSymbols.KEY_VERSION); handleWcsRequest(version, root, request, httpResponse, httpRequest); } else { // error handleUnknownRequest(request, httpResponse); } } catch (WCSException e) { throw e; } catch (SecoreException e) { throw new WCSException(ExceptionCode.SecoreError, e); } catch (Exception e) { // Finally, cast all other exceptions into a WCSException log.error("Runtime error : {}", e.getMessage()); throw new WCSException(ExceptionCode.RuntimeError, "Runtime error while processing request: " + e.getMessage(), e); } } // And catch all WCSExceptions, to display to the client catch (WCSException e) { printError(httpResponse, request, e); } }