public void testSAK_18269() { // http://jira.sakaiproject.org/browse/SAK-18269 String strFromBrowser = null; String result = null; StringBuilder errorMessages = null; String SVG_GOOD = "<div>hello</div><embed allowscriptaccess=\"always\" type=\"image/svg+xml\" src=\"data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAwIiBpZD0ieHNzIj5pbWFnZTwvc3ZnPg==\"></embed>"; String SVG_BAD = "<div>hello</div><embed allowscriptaccess=\"always\" type=\"image/svg+xml\" src=\"data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==\"></embed>"; strFromBrowser = SVG_GOOD; errorMessages = new StringBuilder(); result = FormattedText.processFormattedText(strFromBrowser, errorMessages, true); assertNotNull(result); assertTrue(errorMessages.length() == 0); assertTrue(result.contains("<div")); assertTrue(result.contains("<embed")); assertTrue(result.contains("src=")); assertTrue(result.contains("data:image/svg+xml;base64")); assertFalse(result.contains("<script")); strFromBrowser = SVG_BAD; errorMessages = new StringBuilder(); result = FormattedText.processFormattedText(strFromBrowser, errorMessages, true); assertNotNull(result); assertTrue(errorMessages.length() > 10); assertTrue(result.contains("<div")); assertTrue(result.contains("<embed")); assertFalse(result.contains("src=")); assertFalse(result.contains("data:image/svg+xml;base64")); assertFalse(result.contains("<script")); }
/** * Limit the formatted to a certain number of DISPLAYED characters, adding "..." if it was * truncated. For example, <xmp>trim("Hello \n<b>World</b>!", 7)</xmp> returns <xmp>"Hello * \n<b>W</b>..."</xmp> * * @param value The formatted text to limit. * @param the length to limit to (as an int). * @return The limited string. */ public static String limitFormattedText(String value, int length) { StringBuilder ret = new StringBuilder(); value = FormattedText.escapeHtmlFormattedTextSupressNewlines(value); boolean didTrim = FormattedText.trimFormattedText(value, length, ret); if (didTrim) ret.append("..."); return ret.toString(); }
public void testLegacyProcessFormattedText() { // TESTs using the legacy Sakai library String strFromBrowser = null; String result = null; StringBuilder errorMessages = null; strFromBrowser = TEST1; errorMessages = new StringBuilder(); result = FormattedText.processFormattedText(strFromBrowser, errorMessages, true); assertNotNull(result); // NOTE: FT adds a bunch of spaces so it is hard to predict the output assertTrue(result.contains("href=\"blah.html\"")); assertFalse(result.contains("style=\"font-weight:bold;\"")); // strips this out assertTrue(result.contains("target=\"_blank\"")); // adds target in assertTrue(result.contains("<div>hello there</div>")); assertEquals( "<a href=\"blah.html\" target=\"_blank\" >blah</a><div>hello there</div>", result); strFromBrowser = TEST2; errorMessages = new StringBuilder(); result = FormattedText.processFormattedText(strFromBrowser, errorMessages, true); assertNotNull(result); assertEquals( "<span>this is my span</span><script>alert('oh noes, a XSS attack!');</script><div>hello there from a div</div>", result); }
// DISABLED TEST public void donottestAntisamyProcessFormattedText() { // TESTS using the antiSamy library String strFromBrowser = null; String result = null; StringBuilder errorMessages = null; strFromBrowser = TEST1; errorMessages = new StringBuilder(); result = FormattedText.processFormattedText(strFromBrowser, errorMessages, false); assertNotNull(result); assertTrue(result.contains("href=\"blah.html\"")); // assertFalse( result.contains("style=\"font-weight:bold;\"")); // strips this out // assertTrue( result.contains("target=\"_blank\"")); // adds target in assertTrue(result.contains("<div>hello there</div>")); assertEquals( "<a href=\"blah.html\" style=\"font-weight: bold;\">blah</a>\n<div>hello there</div>", result); strFromBrowser = TEST2; errorMessages = new StringBuilder(); result = FormattedText.processFormattedText(strFromBrowser, errorMessages, false); assertNotNull(result); assertEquals("<span>this is my span</span>\n<div>hello there from a div</div>", result); String SVG_BAD = "<div>hello</div><embed allowscriptaccess=\"always\" type=\"image/svg+xml\" src=\"data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==\"></embed>"; strFromBrowser = SVG_BAD; errorMessages = new StringBuilder(); result = FormattedText.processFormattedText(strFromBrowser, errorMessages, false); assertNotNull(result); assertEquals("", result); }
@Override protected String plainTextContent(Event event) { StringBuilder buf = new StringBuilder(); String newline = "\n\r"; // get the message Reference ref = entityManager.newReference(event.getResource()); AnnouncementMessage msg = (AnnouncementMessage) ref.getEntity(); AnnouncementMessageHeader hdr = (AnnouncementMessageHeader) msg.getAnnouncementHeader(); // use either the configured site, or if not configured, the site (context) of the resource String siteId = (getSite() != null) ? getSite() : ref.getContext(); String url = ServerConfigurationService.getPortalUrl() + "/site/" + siteId; // get a site title String title = siteId; try { Site site = siteService.getSite(siteId); title = site.getTitle(); } catch (Exception ignore) { } // Now build up the message text. if (AnnouncementService.SECURE_ANNC_ADD.equals(event.getEvent())) { buf.append( FormattedText.convertFormattedTextToPlaintext( rb.getFormattedMessage("noti.header.add", new Object[] {title, url}))); } else { buf.append( FormattedText.convertFormattedTextToPlaintext( rb.getFormattedMessage("noti.header.update", new Object[] {title, url}))); } buf.append(" " + rb.getString("at_date") + " "); buf.append(hdr.getDate().toStringLocalFull()); buf.append(newline); buf.append(FormattedText.convertFormattedTextToPlaintext(msg.getBody())); buf.append(newline); // add any attachments List attachments = hdr.getAttachments(); if (attachments.size() > 0) { buf.append(newline + rb.getString("Attachments") + newline); for (Iterator iAttachments = attachments.iterator(); iAttachments.hasNext(); ) { Reference attachment = (Reference) iAttachments.next(); String attachmentTitle = attachment.getProperties().getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME); buf.append(attachmentTitle + ": " + attachment.getUrl() + newline); } } return buf.toString(); }
/** * This will populate the StudentScoresBean with the data associated with the particular versioned * assessment based on the publishedId. * * @param publishedId String * @param bean StudentScoresBean * @return boolean */ public boolean studentScores(String publishedId, StudentScoresBean bean, boolean isValueChange) { log.debug("studentScores()"); try { // SAK-4121, do not pass studentName as f:param, will cause javascript error if name contains // apostrophe // bean.setStudentName(cu.lookupParam("studentName")); bean.setPublishedId(publishedId); String studentId = ContextUtil.lookupParam("studentid"); bean.setStudentId(studentId); AgentFacade agent = new AgentFacade(studentId); bean.setStudentName(agent.getFirstName() + " " + agent.getLastName()); bean.setLastName(agent.getLastName()); bean.setFirstName(agent.getFirstName()); bean.setAssessmentGradingId(ContextUtil.lookupParam("gradingData")); bean.setItemId(ContextUtil.lookupParam("itemId")); bean.setEmail(agent.getEmail()); DeliveryBean dbean = (DeliveryBean) ContextUtil.lookupBean("delivery"); dbean.setActionString("gradeAssessment"); DeliveryActionListener listener = new DeliveryActionListener(); listener.processAction(null); // Added for SAK-13930 DeliveryBean updatedDeliveryBean = (DeliveryBean) ContextUtil.lookupBean("delivery"); ArrayList parts = updatedDeliveryBean.getPageContents().getPartsContents(); Iterator iter = parts.iterator(); while (iter.hasNext()) { ArrayList items = ((SectionContentsBean) iter.next()).getItemContents(); Iterator iter2 = items.iterator(); while (iter2.hasNext()) { ItemContentsBean question = (ItemContentsBean) iter2.next(); if (question.getGradingComment() != null && !question.getGradingComment().equals("")) { question.setGradingComment( FormattedText.convertFormattedTextToPlaintext(question.getGradingComment())); } } } // End of SAK-13930 GradingService service = new GradingService(); AssessmentGradingData adata = (AssessmentGradingData) service.load(bean.getAssessmentGradingId(), false); bean.setComments(FormattedText.convertFormattedTextToPlaintext(adata.getComments())); buildItemContentsMap(dbean); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
/** * Derived property. * * @return ArrayList of model SelectItems */ public ArrayList getPoolSelectList() { poolListSelectItems = new ArrayList(); QuestionPoolService delegate = new QuestionPoolService(); ArrayList<QuestionPoolFacade> qplist = delegate.getBasicInfoOfAllPools(AgentFacade.getAgentString()); Iterator<QuestionPoolFacade> iter = qplist.iterator(); try { while (iter.hasNext()) { QuestionPoolFacade pool = (QuestionPoolFacade) iter.next(); // SAM-2269 - if the parent pool ID is greater than 0 (question pool IDs start at 1), get // the parent pool Long parentPoolID = pool.getParentPoolId(); QuestionPoolFacade parent = null; if (parentPoolID > 0) { for (QuestionPoolFacade qp : qplist) { if (parentPoolID.equals(qp.getQuestionPoolId())) { parent = qp; break; } } } // SAM-2269 - add the appropriate string to the list String original = pool.getDisplayName() + " (" + delegate.getCountItems(pool.getQuestionPoolId()) + ")"; if (parent != null) { poolListSelectItems.add( new SelectItem( pool.getQuestionPoolId().toString(), FormattedText.convertFormattedTextToPlaintext( parent.getDisplayName() + ": " + original))); } else { poolListSelectItems.add( new SelectItem( pool.getQuestionPoolId().toString(), FormattedText.convertFormattedTextToPlaintext(original))); } } } catch (Exception e) { throw new RuntimeException(e); } Collections.sort(poolListSelectItems, new ItemComparator()); return poolListSelectItems; }
public void testKNL_579() { // http://jira.sakaiproject.org/browse/KNL-579 String SCRIPT1 = "<div>testing</div><SCRIPT>alert(\"XSS\");//</SCRIPT>"; String SCRIPT2 = "<div>testing</div><SCRIPT>alert(\"XSS\");//<</SCRIPT>"; String SCRIPT3 = "<div>testing</div><<SCRIPT>alert(\"XSS\");//<</SCRIPT>"; String SCRIPT4 = "<div>testing</div><<SCRIPT>>alert(\"XSS\");//<</SCRIPT>"; String strFromBrowser = null; String result = null; StringBuilder errorMessages = null; strFromBrowser = SCRIPT1; errorMessages = new StringBuilder(); result = FormattedText.processFormattedText(strFromBrowser, errorMessages, true); assertNotNull(result); assertTrue(errorMessages.length() > 10); assertTrue(result.contains("<div>testing</div>")); assertTrue(result.contains("XSS")); assertFalse(result.contains("<SCRIPT")); strFromBrowser = SCRIPT2; errorMessages = new StringBuilder(); result = FormattedText.processFormattedText(strFromBrowser, errorMessages, true); assertNotNull(result); assertTrue(errorMessages.length() > 10); assertTrue(result.contains("<div>testing</div>")); assertTrue(result.contains("XSS")); assertFalse(result.contains("<SCRIPT")); strFromBrowser = SCRIPT3; errorMessages = new StringBuilder(); result = FormattedText.processFormattedText(strFromBrowser, errorMessages, true); assertNotNull(result); assertTrue(errorMessages.length() > 10); assertTrue(result.contains("<div>testing</div>")); assertTrue(result.contains("XSS")); assertFalse(result.contains("<SCRIPT")); strFromBrowser = SCRIPT4; errorMessages = new StringBuilder(); result = FormattedText.processFormattedText(strFromBrowser, errorMessages, true); assertNotNull(result); assertTrue(errorMessages.length() > 10); assertTrue(result.contains("<div>testing</div>")); assertTrue(result.contains("XSS")); assertFalse(result.contains("<SCRIPT")); }
private void sendAlert(RenderRequest request, Context context) { PortletSession pSession = request.getPortletSession(true); String str = (String) pSession.getAttribute(ALERT_MESSAGE); pSession.removeAttribute(ALERT_MESSAGE); if (str != null && str.length() > 0) context.put("alertMessage", validator.escapeHtml(str, false)); }
public void testUnbalancedMarkup() { StringBuilder errorMessages = new StringBuilder(); String strFromBrowser = "A<B Test"; String result = FormattedText.processFormattedText(strFromBrowser, errorMessages, true); assertNull(result); }
public void decode(FacesContext context, UIComponent component) { if (null == context || null == component || !(component instanceof org.sakaiproject.jsf.component.RichTextEditArea)) { throw new IllegalArgumentException(); } String clientId = component.getClientId(context); Map requestParameterMap = context.getExternalContext().getRequestParameterMap(); String newValue = (String) requestParameterMap.get(clientId + "_textinput"); String current_status = (String) requestParameterMap.get(clientId + "_textinput_current_status"); String finalValue = newValue; // if use hid the FCK editor, we treat it as text editor if ("firsttime".equals(current_status)) { finalValue = TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, newValue); } else { StringBuilder alertMsg = new StringBuilder(); try { finalValue = FormattedText.processFormattedText(newValue, alertMsg); if (alertMsg.length() > 0) { log.debug(alertMsg.toString()); } } catch (Exception e) { log.info(e.getMessage()); } } org.sakaiproject.jsf.component.RichTextEditArea comp = (org.sakaiproject.jsf.component.RichTextEditArea) component; comp.setSubmittedValue(finalValue); }
/** * Retrieves a formatted text attribute from an XML element; converts from older forms of * formatted text or plaintext, if found. For example, if the baseAttributeName "foo" is * specified, the attribute "foo-html" will be looked for first, and then "foo-formatted", and * finally just "foo" (plaintext). * * @param element The XML element from which to retrieve the formatted text attribute * @param baseAttributeName The base attribute name of the formatted text attribute */ public static String decodeFormattedTextAttribute(Element element, String baseAttributeName) { String ret; // first check if an HTML-encoded attribute exists, for example "foo-html", and use it if // available ret = StringUtil.trimToNull(Xml.decodeAttribute(element, baseAttributeName + "-html")); if (ret != null) return ret; // next try the older kind of formatted text like "foo-formatted", and convert it if found ret = StringUtil.trimToNull(Xml.decodeAttribute(element, baseAttributeName + "-formatted")); ret = FormattedText.convertOldFormattedText(ret); if (ret != null) return ret; // next try just a plaintext attribute and convert the plaintext to formatted text if found // convert from old plaintext instructions to new formatted text instruction ret = Xml.decodeAttribute(element, baseAttributeName); ret = FormattedText.convertPlaintextToFormattedText(ret); return ret; }
public String getSuggestionUrl() { String searchURL; try { searchURL = "?search=" + URLEncoder.encode(searchTermSuggestion, "UTF-8") + "&scope=" + this.scope; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } return FormattedText.escapeHtml(searchURL, false); }
/* * (non-Javadoc) * * @see org.sakaiproject.search.tool.api.SearchBean#getRssUrl() */ public String getRssURL() { if (hasResults()) { try { return FormattedText.escapeHtml( getToolUrl() + "/rss20?search=" + URLEncoder.encode(search, "UTF-8") + ((scope != null) ? "&scope=" + URLEncoder.encode(scope.toString(), "UTF-8") : ""), false); } catch (UnsupportedEncodingException e) { return FormattedText.escapeHtml( getToolUrl() + "/rss20?search=" + URLEncoder.encode(search) + ((scope != null) ? "&scope=" + URLEncoder.encode(scope.toString()) : ""), false); } } else { return null; } }
public ArrayList getSectionSelectList() { ArrayList list = new ArrayList(); ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.AuthorMessages"); AssessmentBean assessbean = (AssessmentBean) ContextUtil.lookupBean("assessmentBean"); List<SectionContentsBean> sectionSet = assessbean.getSections(); Iterator<SectionContentsBean> iter = sectionSet.iterator(); int i = 0; while (iter.hasNext()) { i = i + 1; SectionContentsBean part = iter.next(); SelectItem selection = new SelectItem(); // need to filter out all the random draw parts if (part.getSectionAuthorType().equals(SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL)) { // skip random draw parts, cannot add items to this part manually } else { if ("".equals(part.getTitle())) { selection.setLabel(rb.getString("p") + " " + i); } else { selection.setLabel( rb.getString("p") + " " + i + " - " + FormattedText.convertFormattedTextToPlaintext(part.getTitle())); } selection.setValue(part.getSectionId()); list.add(selection); } } Collections.reverse(list); // create a new part if there are no non-randomDraw parts available if (list.size() < 1) { i = i + 1; SelectItem temppart = new SelectItem(); temppart.setLabel(rb.getString("p") + " " + i); temppart.setValue( "-1"); // use -1 to indicate this is a temporary part. if the user decides to cancel the // operation, this part will not be created list.add(temppart); } return list; }
public void processAction(ActionEvent ae) throws AbortProcessingException { FacesContext context = FacesContext.getCurrentInstance(); // #1 - read the assessmentId from the form String publishedAssessmentId = (String) FacesContext.getCurrentInstance() .getExternalContext() .getRequestParameterMap() .get("publishedAssessmentId"); log.debug("publishedAssessmentId = " + publishedAssessmentId); // #2 - and use it to set author bean, goto removeAssessment.jsp PublishedAssessmentBean publishedAssessmentBean = (PublishedAssessmentBean) ContextUtil.lookupBean("publishedassessment"); PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService(); PublishedAssessmentFacade publishedAssessment = publishedAssessmentService.getPublishedAssessmentInfoForRemove( Long.valueOf(publishedAssessmentId)); if (publishedAssessment != null) { // #3 - permission checking before proceeding - daisyf AuthorBean author = (AuthorBean) ContextUtil.lookupBean("author"); AuthorizationBean authzBean = (AuthorizationBean) ContextUtil.lookupBean("authorization"); if (!authzBean.isUserAllowedToDeleteAssessment( publishedAssessmentId, publishedAssessment.getCreatedBy(), true)) { String err = (String) ContextUtil.getLocalizedString( "org.sakaiproject.tool.assessment.bundle.AuthorMessages", "denied_delete_other_members_assessment_error"); context.addMessage(null, new FacesMessage(err)); author.setOutcome("author"); return; } author.setOutcome("confirmRemovePublishedAssessment"); publishedAssessmentBean.setAssessmentId(publishedAssessmentId); publishedAssessmentBean.setTitle( FormattedText.convertFormattedTextToPlaintext(publishedAssessment.getTitle())); } else { log.warn("publishedAssessment is null"); } }
public void doError( HttpServletRequest request, HttpServletResponse response, Map<String, Object> theMap, String s, String message, Exception e) throws java.io.IOException { if (e != null) { M_log.error(e.getLocalizedMessage(), e); } theMap.put("/message_response/statusinfo/codemajor", "Fail"); theMap.put("/message_response/statusinfo/severity", "Error"); String msg = rb.getString(s) + ": " + message; M_log.info(msg); theMap.put( "/message_response/statusinfo/description", FormattedText.escapeHtmlFormattedText(msg)); String theXml = XMLMap.getXML(theMap, true); PrintWriter out = response.getWriter(); out.println(theXml); M_log.info("doError=" + theXml); }
public String getOrganizationName() { return FormattedText.convertFormattedTextToPlaintext(organizationName); }
public String getKeywords() { return FormattedText.convertFormattedTextToPlaintext(keywords); }
public String getDisplayName() { return FormattedText.convertFormattedTextToPlaintext(displayName); }
public void processAction(ActionEvent ae) throws AbortProcessingException { AssessmentBean assessmentBean = (AssessmentBean) ContextUtil.lookupBean("assessmentBean"); SectionBean sectionBean = (SectionBean) ContextUtil.lookupBean("sectionBean"); String sectionId = (String) FacesContext.getCurrentInstance() .getExternalContext() .getRequestParameterMap() .get("sectionId"); if (sectionId != null) { sectionBean.setSectionId(sectionId); } else { // i am afraid on returning from removal, EditPartListener is accled to // to re-populate the part // so i can't read sectionId from a form. - daisyf sectionId = sectionBean.getSectionId(); } AuthorBean author = (AuthorBean) ContextUtil.lookupBean("author"); isEditPendingAssessmentFlow = author.getIsEditPendingAssessmentFlow(); // log.info("**SectionId = "+sectionId); // #1a. prepare sectionBean AssessmentService assessmentService = null; SectionFacade section = null; if (isEditPendingAssessmentFlow) { EventTrackingService.post( EventTrackingService.newEvent( "sam.assessment.revise", "siteId=" + AgentFacade.getCurrentSiteId() + ", sectionId=" + sectionId, true)); assessmentService = new AssessmentService(); } else { EventTrackingService.post( EventTrackingService.newEvent( "sam.pubassessment.revise", "siteId=" + AgentFacade.getCurrentSiteId() + ", sectionId=" + sectionId, true)); assessmentService = new PublishedAssessmentService(); } section = assessmentService.getSection(sectionId); section.setAssessment(assessmentBean.getAssessment()); sectionBean.setSection(section); sectionBean.setSectionTitle(FormattedText.convertFormattedTextToPlaintext(section.getTitle())); sectionBean.setSectionDescription(section.getDescription()); sectionBean.setNoOfItems(String.valueOf(section.getItemSet().size())); populateMetaData(section, sectionBean); // todo: get poolsavailable and then add the current pool used, because we need to show it as // one of the choices. /* Huong moved to getPoolsAvailable in SectionBean.java ArrayList poolidlist = sectionBean.getPoolsAvailable(); String currpoolid= sectionBean.getSelectedPool(); // current pool used for random draw if (!("".equals(currpoolid)) && (currpoolid !=null)) { //System.out.println("current pool id not null or empty"); //now we need to get the poolid and displayName QuestionPoolService delegate = new QuestionPoolService();// QuestionPoolFacade pool= delegate.getPool(new Long(currpoolid), AgentFacade.getAgentString());// // now add the current pool used to the list, so it's available in the pulldown poolidlist.add(new SelectItem((pool.getQuestionPoolId().toString()), pool.getDisplayName()));// //System.out.println("added editing pool: "+ pool.getDisplayName());// sectionBean.setPoolsAvailable(poolidlist);// } */ boolean hideRandom = false; if ((sectionBean.getType() == null) || sectionBean.getType().equals(SectionDataIfc.QUESTIONS_AUTHORED_ONE_BY_ONE.toString())) { int itemsize = Integer.parseInt(sectionBean.getNoOfItems()); if (itemsize > 0) { hideRandom = true; } } sectionBean.setHideRandom(hideRandom); }
public void testProcessAnchor() { // Check we add the target attribute assertEquals( "<a href=\"http://sakaiproject.org/\" target=\"_blank\">", FormattedText.processAnchor("<a href=\"http://sakaiproject.org/\">")); }
public String getObjectives() { return FormattedText.convertFormattedTextToPlaintext(objectives); }
public void fillComponents( UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { String currentuserid = externalLogic.getCurrentUserId(); PollViewParameters ecvp = (PollViewParameters) viewparams; Poll poll = null; boolean isNew = true; UIForm newPoll = UIForm.make(tofill, "add-poll-form"); LOG.debug("Poll of id: " + ecvp.id); if (ecvp.id == null || "New 0".equals(ecvp.id)) { UIMessage.make(tofill, "new_poll_title", "new_poll_title"); // build an empty poll LOG.debug("this is a new poll"); poll = new Poll(); } else { UIMessage.make(tofill, "new_poll_title", "new_poll_title_edit"); String strId = ecvp.id; LOG.debug("got id of " + strId); poll = pollListManager.getPollById(Long.valueOf(strId)); voteBean.setPoll(poll); newPoll.parameters.add(new UIELBinding("#{poll.pollId}", poll.getPollId())); isNew = false; } if (!externalLogic.isUserAdmin() && !externalLogic.isAllowedInLocation( PollListManager.PERMISSION_ADD, externalLogic.getCurrentLocationReference(), externalLogic.getCurrentuserReference())) { tml.addMessage(new TargettedMessage("new_poll_noperms")); return; } // only display for exisiting polls if (!isNew) { // fill the options list UIBranchContainer actionBlock = UIBranchContainer.make(newPoll, "option-headers:"); UIMessage.make(actionBlock, "options-title", "new_poll_option_title"); UIInternalLink.make( actionBlock, "option-add", UIMessage.make("new_poll_option_add"), new OptionViewParameters(PollOptionProducer.VIEW_ID, null, poll.getPollId().toString())); List<Vote> votes = pollVoteManager.getAllVotesForPoll(poll); if (votes != null && votes.size() > 0) { LOG.debug("Poll has " + votes.size() + " votes"); UIBranchContainer errorRow = UIBranchContainer.make(tofill, "error-row:", "0"); UIMessage.make(errorRow, "error", "warn_poll_has_votes"); } List<Option> options = pollListManager.getVisibleOptionsForPoll(poll.getPollId()); for (int i = 0; i < options.size(); i++) { Option o = (Option) options.get(i); UIBranchContainer oRow = UIBranchContainer.make(actionBlock, "options-row:", o.getOptionId().toString()); UIVerbatim.make(oRow, "options-name", o.getOptionText()); UIInternalLink editOption = UIInternalLink.make( oRow, "option-edit", UIMessage.make("new_poll_option_edit"), new OptionViewParameters(PollOptionProducer.VIEW_ID, o.getOptionId().toString())); editOption.decorators = new DecoratorList( new UITooltipDecorator( messageLocator.getMessage("new_poll_option_edit") + ":" + FormattedText.convertFormattedTextToPlaintext(o.getOptionText()))); UIInternalLink deleteOption = UIInternalLink.make( oRow, "option-delete", UIMessage.make("new_poll_option_delete"), new OptionViewParameters( PollOptionDeleteProducer.VIEW_ID, o.getOptionId().toString())); deleteOption.decorators = new DecoratorList( new UITooltipDecorator( messageLocator.getMessage("new_poll_option_delete") + ":" + FormattedText.convertFormattedTextToPlaintext(o.getOptionText()))); } } UIMessage.make(tofill, "new-poll-descr", "new_poll_title"); UIMessage.make(tofill, "new-poll-question-label", "new_poll_question_label"); UIMessage pollDescr = UIMessage.make(tofill, "new-poll-descr-label", "new_poll_descr_label"); UIMessage.make(tofill, "new-poll-descr-label2", "new_poll_descr_label2"); // UIMessage.make(tofill, "new-poll-open-label", "new_poll_open_label"); // UIMessage.make(tofill, "new-poll-close-label", "new_poll_close_label"); UIMessage.make(tofill, "new-poll-limits", "new_poll_limits"); // UIMessage pollMin = UIMessage.make(tofill, "new-poll-min-limits", "new_poll_min_limits"); // UIMessage pollMax = UIMessage.make(tofill, "new-poll-max-limits", "new_poll_max_limits"); // the form fields UIInput.make(newPoll, "new-poll-text", "#{poll.text}", poll.getText()); if (!externalLogic.isMobileBrowser()) { // show WYSIWYG editor UIInput itemDescr = UIInput.make( newPoll, "newpolldescr:", "#{poll.details}", poll.getDetails()); // $NON-NLS-1$ //$NON-NLS-2$ richTextEvolver.evolveTextInput(itemDescr); UILabelTargetDecorator.targetLabel(pollDescr, itemDescr); } else { // do not show WYSIWYG editor in the mobile view UIInput itemDescr = UIInput.make( newPoll, "newpolldescr_mobile", "#{poll.details}", poll.getDetails()); // $NON-NLS-1$ //$NON-NLS-2$ UILabelTargetDecorator.targetLabel(pollDescr, itemDescr); } UIInput voteOpen = UIInput.make(newPoll, "openDate-iso8601", "poll.voteOpenStr", poll.getVoteOpenStr()); UIInput voteClose = UIInput.make(newPoll, "closeDate-iso8601", "poll.voteCloseStr", poll.getVoteCloseStr()); // UILabelTargetDecorator.targetLabel(pollOpen, voteOpen); // UILabelTargetDecorator.targetLabel(pollClose, voteClose); /* * access options */ UIMessage pollAccessLabel = UIMessage.make(newPoll, "poll_access_label", "new_poll_access_label"); UIBoundBoolean accessPublic = UIBoundBoolean.make(newPoll, "access-public", "poll.isPublic", poll.getIsPublic()); UIMessage newPollAccessPublicLabel = UIMessage.make(newPoll, "new_poll_access_public_label", "new_poll_access_public"); // SAK-25399: Do not display the public access by default if (!externalLogic.isShowPublicAccess()) { newPoll.remove(pollAccessLabel); newPoll.remove(accessPublic); newPoll.remove(newPollAccessPublicLabel); } String[] minVotes = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" }; String[] maxVotes = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" }; UISelect min = UISelect.make( newPoll, "min-votes", minVotes, "#{poll.minOptions}", Integer.toString(poll.getMinOptions())); UISelect max = UISelect.make( newPoll, "max-votes", maxVotes, "#{poll.maxOptions}", Integer.toString(poll.getMaxOptions())); /* * open - can be viewd at any time * never - not diplayed * afterVoting - after user has voted * afterClosing * */ String[] values = new String[] {"open", "afterVoting", "afterClosing", "never"}; String[] labels = new String[] { messageLocator.getMessage("new_poll_open"), messageLocator.getMessage("new_poll_aftervoting"), messageLocator.getMessage("new_poll_afterClosing"), messageLocator.getMessage("new_poll_never") }; UISelect radioselect = UISelect.make( newPoll, "release-select", values, "#{poll.displayResult}", poll.getDisplayResult()); radioselect.optionnames = UIOutputMany.make(labels); String selectID = radioselect.getFullID(); // StringList optList = new StringList(); UIMessage.make(newPoll, "add_results_label", "new_poll_results_label"); for (int i = 0; i < values.length; ++i) { UIBranchContainer radiobranch = UIBranchContainer.make(newPoll, "releaserow:", Integer.toString(i)); UISelectChoice choice = UISelectChoice.make(radiobranch, "release", selectID, i); UISelectLabel lb = UISelectLabel.make(radiobranch, "releaseLabel", selectID, i); UILabelTargetDecorator.targetLabel(lb, choice); } LOG.debug("About to close the form"); newPoll.parameters.add(new UIELBinding("#{poll.owner}", currentuserid)); String siteId = externalLogic.getCurrentLocationId(); newPoll.parameters.add(new UIELBinding("#{poll.siteId}", siteId)); if (isNew || poll.getPollOptions() == null || poll.getPollOptions().size() == 0) { UICommand.make( newPoll, "submit-new-poll", UIMessage.make("new_poll_saveoption"), "#{pollToolBean.processActionAdd}"); } else { UICommand.make( newPoll, "submit-new-poll", UIMessage.make("new_poll_submit"), "#{pollToolBean.processActionAdd}"); } UICommand cancel = UICommand.make( newPoll, "cancel", UIMessage.make("new_poll_cancel"), "#{pollToolBean.cancel}"); cancel.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "cancel")); LOG.debug("Finished generating view"); }
public String getDescription() { return FormattedText.convertFormattedTextToPlaintext(description); }
public void testProcessAnchorRelative() { // Check we add the target attribute assertEquals( "<a href=\"other.html\" target=\"_blank\">", FormattedText.processAnchor("<a href=\"other.html\">")); }
private void populateMetaData(SectionFacade section, SectionBean bean) { Set metaDataSet = section.getSectionMetaDataSet(); Iterator iter = metaDataSet.iterator(); // reset to null bean.setKeyword(null); bean.setObjective(null); bean.setRubric(null); boolean isRandomizationTypeSet = false; boolean isPointValueHasOverrided = false; boolean isDiscountValueHasOverrided = false; while (iter.hasNext()) { SectionMetaDataIfc meta = (SectionMetaDataIfc) iter.next(); if (meta.getLabel().equals(SectionMetaDataIfc.OBJECTIVES)) { bean.setObjective(FormattedText.convertFormattedTextToPlaintext(meta.getEntry())); } if (meta.getLabel().equals(SectionMetaDataIfc.KEYWORDS)) { bean.setKeyword(FormattedText.convertFormattedTextToPlaintext(meta.getEntry())); } if (meta.getLabel().equals(SectionMetaDataIfc.RUBRICS)) { bean.setRubric(FormattedText.convertFormattedTextToPlaintext(meta.getEntry())); } if (meta.getLabel().equals(SectionDataIfc.AUTHOR_TYPE)) { bean.setType(meta.getEntry()); } if (meta.getLabel().equals(SectionDataIfc.QUESTIONS_ORDERING)) { bean.setQuestionOrdering(meta.getEntry()); } if (meta.getLabel().equals(SectionDataIfc.POOLID_FOR_RANDOM_DRAW)) { bean.setSelectedPool(meta.getEntry()); } if (meta.getLabel().equals(SectionDataIfc.NUM_QUESTIONS_DRAWN)) { bean.setNumberSelected(meta.getEntry()); } if (meta.getLabel().equals(SectionDataIfc.RANDOMIZATION_TYPE)) { bean.setRandomizationType(meta.getEntry()); isRandomizationTypeSet = true; } if (meta.getLabel().equals(SectionDataIfc.POINT_VALUE_FOR_QUESTION)) { if (meta.getEntry() != null && !meta.getEntry().equals("")) { bean.setPointValueHasOverrided(true); isPointValueHasOverrided = true; } bean.setRandomPartScore(meta.getEntry()); } if (meta.getLabel().equals(SectionDataIfc.DISCOUNT_VALUE_FOR_QUESTION)) { if (meta.getEntry() != null && !meta.getEntry().equals("")) { bean.setDiscountValueHasOverrided(true); isDiscountValueHasOverrided = true; } bean.setRandomPartDiscount(meta.getEntry()); } } if (!isRandomizationTypeSet) { bean.setRandomizationType(SectionDataIfc.PER_SUBMISSION); } if (!isPointValueHasOverrided) { bean.setPointValueHasOverrided(false); bean.setRandomPartScore(null); } if (!isDiscountValueHasOverrided) { bean.setDiscountValueHasOverrided(false); bean.setRandomPartDiscount(null); } }
public void testProcessAnchorMailto() { assertEquals( "<a href=\"mailto:[email protected]\" target=\"_blank\">", FormattedText.processAnchor("<a href=\"mailto:[email protected]\">")); }
/** * This will populate the QuestionScoresBean with the data associated with the particular * versioned assessment based on the publishedId. * * @todo Some of this code will change when we move this to Hibernate persistence. * @param publishedId String * @param bean QuestionScoresBean * @return boolean */ public boolean questionScores( String publishedId, QuestionScoresBean bean, boolean isValueChange) { log.debug("questionScores()"); try { PublishedAssessmentService pubService = new PublishedAssessmentService(); PublishedItemService pubItemService = new PublishedItemService(); // get the PublishedAssessment based on publishedId QuestionScoresBean questionBean = (QuestionScoresBean) ContextUtil.lookupBean("questionScores"); PublishedAssessmentIfc publishedAssessment = questionBean.getPublishedAssessment(); if (publishedAssessment == null) { publishedAssessment = pubService.getPublishedAssessment(publishedId); questionBean.setPublishedAssessment(publishedAssessment); } // build a hashMap (publishedItemId, publishedItem) HashMap publishedItemHash = pubService.preparePublishedItemHash(publishedAssessment); log.debug("questionScores(): publishedItemHash.size = " + publishedItemHash.size()); // build a hashMap (publishedItemTextId, publishedItemText) HashMap publishedItemTextHash = pubService.preparePublishedItemTextHash(publishedAssessment); log.debug("questionScores(): publishedItemTextHash.size = " + publishedItemTextHash.size()); HashMap publishedAnswerHash = pubService.preparePublishedAnswerHash(publishedAssessment); // re-attach session and load all lazy loaded parent/child stuff // Set<Long> publishedAnswerHashKeySet = publishedAnswerHash.keySet(); // // for (Long key : publishedAnswerHashKeySet) { // AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(key); // // if (!Hibernate.isInitialized(answer.getChildAnswerSet())) { // pubItemService.eagerFetchAnswer(answer); // } // } log.debug("questionScores(): publishedAnswerHash.size = " + publishedAnswerHash.size()); HashMap agentResultsByItemGradingIdMap = new HashMap(); GradingService delegate = new GradingService(); TotalScoresBean totalBean = (TotalScoresBean) ContextUtil.lookupBean("totalScores"); if (ContextUtil.lookupParam("sortBy") != null && !ContextUtil.lookupParam("sortBy").trim().equals("")) bean.setSortType(ContextUtil.lookupParam("sortBy")); String itemId = ContextUtil.lookupParam("itemId"); if (ContextUtil.lookupParam("newItemId") != null && !ContextUtil.lookupParam("newItemId").trim().equals("") && !ContextUtil.lookupParam("newItemId").trim().equals("null")) itemId = ContextUtil.lookupParam("newItemId"); if (ContextUtil.lookupParam("sortAscending") != null && !ContextUtil.lookupParam("sortAscending").trim().equals("")) { bean.setSortAscending( Boolean.valueOf(ContextUtil.lookupParam("sortAscending")).booleanValue()); } String which = bean.getAllSubmissions(); if (which == null && totalBean.getAllSubmissions() != null) { // use totalscore's selection which = totalBean.getAllSubmissions(); bean.setAllSubmissions(which); } totalBean.setSelectedSectionFilterValue( bean.getSelectedSectionFilterValue()); // set section pulldown if (bean.getSelectedSARationaleView() == null) { // if bean.showSARationaleInLine is null, then set inline to be // the default bean.setSelectedSARationaleView(QuestionScoresBean.SHOW_SA_RATIONALE_RESPONSES_INLINE); } if ("true".equalsIgnoreCase(totalBean.getAnonymous())) { boolean groupRelease = publishedAssessment .getAssessmentAccessControl() .getReleaseTo() .equals(AssessmentAccessControl.RELEASE_TO_SELECTED_GROUPS); if (groupRelease) { totalBean.setSelectedSectionFilterValue( TotalScoresBean.RELEASED_SECTIONS_GROUPS_SELECT_VALUE); } else { totalBean.setSelectedSectionFilterValue(TotalScoresBean.ALL_SECTIONS_SELECT_VALUE); } } bean.setPublishedId(publishedId); Date dueDate = null; HashMap map = getItemScores(Long.valueOf(publishedId), Long.valueOf(itemId), which, isValueChange); log.debug("questionScores(): map .size = " + map.size()); ResourceLoader rb = null; ArrayList allscores = new ArrayList(); Iterator keyiter = map.keySet().iterator(); while (keyiter.hasNext()) { allscores.addAll((ArrayList) map.get(keyiter.next())); } log.debug("questionScores(): allscores.size = " + allscores.size()); // / // now we need filter by sections selected ArrayList scores = new ArrayList(); // filtered list Map useridMap = totalBean.getUserIdMap(TotalScoresBean.CALLED_FROM_QUESTION_SCORE_LISTENER); bean.setUserIdMap(useridMap); log.debug("questionScores(): useridMap.size = " + useridMap.size()); /* * if ("true".equalsIgnoreCase(totalBean.getAnonymous())){ // skip * section filter if it is anonymous grading, SAK-4395, * scores.addAll(allscores); } */ if (totalBean.getReleaseToAnonymous()) { // skip section filter if it's published to anonymous users scores.addAll(allscores); } else { Iterator allscores_iter = allscores.iterator(); // get the Map of all users(keyed on userid) belong to the // selected sections while (allscores_iter.hasNext()) { // AssessmentGradingData data = (AssessmentGradingData) // allscores_iter.next(); ItemGradingData idata = (ItemGradingData) allscores_iter.next(); // String agentid = // idata.getAssessmentGrading().getAgentId(); String agentid = idata.getAgentId(); // now we only include scores of users belong to the // selected sections if (useridMap.containsKey(agentid)) { scores.add(idata); } } } log.debug("questionScores(): scores.size = " + scores.size()); Iterator iter = scores.iterator(); ArrayList agents = new ArrayList(); log.debug("questionScores(): calling populateSections "); populateSections( publishedAssessment, bean, totalBean, scores, pubService); // set up the Q1, Q2... links if (!iter.hasNext()) { // this section has no students log.debug("questionScores(): this section has no students"); bean.setAgents(agents); bean.setAllAgents(agents); bean.setTotalPeople(Integer.toString(bean.getAgents().size())); bean.setAnonymous(totalBean.getAnonymous()); // return true; } // List them by item and assessmentgradingid, so we can // group answers by item and save them for update use. HashMap scoresByItem = new HashMap(); while (iter.hasNext()) { ItemGradingData idata = (ItemGradingData) iter.next(); ItemTextIfc pubItemText = (ItemTextIfc) publishedItemTextHash.get(idata.getPublishedItemTextId()); AnswerIfc pubAnswer = (AnswerIfc) publishedAnswerHash.get(idata.getPublishedAnswerId()); ArrayList temp = (ArrayList) scoresByItem.get(idata.getAssessmentGradingId() + ":" + idata.getPublishedItemId()); if (temp == null) temp = new ArrayList(); // Very small numbers, so bubblesort is fast Iterator iter2 = temp.iterator(); ArrayList newList = new ArrayList(); boolean added = false; while (iter2.hasNext()) { ItemGradingData tmpData = (ItemGradingData) iter2.next(); ItemTextIfc tmpPublishedText = (ItemTextIfc) publishedItemTextHash.get(tmpData.getPublishedItemTextId()); AnswerIfc tmpAnswer = (AnswerIfc) publishedAnswerHash.get(tmpData.getPublishedAnswerId()); if (pubAnswer != null && tmpAnswer != null && !added && (pubItemText.getSequence().intValue() < tmpPublishedText.getSequence().intValue() || (pubItemText.getSequence().intValue() == tmpPublishedText.getSequence().intValue() && pubAnswer.getSequence().intValue() < tmpAnswer.getSequence().intValue()))) { newList.add(idata); added = true; } newList.add(tmpData); } if (!added) newList.add(idata); scoresByItem.put( idata.getAssessmentGradingId() + ":" + idata.getPublishedItemId(), newList); } log.debug("questionScores(): scoresByItem.size = " + scoresByItem.size()); bean.setScoresByItem(scoresByItem); try { bean.setAnonymous( publishedAssessment .getEvaluationModel() .getAnonymousGrading() .equals(EvaluationModel.ANONYMOUS_GRADING) ? "true" : "false"); } catch (RuntimeException e) { // log.info("No evaluation model."); bean.setAnonymous("false"); } // below properties don't seem to be used in jsf pages, try { bean.setLateHandling( publishedAssessment.getAssessmentAccessControl().getLateHandling().toString()); } catch (Exception e) { // log.info("No access control model."); bean.setLateHandling(AssessmentAccessControl.NOT_ACCEPT_LATE_SUBMISSION.toString()); } try { bean.setDueDate(publishedAssessment.getAssessmentAccessControl().getDueDate().toString()); dueDate = publishedAssessment.getAssessmentAccessControl().getDueDate(); } catch (RuntimeException e) { // log.info("No due date."); bean.setDueDate(new Date().toString()); } try { bean.setMaxScore(publishedAssessment.getEvaluationModel().getFixedTotalScore()); } catch (RuntimeException e) { double score = (double) 0.0; Iterator iter2 = publishedAssessment.getSectionArraySorted().iterator(); while (iter2.hasNext()) { SectionDataIfc sdata = (SectionDataIfc) iter2.next(); Iterator iter3 = sdata.getItemArraySortedForGrading().iterator(); while (iter3.hasNext()) { ItemDataIfc idata = (ItemDataIfc) iter3.next(); if (idata.getItemId().equals(Long.valueOf(itemId))) score = idata.getScore().doubleValue(); } } bean.setMaxScore(score); } // need to get id from somewhere else, not from data. data only // contains answered items , we want to return all items. // ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(data.getPublishedItemId()); ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(Long.valueOf(itemId)); if (item != null) { log.debug("item!=null steting type id = " + item.getTypeId().toString()); bean.setTypeId(item.getTypeId().toString()); bean.setItemId(item.getItemId().toString()); bean.setPartName(item.getSection().getSequence().toString()); bean.setItemName(item.getSequence().toString()); item.setHint("***"); // Keyword to not show student answer // for short answer/ essey question, if there is a model short // answer for this question // set haveModelShortAnswer to true if (item.getTypeId().equals(Long.valueOf(5))) { Iterator iterator = publishedAnswerHash.values().iterator(); while (iterator.hasNext()) { PublishedAnswer publishedAnswer = (PublishedAnswer) iterator.next(); if (publishedAnswer.getItem().getItemId().equals(item.getItemId())) { if (publishedAnswer.getText() == null || publishedAnswer.getText().equals("")) { bean.setHaveModelShortAnswer(false); } else { bean.setHaveModelShortAnswer(true); } break; } } } } else { log.debug("item==null "); } ArrayList deliveryItems = new ArrayList(); // so we can use the var if (item != null) deliveryItems.add(item); bean.setDeliveryItem(deliveryItems); if (ContextUtil.lookupParam("roleSelection") != null) { bean.setRoleSelection(ContextUtil.lookupParam("roleSelection")); } if (bean.getSortType() == null) { if (bean.getAnonymous().equals("true")) { bean.setSortType("totalAutoScore"); } else { bean.setSortType("lastName"); } } // recordingData encapsulates the inbeanation needed for recording. // set recording agent, agent assessmentId, // set course_assignment_context value // set max tries (0=unlimited), and 30 seconds max length // String courseContext = bean.getAssessmentName() + " total "; // Note this is HTTP-centric right now, we can't use in Faces // AuthoringHelper authoringHelper = new AuthoringHelper(); // authoringHelper.getRemoteUserID() needs servlet stuff // authoringHelper.getRemoteUserName() needs servlet stuff /* Dump the grading and agent information into AgentResults */ iter = scoresByItem.values().iterator(); while (iter.hasNext()) { AgentResults results = new AgentResults(); // Get all the answers for this question to put in one grading // row ArrayList answerList = (ArrayList) iter.next(); results.setItemGradingArrayList(answerList); Iterator iter2 = answerList.iterator(); ArrayList itemGradingAttachmentList = new ArrayList(); HashMap<Long, Set<String>> fibmap = new HashMap<Long, Set<String>>(); while (iter2.hasNext()) { ItemGradingData gdata = (ItemGradingData) iter2.next(); results.setItemGrading(gdata); itemGradingAttachmentList.addAll(gdata.getItemGradingAttachmentList()); agentResultsByItemGradingIdMap.put(gdata.getItemGradingId(), results); ItemTextIfc gdataPubItemText = (ItemTextIfc) publishedItemTextHash.get(gdata.getPublishedItemTextId()); AnswerIfc gdataAnswer = (AnswerIfc) publishedAnswerHash.get(gdata.getPublishedAnswerId()); // This all just gets the text of the answer to display String answerText = noAnswer; String rationale = ""; String fullAnswerText = noAnswer; // if question type = MC, MR, Survey, TF, Matching, if user // has not submit an answer // answerText = noAnswer. These question type do not use the // itemGrading.answerText field for // storing answers, thye use temGrading.publishedAnswerId to // make their selection if (bean.getTypeId().equals("1") || bean.getTypeId().equals("2") || bean.getTypeId().equals("12") || bean.getTypeId().equals("3") || bean.getTypeId().equals("4") || bean.getTypeId().equals("9") || bean.getTypeId().equals("13")) { if (gdataAnswer != null) answerText = gdataAnswer.getText(); } else { // this handles the other question types: SAQ, File // upload, Audio, FIB, Fill in Numeric // These question type use itemGrading.answetText to // store information about their answer if ((bean.getTypeId().equals("8") || bean.getTypeId().equals("11") || bean.getTypeId().equals("14")) && gdataAnswer == null) { answerText = ""; } else if (bean.getTypeId().equals("14")) { // gopalrc - EMI answerText = gdataPubItemText.getSequence() + ": " + gdataAnswer.getLabel(); } else { answerText = gdata.getAnswerText(); } } if ("4".equals(bean.getTypeId())) { if (rb == null) { rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); } if ("true".equals(answerText)) { answerText = rb.getString("true_msg"); } else if ("false".equals(answerText)) { answerText = rb.getString("false_msg"); } } if (bean.getTypeId().equals("9")) { if (gdataPubItemText == null) { // the matching pair is deleted answerText = ""; } else { answerText = gdataPubItemText.getSequence() + ":" + answerText; } } if (bean.getTypeId().equals("8")) { if (gdataAnswer != null && gdataAnswer.getSequence() != null) { answerText = gdataAnswer.getSequence() + ":" + answerText; } } if (bean.getTypeId().equals("11")) { if (gdataAnswer != null && gdataAnswer.getSequence() != null) { answerText = gdataAnswer.getSequence() + ":" + answerText; } } if (bean.getTypeId().equals("13")) { if (gdataPubItemText == null) { answerText = ""; } else { int answerNo = gdataPubItemText.getSequence().intValue(); answerText = answerNo + ":" + answerText; } } // file upload if (bean.getTypeId().equals("6")) { gdata.setMediaArray(delegate.getMediaArray2(gdata.getItemGradingId().toString())); } // audio recording if (bean.getTypeId().equals("7")) { ArrayList mediaList = delegate.getMediaArray2(gdata.getItemGradingId().toString()); setDurationIsOver(item, mediaList); gdata.setMediaArray(mediaList); } if (bean.getTypeId().equals("16")) { if (gdataPubItemText == null) { // the matching pair is deleted answerText = ""; } else { answerText = gdataPubItemText.getSequence() + ":" + answerText; } } if (answerText == null) answerText = noAnswer; else { if (gdata.getRationale() != null && !gdata.getRationale().trim().equals("")) rationale = "\nRationale: " + gdata.getRationale(); } // Huong's temp commandout // answerText = answerText.replaceAll("<.*?>", ""); answerText = answerText.replaceAll("(\r\n|\r)", "<br/>"); rationale = rationale.replaceAll("<.*?>", ""); rationale = rationale.replaceAll("(\r\n|\r)", "<br/>"); fullAnswerText = answerText; // this is the // non-abbreviated answers // for essay questions int answerTextLength = ServerConfigurationService.getInt("samigo.questionScore.answerText.length", 1000); if (bean.getTypeId().equals("5")) { answerTextLength = 35; } // Fix for SAK-6932: Strip out all HTML tags except image tags if (answerText.length() > answerTextLength) { String noHTMLAnswerText; noHTMLAnswerText = answerText.replaceAll("<((..?)|([^iI][^mM][^gG].*?))>", ""); int index = noHTMLAnswerText.toLowerCase().indexOf("<img"); if (index != -1) { answerText = noHTMLAnswerText; } else { if (noHTMLAnswerText.length() > answerTextLength) { answerText = noHTMLAnswerText.substring(0, answerTextLength) + "..."; } else { answerText = noHTMLAnswerText; } } } /* * // no need to shorten it if (rationale.length() > 35) * rationale = rationale.substring(0, 35) + "..."; */ // SAM-755-"checkmark" indicates right, add "X" to indicate wrong if (gdataAnswer != null) { String checkmarkGif = "<img src='/samigo-app/images/delivery/checkmark.gif'>"; String crossmarkGif = "<img src='/samigo-app/images/crossmark.gif'>"; if (bean.getTypeId().equals("8") || bean.getTypeId().equals("11")) { answerText = FormattedText.escapeHtml(answerText, true); if (gdata.getIsCorrect() == null) { boolean result = false; if (bean.getTypeId().equals("8")) { result = delegate.getFIBResult(gdata, fibmap, item, publishedAnswerHash); } else { result = delegate.getFINResult(gdata, item, publishedAnswerHash); } if (result) { answerText = checkmarkGif + answerText; } else { answerText = crossmarkGif + answerText; } } else { if (gdata.getIsCorrect().booleanValue()) { answerText = checkmarkGif + answerText; } else { answerText = crossmarkGif + answerText; } } } else if (bean.getTypeId().equals("15")) { // CALCULATED_QUESTION answerText = FormattedText.escapeHtml(answerText, true); // need to do something here for fill in the blanks if (gdataAnswer.getScore() > 0) { // if score is 0, there is no way to tell if user got the correct answer // by using "autoscore"... wish there was a better way to tell if its correct or not Double autoscore = gdata.getAutoScore(); if (!(Double.valueOf(0)).equals(autoscore)) { answerText = checkmarkGif + answerText; } else if (Double.valueOf(0).equals(autoscore)) { answerText = crossmarkGif + answerText; } } } else if (!bean.getTypeId().equals("3")) { if ((gdataAnswer.getIsCorrect() != null && gdataAnswer.getIsCorrect()) || (gdataAnswer.getPartialCredit() != null && gdataAnswer.getPartialCredit() > 0)) { answerText = checkmarkGif + answerText; } else if (gdataAnswer.getIsCorrect() != null && !gdataAnswer.getIsCorrect()) { answerText = crossmarkGif + answerText; } } } // -- Got the answer text -- if (!answerList.get(0).equals(gdata)) { // We already have // an agentResults // for this one results.setAnswer(results.getAnswer() + "<br/>" + answerText); if (gdata.getAutoScore() != null) { results.setTotalAutoScore( Double.toString( (Double.valueOf(results.getExactTotalAutoScore())).doubleValue() + gdata.getAutoScore().doubleValue())); } else { results.setTotalAutoScore( Double.toString( (Double.valueOf(results.getExactTotalAutoScore())).doubleValue())); } results.setItemGradingAttachmentList(itemGradingAttachmentList); } else { results.setItemGradingId(gdata.getItemGradingId()); results.setAssessmentGradingId(gdata.getAssessmentGradingId()); if (gdata.getAutoScore() != null) { // for example, if an assessment has one fileupload // question, the autoscore = null results.setTotalAutoScore(gdata.getAutoScore().toString()); } else { results.setTotalAutoScore(Double.toString(0)); } results.setComments(FormattedText.convertFormattedTextToPlaintext(gdata.getComments())); results.setAnswer(answerText); results.setFullAnswer(fullAnswerText); results.setRationale(rationale); results.setSubmittedDate(gdata.getSubmittedDate()); AgentFacade agent = new AgentFacade(gdata.getAgentId()); // log.info("Rachel: agentid = " + gdata.getAgentId()); results.setLastName(agent.getLastName()); results.setFirstName(agent.getFirstName()); results.setEmail(agent.getEmail()); if (results.getLastName() != null && results.getLastName().length() > 0) results.setLastInitial(results.getLastName().substring(0, 1)); else if (results.getFirstName() != null && results.getFirstName().length() > 0) results.setLastInitial(results.getFirstName().substring(0, 1)); else results.setLastInitial("Anonymous"); results.setIdString(agent.getIdString()); results.setAgentEid(agent.getEidString()); results.setAgentDisplayId(agent.getDisplayIdString()); log.debug("testing agent getEid agent.getFirstname= " + agent.getFirstName()); log.debug("testing agent getEid agent.getid= " + agent.getIdString()); log.debug("testing agent getEid agent.geteid = " + agent.getEidString()); log.debug( "testing agent getDisplayId agent.getdisplayid = " + agent.getDisplayIdString()); results.setRole(agent.getRole()); results.setItemGradingAttachmentList(itemGradingAttachmentList); agents.add(results); } } } // log.info("Sort type is " + bean.getSortType() + "."); bs = new BeanSort(agents, bean.getSortType()); if ((bean.getSortType()).equals("assessmentGradingId") || (bean.getSortType()).equals("totalAutoScore") || (bean.getSortType()).equals("totalOverrideScore") || (bean.getSortType()).equals("finalScore")) { bs.toNumericSort(); } else { bs.toStringSort(); } if (bean.isSortAscending()) { log.debug("sortAscending"); agents = (ArrayList) bs.sort(); } else { log.debug("!sortAscending"); agents = (ArrayList) bs.sortDesc(); } // log.info("Listing agents."); bean.setAgents(agents); bean.setAllAgents(agents); bean.setTotalPeople(Integer.valueOf(bean.getAgents().size()).toString()); bean.setAgentResultsByItemGradingId(agentResultsByItemGradingIdMap); } catch (RuntimeException e) { e.printStackTrace(); return false; } return true; }
public void testProcessAnchorName() { assertEquals( "<a href=\"#anchor\" target=\"_blank\">", FormattedText.processAnchor("<a href=\"#anchor\">")); }