List of usage examples for java.text SimpleDateFormat applyPattern
public void applyPattern(String pattern)
From source file:com.rr.wabshs.ui.surveys.surveyController.java
/** * The '/editSurvey' GET request will build out the survey and display the first page of the survey. * * @param i The encrypted survey id/*from ww w . j a v a 2s. c om*/ * @param v The encrypted decryption key * * @param session * @return * @throws Exception */ @RequestMapping(value = { "/editSurvey", "/viewSurvey" }, method = RequestMethod.GET) public ModelAndView editSurvey(@RequestParam String i, @RequestParam String v, HttpSession session, HttpServletRequest request, @RequestParam(value = "sessionId", required = false) Integer sessionId) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/takeSurvey"); mav.addObject("surveys", surveys); //Set the survey answer array to get ready to hold data if (session.getAttribute("questionAnswers") != null) { session.removeAttribute("questionAnswers"); } session.setAttribute("questionAnswers", new ArrayList<surveyQuestionAnswers>()); if (session.getAttribute("selectedProgramProfiles") != null) { session.removeAttribute("selectedProgramProfiles"); } session.setAttribute("selectedProgramProfiles", new ArrayList<surveyProgramProfiles>()); if (session.getAttribute("secondTierEntities") != null) { session.removeAttribute("secondTierEntities"); } session.setAttribute("secondTierEntities", new ArrayList<secondTierEntities>()); if (session.getAttribute("seenPages") != null) { session.removeAttribute("seenPages"); } session.setAttribute("seenPages", new ArrayList<Integer>()); if (session.getAttribute("selectedExtras") != null) { session.removeAttribute("selectedExtras"); } session.setAttribute("selectedExtras", new ArrayList<surveyExtraInformation>()); int clientId = 0; /* Decrypt the url */ decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(i, v); String[] result = obj.toString().split((",")); int submittedSurveyId = Integer.parseInt(result[0].substring(4)); /* Get the survey details */ submittedSurveys submittedSurveyDetails = surveyManager.getSubmittedSurvey(submittedSurveyId); surveys surveyDetails = surveyManager.getSurveyDetails(submittedSurveyDetails.getSurveyId()); mav.addObject("surveyTag", surveyDetails.getSurveyTag()); if (surveyDetails.isAssociateToProgram()) { mav.addObject("showPrograms", true); } else { mav.addObject("showPrograms", false); } User userDetails = (User) session.getAttribute("userDetails"); survey survey = new survey(); survey.setClientId(clientId); survey.setSurveyId(submittedSurveyDetails.getSurveyId()); survey.setSurveyTitle(surveyDetails.getTitle()); survey.setPrevButton(surveyDetails.getPrevButtonText()); survey.setNextButton(surveyDetails.getNextButtonText()); survey.setSaveButton(surveyDetails.getDoneButtonText()); survey.setSubmittedSurveyId(submittedSurveyId); survey.setEntityIds(surveyManager.getSubmittedSurveyEntities(submittedSurveyId, userDetails)); encryptObject encrypt = new encryptObject(); Map<String, String> map; //Encrypt the use id to pass in the url map = new HashMap<String, String>(); map.put("id", Integer.toString(submittedSurveyDetails.getSurveyId())); map.put("topSecret", topSecret); String[] encrypted = encrypt.encryptObject(map); survey.setEncryptedId(encrypted[0]); survey.setEncryptedSecret(encrypted[1]); mav.addObject("surveyURL", "?i=" + encrypted[0] + "&v=" + encrypted[1]); /* Get the pages */ List<SurveyPages> surveyPages = surveyManager.getSurveyPages(submittedSurveyDetails.getSurveyId(), false, 0, 0, 0, 0); SurveyPages currentPage = surveyManager.getSurveyPage(submittedSurveyDetails.getSurveyId(), true, 1, clientId, 0, 0, submittedSurveyId, 0, 0); survey.setPageTitle(currentPage.getPageTitle()); survey.setSurveyPageQuestions(currentPage.getSurveyQuestions()); survey.setTotalPages(surveyPages.size()); survey.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId()); survey.setPageId(currentPage.getId()); /* Need to update any date functions */ if (survey.getSurveyPageQuestions() != null && survey.getSurveyPageQuestions().size() > 0) { for (SurveyQuestions question : survey.getSurveyPageQuestions()) { if (question.getAnswerTypeId() == 6) { if (question.getQuestionValue().length() > 0 && !question.getQuestionValue().contains("^^^^^")) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat df2 = new SimpleDateFormat("M/dd/yy"); SimpleDateFormat df3 = new SimpleDateFormat("M/dd/yyyy"); SimpleDateFormat df4 = new SimpleDateFormat("M/d/yy"); SimpleDateFormat df5 = new SimpleDateFormat("M/d/yyyy"); SimpleDateFormat df6 = new SimpleDateFormat("MM/d/yyyy"); SimpleDateFormat df7 = new SimpleDateFormat("MM/d/yy"); SimpleDateFormat df8 = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat df9 = new SimpleDateFormat("MM/dd/yy"); Date formattedDate; try { formattedDate = df.parse(question.getQuestionValue()); } catch (Exception ex) { try { formattedDate = df2.parse(question.getQuestionValue()); } catch (Exception ex2) { try { formattedDate = df3.parse(question.getQuestionValue()); } catch (Exception ex3) { try { formattedDate = df4.parse(question.getQuestionValue()); } catch (Exception ex4) { try { formattedDate = df5.parse(question.getQuestionValue()); } catch (Exception ex5) { try { formattedDate = df6.parse(question.getQuestionValue()); } catch (Exception ex6) { try { formattedDate = df7.parse(question.getQuestionValue()); } catch (Exception ex7) { try { formattedDate = df8.parse(question.getQuestionValue()); } catch (Exception ex8) { formattedDate = df9.parse(question.getQuestionValue()); } } } } } } } } if (question.getDateFormatType() == 2) { //dd/mm/yyyy df.applyPattern("dd/MM/yyyy"); } else { //mm/dd/yyyy df.applyPattern("MM/dd/yyyy"); } String formattedDateasString = df.format(formattedDate); question.setQuestionValue(formattedDateasString); } } } } if (sessionId != null && sessionId > 0) { survey.setSessionId(sessionId); } mav.addObject("survey", survey); mav.addObject("surveyPages", surveyPages); List<Integer> selectedEntities = surveyManager.getSurveyEntities(submittedSurveyId); /* Get a list of available schools for the selected districts */ if (selectedEntities != null && !selectedEntities.isEmpty() && !"".equals(selectedEntities)) { List<secondTierEntities> tier2EntityList = (List<secondTierEntities>) session .getAttribute("secondTierEntities"); for (Integer entityId : selectedEntities) { List<thirdTierEntities> tier3EntityList = new ArrayList<thirdTierEntities>(); secondTierEntities secondTierEntity = new secondTierEntities(); secondTierEntity.setId(entityId); programHierarchyDetails secondTierEntityDetails = hierarchymanager .getProgramHierarchyItemDetails(entityId); secondTierEntity.setName(secondTierEntityDetails.getName()); Integer userId = 0; if (userDetails.getRoleId() == 3) { userId = userDetails.getId(); } List tier3Entities = hierarchymanager.getProgramOrgHierarchyItems(programId, 3, entityId, userId); if (!tier3Entities.isEmpty() && tier3Entities.size() > 0) { for (ListIterator iter = tier3Entities.listIterator(); iter.hasNext();) { Object[] row = (Object[]) iter.next(); thirdTierEntities thirdTierEntity = new thirdTierEntities(); thirdTierEntity.setId(Integer.parseInt(row[0].toString())); thirdTierEntity.setName(row[1].toString()); //Encrypt the use id to pass in the url map = new HashMap<String, String>(); map.put("id", Integer.toString(Integer.parseInt(row[0].toString()))); map.put("topSecret", topSecret); String[] encrypted2 = encrypt.encryptObject(map); thirdTierEntity.setEncryptedId(encrypted2[0]); thirdTierEntity.setEncryptedSecret(encrypted2[1]); tier3EntityList.add(thirdTierEntity); } secondTierEntity.setTier3EntityList(tier3EntityList); } tier2EntityList.add(secondTierEntity); } mav.addObject("seltier2EntityList", tier2EntityList); } mav.addObject("selSurvey", submittedSurveyDetails.getSurveyId()); mav.addObject("selectedEntities", selectedEntities.toString().replace("[", "").replace("]", "")); mav.addObject("qNum", 0); mav.addObject("currPageNum", 1); boolean disabled = false; if ("/surveys/viewSurvey".equals(request.getServletPath())) { disabled = true; } mav.addObject("disabled", disabled); return mav; }
From source file:org.sakaiproject.tool.podcasts.podHomeBean.java
/** * Receives a particular podcast and packages it as a DecoratedPodcastBean * //from w w w. ja v a 2 s.c o m * @param podcastProperties * Contains the ResourceProperties object of a podcast resource * @param resourceId * The resource ID for the podcast * * @return DecoratedPodcastBean * The packaged podcast or null and exception if problems * * @throws EntityPropertyNotDefinedException * The property wanted was not found * @throws EntityPropertyTypeException * The property (Date/Time) was not a valid one */ public DecoratedPodcastBean getAPodcast(ContentResource podcastResource, boolean folderHidden) throws EntityPropertyNotDefinedException, EntityPropertyTypeException { ResourceProperties podcastProperties = podcastResource.getProperties(); DecoratedPodcastBean podcastInfo = null; // first check if hidden. // if instructor or has hidden property, set hidden property of decorated bean // if not, return null since user cannot see Date tempDate = null; final SimpleDateFormat formatter = new SimpleDateFormat(getErrorMessageString(PUBLISH_DATE_FORMAT), rb.getLocale()); formatter.setTimeZone(TimeService.getLocalTimeZone()); // get release/publish date - else part needed for podcasts created before release/retract dates // feature implemented if (podcastResource.getReleaseDate() == null) { tempDate = podcastService .getGMTdate(podcastProperties.getTimeProperty(PodcastService.DISPLAY_DATE).getTime()); } else { tempDate = new Date(podcastResource.getReleaseDate().getTime()); } // store result of hidden property OR after retract date OR before release date final boolean uiHidden = folderHidden || hiddenInUI(podcastResource, tempDate); if (!uiHidden || getHasHidden()) { podcastInfo = new DecoratedPodcastBean(); podcastInfo.setDisplayDate(formatter.format(tempDate)); // store resourceId podcastInfo.setResourceId(podcastResource.getId()); // store Title and Description podcastInfo.setTitle(podcastProperties.getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME)); podcastInfo.setDescription(podcastProperties.getPropertyFormatted(ResourceProperties.PROP_DESCRIPTION)); podcastInfo.setHidden(uiHidden); // if podcast should be hidden, set style class to 'inactive' if (uiHidden) { podcastInfo.setStyleClass("inactive"); } String filename = null; try { String url = podcastService.getPodcastFileURL(podcastResource.getId()); filename = url.substring(url.lastIndexOf("/") + 1); } catch (PermissionException e) { LOG.warn("PermissionException getting podcast with id " + podcastResource.getId() + " while constructing DecoratedPodcastBean for site " + podcastService.getSiteId() + ". " + e.getMessage(), e); } catch (IdUnusedException e) { LOG.warn("IdUnusedException getting podcast with id " + podcastResource.getId() + " while constructing DecoratedPodcastBean for site " + podcastService.getSiteId() + ". " + e.getMessage(), e); } // if user puts URL instead of file, this is result of retrieving filename if (filename == null) return null; podcastInfo.setFilename(filename); // get content type podcastInfo.setFileContentType(podcastProperties.getProperty(ResourceProperties.PROP_CONTENT_TYPE)); // store actual and formatted file size // determine whether to display filesize as bytes or MB final long size = Long.parseLong(podcastProperties.getProperty(ResourceProperties.PROP_CONTENT_LENGTH)); podcastInfo.setFileSize(size); final double sizeMB = size / (1024.0 * 1024.0); final DecimalFormat df = new DecimalFormat(MB_NUMBER_FORMAT); String sizeString; if (sizeMB > 0.3) { sizeString = df.format(sizeMB) + MB; } else { df.applyPattern(BYTE_NUMBER_FORMAT); sizeString = "" + df.format(size) + " " + BYTES; } podcastInfo.setSize(sizeString); final String extn = Validator.getFileExtension(filename); if (!"".equals(extn)) { podcastInfo.setType(Validator.getFileExtension(filename).toUpperCase()); } else { podcastInfo.setType("UNK"); } // get and format last modified time formatter.applyPattern(LAST_MODIFIED_TIME_FORMAT); tempDate = new Date(podcastProperties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE).getTime()); podcastInfo.setPostedTime(formatter.format(tempDate)); // get and format last modified date formatter.applyPattern(LAST_MODIFIED_DATE_FORMAT); tempDate = new Date(podcastProperties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE).getTime()); podcastInfo.setPostedDate(formatter.format(tempDate)); // get author podcastInfo.setAuthor(podcastProperties.getPropertyFormatted(ResourceProperties.PROP_CREATOR)); } return podcastInfo; }
From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.DocumentFactory.java
/** * Constructs a CDA Consent for the given user. * //from www . java 2 s. c o m * @param user * @param policySet * - null if either the participation should end or if a new * PolicySet should be created. * @param author * @param participation * - true if the user wants to participate, else false * @param out * - The OutputStream on which the generated PDF presentation * will be written * @return - The generated CDA file. * */ public Document constructCDA(User user, Document policySet, User author, boolean participation, OutputStream out) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document domCDA = null; Document domAssignedAuthor = null; Document domScanningDevice = null; Document domDataEnterer = null; Document domCustodian = null; Document domLegalAuthenticator = null; String cdaAsString = ""; DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); domCDA = db.parse(urlCdaSkeleton); domAssignedAuthor = db.parse(urlAssignedAuthor); domScanningDevice = db.parse(urlScanningDevice); domDataEnterer = db.parse(urlDataEnterer); domCustodian = db.parse(urlCustodian); domLegalAuthenticator = db.parse(urlLegalAuthenticator); } catch (Exception e) { Logger.getLogger(this.getClass()).error(e); } Date d = new Date(); String uniqueID = RandomStringUtils.randomNumeric(64); domCDA.getElementsByTagName("id").item(0).getAttributes().item(0).setNodeValue(uniqueID); domCDA.getElementsByTagName("id").item(0).getAttributes().item(1) .setNodeValue("1.2.276.0.76.3.1.78.1.0.10.40"); SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssZ"); domCDA.getElementsByTagName("effectiveTime").item(0).getAttributes().item(0).setTextContent(sd.format(d)); Node title = domCDA.getElementsByTagName("title").item(0); if (participation) { title.setTextContent("Dies ist die Einwilligungserklrung fr die Teilnahme an ISIS von " + user.getForename() + " " + user.getName()); } else { title.setTextContent("Dieses Dokument erklrt den Verzicht von " + user.getForename() + " " + user.getName() + " auf die Teilnahme an ISIS."); } Node pR = domCDA.getElementsByTagName("patientRole").item(0); NodeList prChildren = pR.getChildNodes(); Node id = prChildren.item(1); // extension id.getAttributes().item(0).setNodeValue(user.getID()); // PID // root id.getAttributes().item(1).setNodeValue("1.2.276.0.76.3.1.78.1.0.10.20"); // Assigning // Authority NodeList addr = prChildren.item(3).getChildNodes(); addr.item(1).setTextContent(user.getStreet()); addr.item(3).setTextContent(user.getCity()); addr.item(5).setTextContent("");//Hier knnte das Bundesland // stehen! addr.item(7).setTextContent(String.valueOf(user.getZipcode())); addr.item(9).setTextContent("Deutschland");// Es sollte nicht // standardmig Deutschland // gesetzt werden! NodeList pat = prChildren.item(5).getChildNodes(); NodeList name = pat.item(1).getChildNodes(); if (user.getGender().equalsIgnoreCase("male")) { name.item(1).setTextContent("Herr"); pat.item(3).getAttributes().item(0).setTextContent("M"); } else { name.item(1).setTextContent("Frau"); pat.item(3).getAttributes().item(0).setTextContent("F"); } name.item(3).setTextContent(user.getForename()); name.item(5).setTextContent(user.getName()); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); pat.item(5).getAttributes().item(0).setTextContent(formatter.format(user.getBirthdate())); if (policySet == null) { policySet = getSkeletonPolicySet(participation, user); } Document doc = db.newDocument(); Element root = doc.createElement("component"); doc.appendChild(root); Node copy = doc.importNode(policySet.getDocumentElement(), true); root.appendChild(copy); NodeList list = domCDA.getElementsByTagName("structuredBody"); Node f = domCDA.importNode(doc.getDocumentElement(), true); list.item(0).appendChild(f); Node docuOfNode = domCDA.getElementsByTagName("documentationOf").item(0); if (author == user) { domAssignedAuthor.getElementsByTagName("time").item(0).getAttributes().item(0) .setNodeValue(sd.format(d)); domAssignedAuthor.getElementsByTagName("id").item(0).getAttributes().item(0) .setNodeValue(author.getID()); // ID domAssignedAuthor.getElementsByTagName("id").item(0).getAttributes().item(1) .setNodeValue("1.2.276.0.76.3.1.78.1.0.10.20");// MPI-assigning // authority if (user.getGender().equalsIgnoreCase("male")) { domAssignedAuthor.getElementsByTagName("prefix").item(0).setTextContent("Herr"); } else { name.item(1).setTextContent("Frau"); domAssignedAuthor.getElementsByTagName("prefix").item(0).setTextContent("Frau"); } // suffix Wert setzen // domAssignedAuthor.getElementsByTagName("suffix").item(0).getAttributes().item(0).setNodeValue(""); domAssignedAuthor.getElementsByTagName("given").item(0).setTextContent(author.getForename()); domAssignedAuthor.getElementsByTagName("family").item(0).setTextContent(author.getName()); // TODO Werte setzen assignedPerson oder Werte loeschen } else if (author != user && author != null) { // Zukunft: Erzeugung durch Dritte } else { // Std values from AssignedAuthor.xml } Node copyAssignedAuthorNode = domCDA.importNode(domAssignedAuthor.getDocumentElement(), true); Node copyScanningDeviceNode = domCDA.importNode(domScanningDevice.getDocumentElement(), true); Node copyDataEntererNode = domCDA.importNode(domDataEnterer.getDocumentElement(), true); Node copyCustodianNode = domCDA.importNode(domCustodian.getDocumentElement(), true); Node copyLegalAuthenticator = domCDA.importNode(domLegalAuthenticator.getDocumentElement(), true); sd.applyPattern("yyyyMMdd"); domCDA.getElementsByTagName("low").item(0).getAttributes().item(0).setNodeValue(sd.format(d)); Date d2 = new Date((long) (d.getTime() + 30 * 3.1556926 * Math.pow(10, 10))); domCDA.getElementsByTagName("high").item(0).getAttributes().item(0).setNodeValue(sd.format(d2)); copyAssignedAuthorNode.getChildNodes().item(3).getAttributes().item(0).setNodeValue(sd.format(d)); Node clinicalDocumentNode = domCDA.getElementsByTagName("ClinicalDocument").item(0); clinicalDocumentNode.insertBefore(copyAssignedAuthorNode, docuOfNode); clinicalDocumentNode.insertBefore(copyScanningDeviceNode, docuOfNode); clinicalDocumentNode.insertBefore(copyDataEntererNode, docuOfNode); clinicalDocumentNode.insertBefore(copyCustodianNode, docuOfNode); clinicalDocumentNode.insertBefore(copyLegalAuthenticator, docuOfNode); Document noNSCDA = (Document) domCDA.cloneNode(true); NodeList l = noNSCDA.getElementsByTagName("ClinicalDocument"); NamedNodeMap attributes = l.item(0).getAttributes(); attributes.removeNamedItem("xmlns"); attributes.removeNamedItem("xmlns:voc"); attributes.removeNamedItem("xmlns:xsi"); attributes.removeNamedItem("xsi:schemaLocation"); l = noNSCDA.getElementsByTagName("PolicySet"); attributes = l.item(0).getAttributes(); attributes.removeNamedItem("xmlns"); attributes.removeNamedItem("PolicyCombiningAlgId"); attributes.removeNamedItem("xmlns:xsi"); attributes.removeNamedItem("xsi:schemaLocation"); attributes.removeNamedItem("PolicySetId"); formatter = new SimpleDateFormat("dd.MM.yyyy"); noNSCDA.getElementsByTagName("birthTime").item(0).getAttributes().item(0) .setTextContent(formatter.format(user.getBirthdate())); cdaAsString = getStringFromDocument(noNSCDA); Document nonXMLBody = constructPDF(cdaAsString, out); Node copyNode = domCDA.importNode(nonXMLBody.getDocumentElement(), true); Node component = domCDA.getElementsByTagName("component").item(0); Node structBody = component.getChildNodes().item(1); component.insertBefore(copyNode, structBody); NamedNodeMap nlm = domCDA.getDocumentElement().getElementsByTagName("PolicySet").item(0).getAttributes(); // nlm.removeNamedItem("xmlns:xsi"); // nlm.removeNamedItem("xsi:schemaLocation"); return domCDA; }
From source file:org.sakaiproject.assignment.tool.AssignmentAction.java
public boolean createTIIAssignment(AssignmentContentEdit assign, String assignmentRef, Time openTime, Time dueTime, Time closeTime, SessionState state) { Map opts = new HashMap(); opts.put("submit_papers_to", assign.getSubmitReviewRepo()); opts.put("report_gen_speed", assign.getGenerateOriginalityReport()); opts.put("institution_check", assign.isCheckInstitution() ? "1" : "0"); opts.put("internet_check", assign.isCheckInternet() ? "1" : "0"); opts.put("journal_check", assign.isCheckPublications() ? "1" : "0"); opts.put("s_paper_check", assign.isCheckTurnitin() ? "1" : "0"); opts.put("s_view_report", assign.getAllowStudentViewReport() ? "1" : "0"); if (ServerConfigurationService.getBoolean("turnitin.option.exclude_bibliographic", true)) { //we don't want to pass parameters if the user didn't get an option to set it opts.put("exclude_biblio", assign.isExcludeBibliographic() ? "1" : "0"); }//from w w w . j av a 2s .c o m if (ServerConfigurationService.getBoolean("turnitin.option.exclude_quoted", true)) { //we don't want to pass parameters if the user didn't get an option to set it opts.put("exclude_quoted", assign.isExcludeQuoted() ? "1" : "0"); } if ((assign.getExcludeType() == 1 || assign.getExcludeType() == 2) && assign.getExcludeValue() >= 0 && assign.getExcludeValue() <= 100) { opts.put("exclude_type", Integer.toString(assign.getExcludeType())); opts.put("exclude_value", Integer.toString(assign.getExcludeValue())); } opts.put("late_accept_flag", "1"); SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); dform.applyPattern("yyyy-MM-dd HH:mm:ss"); opts.put("dtstart", dform.format(openTime.getTime())); opts.put("dtdue", dform.format(dueTime.getTime())); //opts.put("dtpost", dform.format(closeTime.getTime())); opts.put("title", assign.getTitle()); opts.put("instructions", assign.getInstructions()); if (assign.getAttachments() != null && assign.getAttachments().size() > 0) { List<String> attachments = new ArrayList<String>(); for (Reference ref : assign.getAttachments()) { attachments.add(ref.getReference()); } opts.put("attachments", attachments); } try { contentReviewService.createAssignment(assign.getContext(), assignmentRef, opts); return true; } catch (Exception e) { M_log.error(e); String uiService = ServerConfigurationService.getString("ui.service", "Sakai"); String[] args = new String[] { contentReviewService.getServiceName(), uiService, e.toString() }; state.setAttribute("alertMessage", rb.getFormattedMessage("content_review.error.createAssignment", args)); } return false; }
From source file:org.sakaiproject.assignment.tool.AssignmentAction.java
/** * Takes the inline submission, prepares it as an attachment to the submission and queues the attachment with the content review service *///from www.j a v a 2 s . com private void prepareInlineForContentReview(String text, AssignmentSubmissionEdit edit, SessionState state, User student) { //We will be replacing the inline submission's attachment //firstly, disconnect any existing attachments with AssignmentSubmission.PROP_INLINE_SUBMISSION set List attachments = edit.getSubmittedAttachments(); List toRemove = new ArrayList(); Iterator itAttachments = attachments.iterator(); while (itAttachments.hasNext()) { Reference attachment = (Reference) itAttachments.next(); ResourceProperties attachProps = attachment.getProperties(); if ("true".equals(attachProps.getProperty(AssignmentSubmission.PROP_INLINE_SUBMISSION))) { toRemove.add(attachment); } } Iterator itToRemove = toRemove.iterator(); while (itToRemove.hasNext()) { Reference attachment = (Reference) itToRemove.next(); edit.removeSubmittedAttachment(attachment); } //now prepare the new resource //provide lots of info for forensics - filename=InlineSub_assignmentId_userDisplayId_(for_studentDisplayId)_date.html User currentUser = UserDirectoryService.getCurrentUser(); String currentDisplayName = currentUser.getDisplayId(); String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING); SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); //avoid semicolons in filenames, right? dform.applyPattern("yyyy-MM-dd_HH-mm-ss"); StringBuilder sb_resourceId = new StringBuilder("InlineSub_"); String u = "_"; sb_resourceId.append(edit.getAssignmentId()).append(u).append(currentDisplayName).append(u); boolean isOnBehalfOfStudent = student != null && !student.equals(currentUser); if (isOnBehalfOfStudent) { // We're submitting on behalf of somebody sb_resourceId.append("for_").append(student.getDisplayId()).append(u); } sb_resourceId.append(dform.format(new Date())); String fileExtension = ".html"; /* * TODO: add and use a method in ContentHostingService to get the length of the ID of an attachment collection * Attachment collections currently look like this: * /attachment/dc126c4a-a48f-42a6-bda0-cf7b9c4c5c16/Assignments/eac7212a-9597-4b7d-b958-89e1c47cdfa7/ * See BaseContentService.addAttachmentResource for more information */ String toolName = "Assignments"; // TODO: add and use a method in IdManager to get the maxUuidLength int maxUuidLength = 36; int esl = Entity.SEPARATOR.length(); int attachmentCollectionLength = ContentHostingService.ATTACHMENTS_COLLECTION.length() + siteId.length() + esl + toolName.length() + esl + maxUuidLength + esl; int maxChars = ContentHostingService.MAXIMUM_RESOURCE_ID_LENGTH - attachmentCollectionLength - fileExtension.length() - 1; String resourceId = StringUtils.substring(sb_resourceId.toString(), 0, maxChars) + fileExtension; ResourcePropertiesEdit inlineProps = m_contentHostingService.newResourceProperties(); inlineProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, rb.getString("submission.inline")); inlineProps.addProperty(ResourceProperties.PROP_DESCRIPTION, resourceId); inlineProps.addProperty(AssignmentSubmission.PROP_INLINE_SUBMISSION, "true"); //create a byte array input stream //text is almost in html format, but it's missing the start and ending tags //(Is this always the case? Does the content review service care?) String toHtml = "<html><head></head><body>" + text + "</body></html>"; InputStream contentStream = new ByteArrayInputStream(toHtml.getBytes()); String contentType = "text/html"; //duplicating code from doAttachUpload. TODO: Consider refactoring into a method SecurityAdvisor sa = new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { if (function.equals(m_contentHostingService.AUTH_RESOURCE_ADD)) { return SecurityAdvice.ALLOWED; } else if (function.equals(m_contentHostingService.AUTH_RESOURCE_WRITE_ANY)) { return SecurityAdvice.ALLOWED; } else { return SecurityAdvice.PASS; } } }; try { m_securityService.pushAdvisor(sa); ContentResource attachment = m_contentHostingService.addAttachmentResource(resourceId, siteId, toolName, contentType, contentStream, inlineProps); // TODO: need to put this file in some kind of list to improve performance with web service impls of content-review service String contentUserId = isOnBehalfOfStudent ? student.getId() : currentUser.getId(); contentReviewService.queueContent(contentUserId, siteId, edit.getAssignment().getReference(), Arrays.asList(attachment)); try { Reference ref = EntityManager .newReference(m_contentHostingService.getReference(attachment.getId())); edit.addSubmittedAttachment(ref); } catch (Exception e) { M_log.warn(this + "prepareInlineForContentReview() cannot find reference for " + attachment.getId() + e.getMessage()); } } catch (PermissionException e) { addAlert(state, rb.getString("notpermis4")); } catch (RuntimeException e) { if (m_contentHostingService.ID_LENGTH_EXCEPTION.equals(e.getMessage())) { addAlert(state, rb.getFormattedMessage("alert.toolong", new String[] { resourceId })); } } catch (ServerOverloadException e) { M_log.debug(this + ".prepareInlineForContentReview() ***** DISK IO Exception ***** " + e.getMessage()); addAlert(state, rb.getString("failed.diskio")); } catch (Exception ignore) { M_log.debug( this + ".prepareInlineForContentReview() ***** Unknown Exception ***** " + ignore.getMessage()); addAlert(state, rb.getString("failed")); } finally { m_securityService.popAdvisor(sa); } }
From source file:com.clark.func.Functions.java
/** * <p>//from w w w. j ava 2 s . c o m * Parses a string representing a date by trying a variety of different * parsers. * </p> * * <p> * The parse will try each parse pattern in turn. A parse is only deemed * successful if it parses the whole of the input string. If no parse * patterns match, a ParseException is thrown. * </p> * * @param str * the date to parse, not null * @param parsePatterns * the date format patterns to use, see SimpleDateFormat, not * null * @param lenient * Specify whether or not date/time parsing is to be lenient. * @return the parsed date * @throws IllegalArgumentException * if the date string or pattern array is null * @throws ParseException * if none of the date patterns were suitable * @see java.util.Calender#isLenient() */ private static Date parseDateWithLeniency(String str, String[] parsePatterns, boolean lenient) throws ParseException { if (str == null || parsePatterns == null) { throw new IllegalArgumentException("Date and Patterns must not be null"); } SimpleDateFormat parser = new SimpleDateFormat(); parser.setLenient(lenient); ParsePosition pos = new ParsePosition(0); for (int i = 0; i < parsePatterns.length; i++) { String pattern = parsePatterns[i]; // LANG-530 - need to make sure 'ZZ' output doesn't get passed to // SimpleDateFormat if (parsePatterns[i].endsWith("ZZ")) { pattern = pattern.substring(0, pattern.length() - 1); } parser.applyPattern(pattern); pos.setIndex(0); String str2 = str; // LANG-530 - need to make sure 'ZZ' output doesn't hit // SimpleDateFormat as it will ParseException if (parsePatterns[i].endsWith("ZZ")) { str2 = str.replaceAll("([-+][0-9][0-9]):([0-9][0-9])$", "$1$2"); } Date date = parser.parse(str2, pos); if (date != null && pos.getIndex() == str2.length()) { return date; } } throw new ParseException("Unable to parse the date: " + str, -1); }