public String getStudyHost(String studyOid) throws Exception { String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid; String pManageUrl = CoreResources.getField("portalURL"); String pManageUrlFull = pManageUrl + "/app/rest/oc/authorizations?studyoid=" + studyOid + "&instanceurl=" + ocUrl; CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory(); requestFactory.setReadTimeout(PARTICIPATE_READ_TIMEOUT); RestTemplate rest = new RestTemplate(requestFactory); try { Authorization[] response = rest.getForObject(pManageUrlFull, Authorization[].class); if (response.length > 0 && response[0].getStudy() != null && response[0].getStudy().getHost() != null && !response[0].getStudy().getHost().equals("")) { URL url = new URL(pManageUrl); String port = ""; if (url.getPort() > 0) port = ":" + String.valueOf(url.getPort()); return url.getProtocol() + "://" + response[0].getStudy().getHost() + "." + url.getHost() + port + "/#/login"; } } catch (Exception e) { logger.error(e.getMessage()); logger.error(ExceptionUtils.getStackTrace(e)); } return ""; }
public String registerStudy(String studyOid, String hostName) { String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid; String pManageUrl = CoreResources.getField("portalURL") + "/app/rest/oc/authorizations?studyoid=" + studyOid + "&instanceurl=" + ocUrl; Authorization authRequest = new Authorization(); Study authStudy = new Study(); authStudy.setStudyOid(studyOid); authStudy.setInstanceUrl(ocUrl); authStudy.setHost(hostName); authRequest.setStudy(authStudy); CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory(); requestFactory.setReadTimeout(PARTICIPATE_READ_TIMEOUT); RestTemplate rest = new RestTemplate(requestFactory); try { Authorization response = rest.postForObject(pManageUrl, authRequest, Authorization.class); if (response != null && response.getAuthorizationStatus() != null) return response.getAuthorizationStatus().getStatus(); } catch (Exception e) { logger.error(e.getMessage()); logger.error(ExceptionUtils.getStackTrace(e)); } return ""; }
public ExtractBean generateExtractBean( DatasetBean dsetBean, StudyBean currentStudy, StudyBean parentStudy) { ExtractBean eb = new ExtractBean(ds); eb.setDataset(dsetBean); eb.setShowUniqueId(CoreResources.getField("show_unique_id")); eb.setStudy(currentStudy); eb.setParentStudy(parentStudy); eb.setDateCreated(new java.util.Date()); return eb; }
private String loadRegistrationStatus(String studyOid) { String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid; String pManageUrl = CoreResources.getField("portalURL") + "/app/rest/oc/authorizations?studyoid=" + studyOid + "&instanceurl=" + ocUrl; CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory(); requestFactory.setReadTimeout(PARTICIPATE_READ_TIMEOUT); RestTemplate rest = new RestTemplate(requestFactory); try { Authorization[] response = rest.getForObject(pManageUrl, Authorization[].class); if (response.length > 0 && response[0].getAuthorizationStatus() != null) return response[0].getAuthorizationStatus().getStatus(); } catch (Exception e) { logger.error(e.getMessage()); logger.debug(ExceptionUtils.getStackTrace(e)); } return ""; }
public String getHostNameAvailability(String hostName) { String pManageUrl = CoreResources.getField("portalURL") + "/app/permit/studys/name?hostName=" + hostName; CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory(); requestFactory.setReadTimeout(PARTICIPATE_READ_TIMEOUT); RestTemplate rest = new RestTemplate(requestFactory); String response = null; try { if (!validHostNameCheck(hostName)) return INVALID; response = rest.getForObject(pManageUrl, String.class); if (response.equals("UNAVAILABLE")) return UNAVAILABLE; else if (response.equals("INVALID")) return INVALID; else if (response.equals("AVAILABLE")) return AVAILABLE; } catch (Exception e) { logger.error(e.getMessage()); logger.error(ExceptionUtils.getStackTrace(e)); } return UNKNOWN; }
public boolean validHostNameCheck(String hostName) { String pManageBaseUrl = CoreResources.getField("portalURL"); if (hostName.contains(".")) return false; try { URL baseUrl = new URL(pManageBaseUrl); String port = ""; if (baseUrl.getPort() > 0) port = ":" + String.valueOf(baseUrl.getPort()); // Check that hostname makes a valid URL URL customerUrl = new URL(baseUrl.getProtocol() + "://" + hostName + "." + baseUrl.getHost() + port); // Check that hostname only contains alphanumeric characters and/or hyphens if (hostName.matches("^[A-Za-z0-9-]+$")) return true; } catch (MalformedURLException mue) { logger.error("Error validating customer selected Participate subdomain."); logger.error(mue.getMessage()); logger.error(ExceptionUtils.getStackTrace(mue)); } return false; }
public int createFile( String zipName, ArrayList names, String dir, ArrayList contents, DatasetBean datasetBean, long time, ExportFormatBean efb, boolean saveToDB) { ArchivedDatasetFileBean fbFinal = new ArchivedDatasetFileBean(); // >> tbh #4915 zipName = zipName.replaceAll(" ", "_"); fbFinal.setId(0); try { File complete = new File(dir); if (!complete.isDirectory()) { complete.mkdirs(); } int totalSize = 0; ZipOutputStream z = new ZipOutputStream(new FileOutputStream(new File(complete, zipName + ".zip"))); FileInputStream is = null; for (int i = 0; i < names.size(); i++) { String name = (String) names.get(i); // >> tbh #4915 name = name.replaceAll(" ", "_"); String content = (String) contents.get(i); File newFile = new File(complete, name); // totalSize = totalSize + (int)newFile.length(); newFile.setLastModified(System.currentTimeMillis()); BufferedWriter w = new BufferedWriter(new FileWriter(newFile)); w.write(content); w.close(); logger.info("finished writing the text file..."); // now, we write the file to the zip file is = new FileInputStream(newFile); logger.info("created zip output stream..."); z.putNextEntry(new java.util.zip.ZipEntry(name)); int bytesRead; byte[] buff = new byte[512]; while ((bytesRead = is.read(buff)) != -1) { z.write(buff, 0, bytesRead); totalSize += 512; } z.closeEntry(); // A. Hamid. 4910 is.close(); if (CoreResources.getField("dataset_file_delete").equalsIgnoreCase("true") || CoreResources.getField("dataset_file_delete").equals("")) { newFile.delete(); } } logger.info("writing buffer..."); // } z.flush(); z.finish(); z.close(); if (is != null) { try { is.close(); } catch (java.io.IOException ie) { ie.printStackTrace(); } } logger.info("finished zipping up file..."); // set up the zip to go into the database if (saveToDB) { ArchivedDatasetFileBean fb = new ArchivedDatasetFileBean(); fb.setName(zipName + ".zip"); fb.setFileReference(dir + zipName + ".zip"); // current location of the file on the system fb.setFileSize(totalSize); // set the above to compressed size? fb.setRunTime((int) time); // need to set this in milliseconds, get it passed from above // methods? fb.setDatasetId(datasetBean.getId()); fb.setExportFormatBean(efb); fb.setExportFormatId(efb.getId()); fb.setOwner(userBean); fb.setOwnerId(userBean.getId()); fb.setDateCreated(new Date(System.currentTimeMillis())); boolean write = true; ArchivedDatasetFileDAO asdfDAO = new ArchivedDatasetFileDAO(ds); if (write) { fbFinal = (ArchivedDatasetFileBean) asdfDAO.create(fb); logger.info("Created ADSFile!: " + fbFinal.getId() + " for " + zipName + ".zip"); } else { logger.info("duplicate found: " + fb.getName()); } } // created in database! } catch (Exception e) { logger.warn(e.getMessage()); System.out.println("-- exception at create file: " + e.getMessage()); e.printStackTrace(); } return fbFinal.getId(); }
/** * @api {post} /pages/api/v1/editform/:studyOid/submission Submit form data * @apiName doSubmission * @apiPermission admin * @apiVersion 1.0.0 * @apiParam {String} studyOid Study Oid. * @apiParam {String} ecid Key that will be used to look up subject context information while * processing submission. * @apiGroup Form * @apiDescription Submits the data from a completed form. */ @POST @Path("/{studyOID}/submission") @Produces(MediaType.APPLICATION_XML) public Response doSubmission( @Context HttpServletRequest request, @Context HttpServletResponse response, @Context ServletContext servletContext, @PathParam("studyOID") String studyOID, @QueryParam(FORM_CONTEXT) String context) { String output = null; Response.ResponseBuilder builder = Response.noContent(); String studySubjectOid = null; Integer studyEventDefnId = null; Integer studyEventOrdinal = null; String crfVersionOID = null; CRFVersionDAO crfvdao = new CRFVersionDAO(dataSource); try { if (ServletFileUpload.isMultipartContent(request)) { LOGGER.warn("WARNING: This prototype doesn't support multipart content."); } if (!mayProceedSubmission(studyOID)) builder.status(javax.ws.rs.core.Response.Status.NOT_ACCEPTABLE).build(); PFormCache cache = PFormCache.getInstance(servletContext); HashMap<String, String> userContext = cache.getSubjectContext(context); StudySubjectDAO ssdao = new StudySubjectDAO<String, ArrayList>(dataSource); StudySubjectBean ssBean = getSSBean(userContext); if (!mayProceedSubmission(studyOID, ssBean)) return null; studyEventDefnId = Integer.valueOf(userContext.get("studyEventDefinitionID")); studyEventOrdinal = Integer.valueOf(userContext.get("studyEventOrdinal")); crfVersionOID = userContext.get("crfVersionOID"); StringWriter writer = new StringWriter(); String body = IOUtils.toString(request.getInputStream(), "UTF-8"); CRFVersionBean crfVersion = crfvdao.findByOid(crfVersionOID); if (crfVersion.getXform() != null && !crfVersion.getXform().equals("")) { body = body.substring(body.indexOf("<" + crfVersion.getXformName())); int length = body.indexOf(" "); body = body.replace( body.substring(body.lastIndexOf("<meta>"), body.lastIndexOf("</meta>") + 7), ""); body = body.substring(0, body.lastIndexOf("</" + crfVersion.getXformName()) + length + 2); body = "<instance>" + body + "</instance>"; } else { body = body.substring(body.indexOf("<F_")); int length = body.indexOf(" "); body = body.replace(body.substring(body.indexOf("<meta>"), body.indexOf("</meta>") + 7), ""); body = body.substring(0, body.indexOf("</F_") + length + 2); body = "<instance>" + body + "</instance>"; } Errors errors = getPformSubmissionService() .saveProcess( body, ssBean.getOid(), studyEventDefnId, studyEventOrdinal, crfvdao.findByOid(crfVersionOID)); // Set response headers Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); Date currentDate = new Date(); cal.setTime(currentDate); SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss zz"); format.setCalendar(cal); builder.header("Date", format.format(currentDate)); builder.header("X-OpenRosa-Version", "1.0"); builder.type("text/xml; charset=utf-8"); if (!errors.hasErrors()) { builder.entity( "<OpenRosaResponse xmlns=\"http://openrosa.org/http/response\">" + "<message>success</message>" + "</OpenRosaResponse>"); LOGGER.debug("Successful OpenRosa submission"); } else { LOGGER.error("Failed OpenRosa submission"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.flushBuffer(); } } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.error(ExceptionUtils.getStackTrace(e)); return builder.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).build(); } try { // Notify Participate of successful form submission. String pManageUrl = CoreResources.getField("portalURL") + "/app/rest/oc/submission"; Submission submission = new Submission(); Study pManageStudy = new Study(); pManageStudy.setInstanceUrl( CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOID); pManageStudy.setStudyOid(studyOID); submission.setStudy(pManageStudy); submission.setStudy_event_def_id(studyEventDefnId); submission.setStudy_event_def_ordinal(studyEventOrdinal); submission.setCrf_version_id(crfvdao.findByOid(crfVersionOID).getId()); RestTemplate rest = new RestTemplate(); String result = rest.postForObject(pManageUrl, submission, String.class); LOGGER.debug("Notified Participate of CRF submission with a result of: " + result); } catch (Exception e) { LOGGER.error("Unable to notify Participate of successful CRF submission."); LOGGER.error(e.getMessage()); LOGGER.error(ExceptionUtils.getStackTrace(e)); } return builder.status(javax.ws.rs.core.Response.Status.CREATED).build(); }