List of usage examples for java.text DateFormat MEDIUM
int MEDIUM
To view the source code for java.text DateFormat MEDIUM.
Click Source Link
From source file:com.appeligo.channelfeed.work.FileWriter.java
private synchronized void closeDoc() { if (body == null) { return;/* ww w . jav a2s. c o m*/ } try { doc = new PrintStream(new GZIPOutputStream(new FileOutputStream(filenamePrefix + ".html.gz"))); writeHead(); } catch (IOException e) { log.error("Can't create .html.gz file.", e); return; } try { String programTitle = program.getProgramTitle(); doc.println("<!-- WARNING, XDS IS INFORMATIONAL ONLY AND CAN BE VERY UNRELIABLE -->"); if (xdsData.getCallLettersAndNativeChannel() != null) { doc.println( "<meta name=\"XDSCallLettersAndNativeChannel\" content=\"" + StringEscapeUtils.escapeHtml( xdsData.getCallLettersAndNativeChannel().replaceAll("[\\p{Cntrl}]", "")) + "\"/>"); } if (xdsData.getNetworkName() != null) { doc.println("<meta name=\"XDSNetworkName\" content=\"" + StringEscapeUtils.escapeHtml(xdsData.getNetworkName().replaceAll("[\\p{Cntrl}]", "")) + "\"/>"); } if (xdsData.getProgramName() != null) { doc.println("<meta name=\"XDSProgramName\" content=\"" + StringEscapeUtils.escapeHtml(xdsData.getProgramName().replaceAll("[\\p{Cntrl}]", "")) + "\"/>"); if (programTitle == null) { programTitle = xdsData.getProgramName(); } } try { if (xdsData.getProgramType() != null) { doc.println("<meta name=\"XDSProgramType\" content=\"" + XDSData.convertProgramType(xdsData.getProgramType()) + "\"/>"); } if (xdsData.getProgramStartTimeID() != null) { long startTimestamp = XDSData.convertProgramStartTimeID(xdsData.getProgramStartTimeID()); doc.println("<meta name=\"XDSProgramStartTimeID\" content=\"" + startTimestamp + "\"/>"); Date date = new Date(startTimestamp); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG); df.setTimeZone(TimeZone.getTimeZone("GMT")); doc.println("<meta name=\"XDSProgramStartTime\" content=\"" + df.format(date) + "\"/>"); if (XDSData.convertProgramTapeDelayed(xdsData.getProgramStartTimeID())) { doc.println("<meta name=\"XDSProgramTapeDelayed\" content=\"true\"/>"); } } if (xdsData.getProgramLength() != null) { doc.println("<meta name=\"XDSProgramLength\" content=\"" + XDSData.convertProgramLength(xdsData.getProgramLength()) + "\"/>"); } } catch (Exception e) { //ignore program type errors... probably bad data... such is XDS } if (program != null) { doc.println("<meta name=\"ProgramID\" content=\"" + program.getProgramId() + "\"/>"); doc.println("<meta name=\"ScheduleID\" content=\"" + program.getScheduleId() + "\"/>"); doc.println("<meta name=\"EpisodeTitle\" content=\"" + StringEscapeUtils.escapeHtml(program.getEpisodeTitle()) + "\"/>"); doc.println("<meta name=\"StartTime\" content=\"" + program.getStartTime().getTime() + "\"/>"); doc.println("<meta name=\"EndTime\" content=\"" + program.getEndTime().getTime() + "\"/>"); doc.println("<meta name=\"TVRating\" content=\"" + StringEscapeUtils.escapeHtml(program.getTvRating()) + "\"/>"); if (programTitle == null) { programTitle = Long.toString(program.getStartTime().getTime()); } } doc.println("<title>" + StringEscapeUtils.escapeHtml(programTitle) + "</title>"); doc.println("</head>"); doc.println("<body>"); doc.println("<h1>" + StringEscapeUtils.escapeHtml(programTitle) + "</h1>"); body.close(); body = null; InputStream readBody = new BufferedInputStream(new FileInputStream(filenamePrefix + ".body")); int b = readBody.read(); while (b >= 0) { doc.write(b); b = readBody.read(); } readBody.close(); File f = new File(filenamePrefix + ".body"); f.delete(); writeFoot(); doc.close(); doc = null; } catch (FileNotFoundException e) { log.error("Lost .body file!", e); } catch (IOException e) { log.error("Error copying .body to .html.gz", e); } doc = null; }
From source file:org.sakaiproject.evaluation.tool.producers.TakeEvalProducer.java
public void fill(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { // force the headers to expire this - http://jira.sakaiproject.org/jira/browse/EVALSYS-621 RenderingUtils.setNoCacheHeaders(httpServletResponse); boolean canAccess = false; // can a user access this evaluation boolean userCanAccess = false; // can THIS user take this evaluation boolean isUserSitePublished = true; //is the users' valid group(s) published? At least one group must be String currentUserId = commonLogic.getCurrentUserId(); // set the session timeout to 5 hours evalExternalLogic.setSessionTimeout(18000); // use a date which is related to the current users locale DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); UIMessage.make(tofill, "page-title", "takeeval.page.title"); // get passed in get params EvalViewParameters evalTakeViewParams = (EvalViewParameters) viewparams; Long evaluationId = evalTakeViewParams.evaluationId; if (evaluationId == null) { // redirect over to the main view maybe?? (not sure how to do this in RSF) LOG.debug("User (" + currentUserId + ") cannot take evaluation, eval id is not set"); throw new IllegalArgumentException( "Invalid evaluationId: id must be set and cannot be null, cannot load evaluation"); }/*from w w w . j a v a 2 s.c o m*/ String evalGroupId = evalTakeViewParams.evalGroupId; responseId = evalTakeViewParams.responseId; // get the evaluation based on the passed in VPs EvalEvaluation eval = evaluationService.getEvaluationById(evaluationId); if (eval == null) { throw new IllegalArgumentException( "Invalid evaluationId (" + evaluationId + "), cannot load evaluation"); } if (!evalTakeViewParams.external) { UIBranchContainer navTool = UIBranchContainer.make(tofill, "navIntraTool:"); UIInternalLink.make(navTool, "summary-link", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID)); } UIMessage.make(tofill, "eval-title-header", "takeeval.eval.title.header"); UIOutput.make(tofill, "evalTitle", eval.getTitle()); /* check the states of the evaluation first to give the user a tip that this eval is not takeable, * also avoids wasting time checking permissions when the evaluation certainly is closed, * also allows us to give the user a nice custom message */ String evalState = evaluationService.returnAndFixEvalState(eval, true); // make sure state is up to date if (EvalUtils.checkStateBefore(evalState, EvalConstants.EVALUATION_STATE_ACTIVE, false)) { String dueDate = "--------"; if (eval.getDueDate() != null) { dueDate = df.format(eval.getDueDate()); } UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.not.open", new String[] { df.format(eval.getStartDate()), dueDate }); LOG.info("User (" + currentUserId + ") cannot take evaluation yet, not open until: " + eval.getStartDate()); } else if (EvalUtils.checkStateAfter(evalState, EvalConstants.EVALUATION_STATE_CLOSED, true)) { UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.closed", new String[] { df.format(eval.getDueDate()) }); LOG.info( "User (" + currentUserId + ") cannot take evaluation anymore, closed on: " + eval.getDueDate()); } else { // eval state is possible to take eval canAccess = true; } List<EvalGroup> validGroups = new ArrayList<>(); // stores EvalGroup objects if (canAccess) { if (LOG.isDebugEnabled()) { LOG.debug("User (" + currentUserId + ") can take evalution (" + evaluationId + ")"); } // eval is accessible so check user can take it if (evalGroupId != null) { // there was an eval group passed in so make sure things are ok if (evaluationService.canTakeEvaluation(currentUserId, evaluationId, evalGroupId)) { userCanAccess = true; } else { isUserSitePublished = false; } } // select the first eval group the current user can take evaluation in, // also store the total number so we can give the user a list to choose from if there are more than one Map<Long, List<EvalAssignGroup>> m = evaluationService .getAssignGroupsForEvals(new Long[] { evaluationId }, true, null); if (!commonLogic.isUserAnonymous(currentUserId) && commonLogic.isUserAdmin(currentUserId)) { // special case, the super admin can always access userCanAccess = true; List<EvalAssignGroup> assignGroups = m.get(evaluationId); for (int i = 0; i < assignGroups.size(); i++) { EvalAssignGroup assignGroup = assignGroups.get(i); if (evalGroupId == null) { // set the evalGroupId to the first valid group if unset evalGroupId = assignGroup.getEvalGroupId(); } validGroups.add(commonLogic.makeEvalGroupObject(assignGroup.getEvalGroupId())); } } else { EvalGroup[] evalGroups; if (EvalConstants.EVALUATION_AUTHCONTROL_NONE.equals(eval.getAuthControl())) { // anonymous eval allows any group to be evaluated List<EvalAssignGroup> assignGroups = m.get(evaluationId); evalGroups = new EvalGroup[assignGroups.size()]; for (int i = 0; i < assignGroups.size(); i++) { EvalAssignGroup assignGroup = assignGroups.get(i); evalGroups[i] = commonLogic.makeEvalGroupObject(assignGroup.getEvalGroupId()); } } else { List<EvalAssignUser> userAssignments = evaluationService.getParticipantsForEval(evaluationId, currentUserId, null, EvalAssignUser.TYPE_EVALUATOR, null, null, null); Set<String> evalGroupIds = EvalUtils.getGroupIdsFromUserAssignments(userAssignments); List<EvalGroup> groups = EvalUtils.makeGroupsFromGroupsIds(evalGroupIds, commonLogic); evalGroups = EvalUtils.getGroupsInCommon(groups, m.get(evaluationId)); } for (EvalGroup group : evalGroups) { if (evaluationService.canTakeEvaluation(currentUserId, evaluationId, group.evalGroupId)) { if (evalGroupId == null) { // set the evalGroupId to the first valid group if unset evalGroupId = group.evalGroupId; userCanAccess = true; } validGroups.add(commonLogic.makeEvalGroupObject(group.evalGroupId)); } } isUserSitePublished = userCanAccess; } if (!isUserSitePublished) { userCanAccess = false; UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.site.notpublished"); LOG.info( "User (" + currentUserId + ") cannot take evaluation because his site(s) are unpublished."); } else if (userCanAccess) { // check if we had a failure during a previous submit and get the missingKeys out if there are some Set<String> missingKeys = new HashSet<>(); if (messages.isError() && messages.size() > 0) { for (int i = 0; i < messages.size(); i++) { TargettedMessage message = messages.messageAt(i); Exception e = message.exception; if (e instanceof ResponseSaveException) { ResponseSaveException rse = (ResponseSaveException) e; if (rse.missingItemAnswerKeys != null && rse.missingItemAnswerKeys.length > 0) { missingKeys.addAll(Arrays.asList(rse.missingItemAnswerKeys)); } break; } } } // load up the response if this user has one already if (responseId == null) { response = evaluationService.getResponseForUserAndGroup(evaluationId, currentUserId, evalGroupId); if (response == null) { if (LOG.isDebugEnabled()) { LOG.debug("User (" + currentUserId + ") has no previous response for eval (" + evaluationId + ")"); } // create the initial response if there is not one // EVALSYS-360 because of a hibernate issue this will not work, do a binding instead -AZ //responseId = localResponsesLogic.createResponse(evaluationId, currentUserId, evalGroupId); } else { responseId = response.getId(); if (LOG.isDebugEnabled()) { LOG.debug("User (" + currentUserId + ") has previous response (" + responseId + ") in eval (" + evaluationId + ")"); } } } if (responseId != null) { // load up the previous responses for this user (no need to attempt to load if the response is new, there will be no answers yet) answerMap = localResponsesLogic.getAnswersMapByTempItemAndAssociated(responseId); if (LOG.isDebugEnabled()) { LOG.debug("User (" + currentUserId + "), eval (" + evaluationId + "), previous answers map: " + answerMap); } } // show the switch group selection and form if there are other valid groups for this user if (validGroups.size() > 1) { String[] values = new String[validGroups.size()]; String[] labels = new String[validGroups.size()]; for (int i = 0; i < validGroups.size(); i++) { EvalGroup group = validGroups.get(i); values[i] = group.evalGroupId; labels[i] = group.title; } // show the switch group selection and form UIBranchContainer showSwitchGroup = UIBranchContainer.make(tofill, "show-switch-group:"); UIMessage.make(showSwitchGroup, "switch-group-header", "takeeval.switch.group.header"); UIForm chooseGroupForm = UIForm.make(showSwitchGroup, "switch-group-form", new EvalViewParameters(TakeEvalProducer.VIEW_ID, evaluationId, responseId, evalGroupId)); UISelect.make(chooseGroupForm, "switch-group-list", values, labels, "#{evalGroupId}"); } // fill in group title EvalGroup evalGroup = commonLogic.makeEvalGroupObject(evalGroupId); UIBranchContainer groupTitle = UIBranchContainer.make(tofill, "show-group-title:"); UIMessage.make(groupTitle, "group-title-header", "takeeval.group.title.header"); UIOutput.make(groupTitle, "group-title", evalGroup.title); if (LOG.isDebugEnabled()) { LOG.debug("Begin render of eval: " + eval.getTitle() + " (" + evaluationId + "), group: " + groupTitle + " (" + evalGroupId + ")"); } // show instructions if not null if (eval.getInstructions() != null && !("".equals(eval.getInstructions()))) { UIBranchContainer instructions = UIBranchContainer.make(tofill, "show-eval-instructions:"); UIMessage.make(instructions, "eval-instructions-header", "takeeval.instructions.header"); UIVerbatim.make(instructions, "eval-instructions", eval.getInstructions()); } // get the setting and make sure it cannot be null (fix for http://www.caret.cam.ac.uk/jira/browse/CTL-531) Boolean studentAllowedLeaveUnanswered = (Boolean) evalSettings .get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED); if (studentAllowedLeaveUnanswered == null) { studentAllowedLeaveUnanswered = EvalUtils.safeBool(eval.getBlankResponsesAllowed(), false); } // show a warning to the user if all items must be filled in if (studentAllowedLeaveUnanswered == false) { UIBranchContainer note = UIBranchContainer.make(tofill, "show-eval-note:"); UIMessage.make(note, "eval-note-text", "takeeval.user.must.answer.all.note"); } UIBranchContainer formBranch = UIBranchContainer.make(tofill, "form-branch:"); UIForm form = UIForm.make(formBranch, "evaluationForm"); // bind the evaluation and evalGroup to the ones in the take eval bean String evalOTP = "evaluationBeanLocator."; form.parameters .add(new UIELBinding("#{takeEvalBean.eval}", new ELReference(evalOTP + eval.getId()))); form.parameters.add(new UIELBinding("#{takeEvalBean.evalGroupId}", evalGroupId)); // BEGIN the complex task of rendering the evaluation items // make the TI data structure TemplateItemDataList tidl = new TemplateItemDataList(evaluationId, evalGroupId, evaluationService, authoringService, hierarchyLogic, null); Set<String> instructorIds = tidl.getAssociateIds(EvalConstants.ITEM_CATEGORY_INSTRUCTOR); Set<String> assistantIds = tidl.getAssociateIds(EvalConstants.ITEM_CATEGORY_ASSISTANT); List<String> associatedTypes = tidl.getAssociateTypes(); if (LOG.isDebugEnabled()) { LOG.debug("TIDL: eval=" + evaluationId + ", group=" + evalGroupId + ", items=" + tidl.getTemplateItemsCount() + " instructorIds: " + instructorIds + ", " + " associatedTypes: " + associatedTypes); } // SELECTION Code - EVALSYS-618 Boolean selectionsEnabled = (Boolean) evalSettings .get(EvalSettings.ENABLE_INSTRUCTOR_ASSISTANT_SELECTION); String instructorSelectionOption = EvalAssignGroup.SELECTION_OPTION_ALL; String assistantSelectionOption = EvalAssignGroup.SELECTION_OPTION_ALL; if (LOG.isDebugEnabled()) { LOG.debug("Selections: enabled=" + selectionsEnabled + ", inst=" + instructorSelectionOption + ", asst=" + assistantSelectionOption); } Map<String, String[]> savedSelections = new HashMap<>(); if (response != null) { savedSelections = response.getSelections(); } if (selectionsEnabled) { // only do the selection calculations if it is enabled EvalAssignGroup assignGroup = evaluationService.getAssignGroupByEvalAndGroupId(evaluationId, evalGroupId); Map<String, String> selectorType = new HashMap<>(); instructorSelectionOption = EvalUtils .getSelectionSetting(EvalAssignGroup.SELECTION_TYPE_INSTRUCTOR, assignGroup, null); selectorType.put(EvalConstants.ITEM_CATEGORY_INSTRUCTOR, instructorSelectionOption); Boolean assistantsEnabled = (Boolean) evalSettings.get(EvalSettings.ENABLE_ASSISTANT_CATEGORY); if (assistantsEnabled) { assistantSelectionOption = EvalUtils .getSelectionSetting(EvalAssignGroup.SELECTION_TYPE_ASSISTANT, assignGroup, null); selectorType.put(EvalConstants.ITEM_CATEGORY_ASSISTANT, assistantSelectionOption); } if (response != null) { // emit currently selected people into hidden element for JS use Set<String> savedIds = new HashSet<>(); for (String selectKey : savedSelections.keySet()) { String[] usersFound = savedSelections.get(selectKey); savedIds.add(usersFound[0]); } UIOutput savedSel = UIOutput.make(formBranch, "selectedPeopleInResponse", savedIds.toString()); savedSel.decorators = new DecoratorList( new UIIDStrategyDecorator("selectedPeopleInResponse")); } Iterator<Map.Entry<String, String>> selector = selectorType.entrySet().iterator(); while (selector.hasNext()) { Map.Entry<String, String> pairs = selector.next(); String selectKey = (String) pairs.getKey(); String selectKeyLowerCaps = selectKey.toLowerCase(); String selectValue = (String) pairs.getValue(); String uiTag = "select-" + selectKeyLowerCaps; String selectionOTP = "#{takeEvalBean.selection" + selectKeyLowerCaps + "Ids}"; Set<String> selectUserIds = new HashSet<>(); if (selectKeyLowerCaps.equals(SELECT_KEY_INSTRUCTOR)) { selectUserIds = instructorIds; } else if (selectKeyLowerCaps.equals(SELECT_KEY_ASSISTANT)) { selectUserIds = assistantIds; } // We render the selection controls if there are at least two // Instructors/TAs if (selectUserIds.size() > 1 && associatedTypes.contains(selectKey)) { if (selectValue.equals(EvalAssignGroup.SELECTION_OPTION_ALL)) { // nothing special to do in all case } else if (EvalAssignGroup.SELECTION_OPTION_MULTIPLE.equals(selectValue)) { UIBranchContainer showSwitchGroup = UIBranchContainer.make(form, uiTag + "-multiple:"); // Things for building the UISelect of Assignment Checkboxes List<String> assLabels = new ArrayList<>(); List<String> assValues = new ArrayList<>(); UISelect assSelect = UISelect.makeMultiple(showSwitchGroup, uiTag + "-multiple-holder", new String[] {}, new String[] {}, selectionOTP, new String[] {}); String assSelectID = assSelect.getFullID(); for (String userId : selectUserIds) { EvalUser user = commonLogic.getEvalUserById(userId); assValues.add(user.userId); assLabels.add(user.displayName); UIBranchContainer row = UIBranchContainer.make(showSwitchGroup, uiTag + "-multiple-row:"); UISelectChoice.make(row, uiTag + "-multiple-box", assSelectID, assLabels.size() - 1); UISelectLabel.make(row, uiTag + "-multiple-label", assSelectID, assLabels.size() - 1); } assSelect.optionlist = UIOutputMany.make(assValues.toArray(new String[] {})); assSelect.optionnames = UIOutputMany.make(assLabels.toArray(new String[] {})); } else if (EvalAssignGroup.SELECTION_OPTION_ONE.equals(selectValue)) { List<String> value = new ArrayList<>(); List<String> label = new ArrayList<>(); value.add("default"); label.add(messageLocator.getMessage("takeeval.selection.dropdown")); List<EvalUser> users = commonLogic.getEvalUsersByIds(new ArrayList(selectUserIds)); for (EvalUser user : users) { value.add(user.userId); label.add(user.displayName); } UIBranchContainer showSwitchGroup = UIBranchContainer.make(form, uiTag + "-one:"); UIOutput.make(showSwitchGroup, uiTag + "-one-header"); UISelect.make(showSwitchGroup, uiTag + "-one-list", value.toArray(new String[value.size()]), label.toArray(new String[label.size()]), selectionOTP); } else { throw new IllegalStateException("Invalid selection option (" + selectValue + "): do not know how to handle this."); } } else if (selectUserIds.size() == 1 && associatedTypes.contains(selectKey)) { // handle case where there are selections set but ONLY 1 user in the role. if (!selectValue.equals(EvalAssignGroup.SELECTION_OPTION_ALL)) { for (String userId : selectUserIds) { form.parameters.add(new UIELBinding(selectionOTP, userId)); } } } else { // handle case where there are selections set but no users in the roles. if (!selectValue.equals(EvalAssignGroup.SELECTION_OPTION_ALL)) { form.parameters.add(new UIELBinding(selectionOTP, "none")); } } } } // loop through the TIGs and handle each associated category Boolean useCourseCategoryOnly = (Boolean) evalSettings .get(EvalSettings.ITEM_USE_COURSE_CATEGORY_ONLY); if (LOG.isDebugEnabled()) { LOG.debug("TIGs: useCourseCategoryOnly=" + useCourseCategoryOnly); } for (TemplateItemGroup tig : tidl.getTemplateItemGroups()) { if (LOG.isDebugEnabled()) { LOG.debug("TIGs: tig.associateType=" + tig.associateType); } UIBranchContainer categorySectionBranch = UIBranchContainer.make(form, "categorySection:"); // only do headers if we are allowed to use categories if (!useCourseCategoryOnly) { // handle printing the category header if (EvalConstants.ITEM_CATEGORY_COURSE.equals(tig.associateType)) { UIMessage.make(categorySectionBranch, "categoryHeader", "takeeval.group.questions.header"); } else if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(tig.associateType)) { showHeaders(categorySectionBranch, tig.associateType, tig.associateId, instructorIds, instructorSelectionOption, savedSelections); } else if (EvalConstants.ITEM_CATEGORY_ASSISTANT.equals(tig.associateType)) { showHeaders(categorySectionBranch, tig.associateType, tig.associateId, assistantIds, assistantSelectionOption, savedSelections); } } // loop through the hierarchy node groups if (LOG.isDebugEnabled()) { LOG.debug("TIGs: tig.hierarchyNodeGroups=" + tig.hierarchyNodeGroups.size()); } for (HierarchyNodeGroup hng : tig.hierarchyNodeGroups) { // render a node title if (hng.node != null) { // Showing the section title is system configurable via the administrate view Boolean showHierSectionTitle = (Boolean) evalSettings .get(EvalSettings.DISPLAY_HIERARCHY_HEADERS); if (showHierSectionTitle) { UIBranchContainer nodeTitleBranch = UIBranchContainer.make(categorySectionBranch, "itemrow:nodeSection"); UIOutput.make(nodeTitleBranch, "nodeTitle", hng.node.title); } } List<DataTemplateItem> dtis = hng.getDataTemplateItems(false); if (LOG.isDebugEnabled()) { LOG.debug("DTIs: count=" + dtis.size()); } for (int i = 0; i < dtis.size(); i++) { DataTemplateItem dti = dtis.get(i); UIBranchContainer nodeItemsBranch = UIBranchContainer.make(categorySectionBranch, "itemrow:templateItem"); if (i % 2 != 0) { nodeItemsBranch.decorate(new UIStyleDecorator("itemsListOddLine")); // must match the existing CSS class } renderItemPrep(nodeItemsBranch, form, dti, eval, missingKeys); } } } if (response != null && !response.complete) { UIMessage.make(tofill, "saveEvaluationWithoutSubmitWarning", "takeeval.saved.warning"); } Boolean saveEvaluationWithoutSubmit = (Boolean) evalSettings .get(EvalSettings.STUDENT_SAVE_WITHOUT_SUBMIT); if (saveEvaluationWithoutSubmit && (response == null || !response.complete)) { UICommand.make(form, "saveEvaluationWithoutSubmit", UIMessage.make("takeeval.save.button"), "#{takeEvalBean.saveEvaluationWithoutSubmit}"); } UICommand.make(form, "submitEvaluation", UIMessage.make("takeeval.submit.button"), "#{takeEvalBean.submitEvaluation}"); Boolean studentCancelAllowed = (Boolean) evalSettings.get(EvalSettings.STUDENT_CANCEL_ALLOWED); if (studentCancelAllowed) { UIMessage.make(form, "cancelEvaluation", "general.cancel.button"); // populate the URL we will activate (do NOT use summary-link here) UIInternalLink.make(tofill, "dashboard-link", new SimpleViewParameters(SummaryProducer.VIEW_ID)); } } else { // user cannot access eval so give them a sad message EvalUser current = commonLogic.getEvalUserById(currentUserId); UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.user.cannot.take", new String[] { current.displayName, current.email, current.username }); LOG.info("User (" + currentUserId + ") cannot take evaluation: " + eval.getId()); } } }
From source file:ch.entwine.weblounge.kernel.command.SiteCommand.java
/** * Prints out information about the given url or page identifier. * //w w w. jav a2 s . co m * @param site * the site * @param args * arguments to this function */ private void inspect(Site site, String[] args) { if (args.length == 0) { System.err.println("Please specify what to inspect"); System.err.println("Usage: site <id> inspect <url>|<id>"); return; } // What are we looking at? ContentRepository repository = site.getContentRepository(); Page page = null; // Is it a page? try { String objectId = args[0]; // TODO: What if we hit a file or an image? if (objectId.startsWith("/")) page = (Page) repository.get(new PageURIImpl(site, args[0])); else page = (Page) repository.get(new PageURIImpl(site, null, args[0])); if (page != null) { title("page"); pad("id", page.getURI().getIdentifier().toString()); pad("path", page.getURI().getPath()); section("lifecycle"); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG); // Created if (page.getCreationDate() != null) { StringBuffer buf = new StringBuffer(); buf.append(df.format(page.getCreationDate())); if (page.getCreator() != null) { buf.append(" by ").append(page.getCreator().toString()); } pad("created", buf.toString()); } // Modified if (page.getModificationDate() != null) { StringBuffer buf = new StringBuffer(); buf.append(df.format(page.getModificationDate())); if (page.getModifier() != null) { buf.append(" by ").append(page.getModifier().toString()); } pad("modified", buf.toString()); } // Published if (page.getPublishFrom() != null) { StringBuffer buf = new StringBuffer(); buf.append(df.format(page.getPublishFrom())); if (page.getPublisher() != null) { buf.append(" by ").append(page.getPublisher().toString()); } pad("published", buf.toString()); if (page.getPublishTo() != null) pad("published until", df.format(page.getPublishTo())); } section("header"); if (page.getTitle() != null) pad("title", page.getTitle()); // subjects StringBuffer subjectList = new StringBuffer(); for (String c : page.getSubjects()) { if (subjectList.length() > 0) subjectList.append(", "); subjectList.append(c); } pad("subjects", subjectList.toString()); section("content"); // composers StringBuffer composerList = new StringBuffer(); for (Composer c : page.getComposers()) { if (composerList.length() > 0) composerList.append(", "); composerList.append(c.getIdentifier()); composerList.append(" (").append(c.getPagelets().length).append(")"); } pad("composers", composerList.toString()); } } catch (ContentRepositoryException e) { System.err.println("Error trying to access the content repository"); e.printStackTrace(System.err); } }
From source file:mobisocial.bento.anyshare.util.DBHelper.java
private long addObjectByPostdata(long localId, Postdata postdata, long hash, byte[] raw, long parentid, String feedname, String sender) { long objId = (localId == -1) ? getNextId() : localId; String sizestr = ""; if (postdata.datatype.equals(Postdata.TYPE_STREAM)) { if (postdata.filesize < 972) { sizestr = "(" + postdata.filesize + "Byte)"; } else if (postdata.filesize < 996147) { sizestr = "(" + Math.floor(postdata.filesize / 1024 * 10) / 10 + "KB)"; } else if (postdata.filesize > 0) { sizestr = "(" + Math.floor(postdata.filesize / 1024 / 1024 * 10) / 10 + "MB)"; }/*from www . j a v a 2 s . c o m*/ } String desc = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT) .format(new Date(Long.parseLong(postdata.timestamp))) + " " + sizestr; if (!sender.isEmpty()) { desc += " by " + sender; } String title = postdata.title; ContentValues cv = new ContentValues(); cv.put(ItemObject._ID, objId); cv.put(ItemObject.FEEDNAME, feedname); cv.put(ItemObject.TITLE, title); cv.put(ItemObject.DESC, desc); cv.put(ItemObject.TIMESTAMP, postdata.timestamp); cv.put(ItemObject.OBJHASH, hash); cv.put(ItemObject.PARENT_ID, parentid); if (raw != null) { cv.put(ItemObject.RAW, raw); } // Log.d(TAG, cv.toString()); getWritableDatabase().insertOrThrow(ItemObject.TABLE, null, cv); return objId; }
From source file:at.alladin.rmbt.controlServer.HistoryResource.java
@Post("json") public String request(final String entity) { long startTime = System.currentTimeMillis(); addAllowOrigin();//from ww w .jav a 2 s .c o m JSONObject request = null; final ErrorList errorList = new ErrorList(); final JSONObject answer = new JSONObject(); String answerString; final String clientIpRaw = getIP(); System.out.println(MessageFormat.format(labels.getString("NEW_HISTORY"), clientIpRaw)); if (entity != null && !entity.isEmpty()) // try parse the string to a JSON object try { request = new JSONObject(entity); String lang = request.optString("language"); // Load Language Files for Client final List<String> langs = Arrays .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*")); if (langs.contains(lang)) { errorList.setLanguage(lang); labels = ResourceManager.getSysMsgBundle(new Locale(lang)); } else lang = settings.getString("RMBT_DEFAULT_LANGUAGE"); // System.out.println(request.toString(4)); if (conn != null) { final Client client = new Client(conn); if (request.optString("uuid").length() > 0 && client.getClientByUuid(UUID.fromString(request.getString("uuid"))) > 0) { final Locale locale = new Locale(lang); final Format format = new SignificantFormat(2, locale); String limitRequest = ""; if (request.optInt("result_limit", 0) != 0) { final int limit = request.getInt("result_limit"); //get offset string if there is one String offsetString = ""; if ((request.optInt("result_offset", 0) != 0) && (request.getInt("result_offset") >= 0)) { offsetString = " OFFSET " + request.getInt("result_offset"); } limitRequest = " LIMIT " + limit + offsetString; } final ArrayList<String> deviceValues = new ArrayList<>(); String deviceRequest = ""; if (request.optJSONArray("devices") != null) { final JSONArray devices = request.getJSONArray("devices"); boolean checkUnknown = false; final StringBuffer sb = new StringBuffer(); for (int i = 0; i < devices.length(); i++) { final String device = devices.getString(i); if (device.equals("Unknown Device")) checkUnknown = true; else { if (sb.length() > 0) sb.append(','); deviceValues.add(device); sb.append('?'); } } if (sb.length() > 0) deviceRequest = " AND (COALESCE(adm.fullname, t.model) IN (" + sb.toString() + ")" + (checkUnknown ? " OR model IS NULL OR model = ''" : "") + ")"; // System.out.println(deviceRequest); } final ArrayList<String> filterValues = new ArrayList<>(); String networksRequest = ""; if (request.optJSONArray("networks") != null) { final JSONArray tmpArray = request.getJSONArray("networks"); final StringBuilder tmpString = new StringBuilder(); if (tmpArray.length() >= 1) { tmpString.append("AND nt.group_name IN ("); boolean first = true; for (int i = 0; i < tmpArray.length(); i++) { if (first) first = false; else tmpString.append(','); tmpString.append('?'); filterValues.add(tmpArray.getString(i)); } tmpString.append(')'); } networksRequest = tmpString.toString(); } final JSONArray historyList = new JSONArray(); final PreparedStatement st; try { if (client.getSync_group_id() == 0) { //use faster request ignoring sync-group as user is not synced (id=0) st = conn.prepareStatement(String.format( "SELECT DISTINCT" + " t.uuid, time, timezone, speed_upload, speed_download, ping_median, network_type, nt.group_name network_type_group_name," + " COALESCE(adm.fullname, t.model) model" + " FROM test t" + " LEFT JOIN device_map adm ON adm.codename=t.model" + " LEFT JOIN network_type nt ON t.network_type=nt.uid" + " WHERE t.deleted = false AND t.implausible = false AND t.status = 'FINISHED'" + " AND client_id = ?" + " %s %s" + " ORDER BY time DESC" + " %s", deviceRequest, networksRequest, limitRequest)); } else { //use slower request including sync-group if client is synced st = conn.prepareStatement(String.format("SELECT DISTINCT" + " t.uuid, time, timezone, speed_upload, speed_download, ping_median, network_type, nt.group_name network_type_group_name," + " COALESCE(adm.fullname, t.model) model" + " FROM test t" + " LEFT JOIN device_map adm ON adm.codename=t.model" + " LEFT JOIN network_type nt ON t.network_type=nt.uid" + " WHERE t.deleted = false AND t.implausible = false AND t.status = 'FINISHED'" + " AND (t.client_id IN (SELECT ? UNION SELECT uid FROM client WHERE sync_group_id = ? ))" + " %s %s" + " ORDER BY time DESC" + " %s", deviceRequest, networksRequest, limitRequest)); } int i = 1; st.setLong(i++, client.getUid()); if (client.getSync_group_id() != 0) st.setInt(i++, client.getSync_group_id()); for (final String value : deviceValues) st.setString(i++, value); for (final String filterValue : filterValues) st.setString(i++, filterValue); //System.out.println(st.toString()); final ResultSet rs = st.executeQuery(); while (rs.next()) { final JSONObject jsonItem = new JSONObject(); jsonItem.put("test_uuid", rs.getString("uuid")); final Date date = rs.getTimestamp("time"); final long time = date.getTime(); final String tzString = rs.getString("timezone"); final TimeZone tz = TimeZone.getTimeZone(tzString); jsonItem.put("time", time); jsonItem.put("timezone", tzString); final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale); dateFormat.setTimeZone(tz); jsonItem.put("time_string", dateFormat.format(date)); jsonItem.put("speed_upload", format.format(rs.getInt("speed_upload") / 1000d)); jsonItem.put("speed_download", format.format(rs.getInt("speed_download") / 1000d)); final long ping = rs.getLong("ping_median"); jsonItem.put("ping", format.format(ping / 1000000d)); // backwards compatibility for old clients jsonItem.put("ping_shortest", format.format(ping / 1000000d)); jsonItem.put("model", rs.getString("model")); jsonItem.put("network_type", rs.getString("network_type_group_name")); //for appscape-iPhone-Version: also add classification to the response jsonItem.put("speed_upload_classification", Classification .classify(classification.THRESHOLD_UPLOAD, rs.getInt("speed_upload"))); jsonItem.put("speed_download_classification", Classification .classify(classification.THRESHOLD_DOWNLOAD, rs.getInt("speed_download"))); jsonItem.put("ping_classification", Classification .classify(classification.THRESHOLD_PING, rs.getLong("ping_median"))); // backwards compatibility for old clients jsonItem.put("ping_shortest_classification", Classification .classify(classification.THRESHOLD_PING, rs.getLong("ping_median"))); historyList.put(jsonItem); } if (historyList.length() == 0) errorList.addError("ERROR_DB_GET_HISTORY"); // errorList.addError(MessageFormat.format(labels.getString("ERROR_DB_GET_CLIENT"), // new Object[] {uuid})); rs.close(); st.close(); } catch (final SQLException e) { e.printStackTrace(); errorList.addError("ERROR_DB_GET_HISTORY_SQL"); // errorList.addError("ERROR_DB_GET_CLIENT_SQL"); } answer.put("history", historyList); } else errorList.addError("ERROR_REQUEST_NO_UUID"); } else errorList.addError("ERROR_DB_CONNECTION"); } catch (final JSONException e) { errorList.addError("ERROR_REQUEST_JSON"); System.out.println("Error parsing JSDON Data " + e.toString()); } catch (final IllegalArgumentException e) { errorList.addError("ERROR_REQUEST_NO_UUID"); } else errorList.addErrorString("Expected request is missing."); try { answer.putOpt("error", errorList.getList()); } catch (final JSONException e) { System.out.println("Error saving ErrorList: " + e.toString()); } answerString = answer.toString(); long elapsedTime = System.currentTimeMillis() - startTime; System.out.println(MessageFormat.format(labels.getString("NEW_HISTORY_SUCCESS"), clientIpRaw, Long.toString(elapsedTime))); return answerString; }
From source file:org.kalypso.model.wspm.tuhh.core.wprof.BCEShapeWPRofContentProvider.java
@Override public String getProfileComment() { final Date date = getDate(); final String dateText = date == null ? "-" : DateFormat.getDateInstance(DateFormat.MEDIUM).format(date); //$NON-NLS-1$ final String pnam = getPNam(); final StringBuilder builder = new StringBuilder(); builder.append(String.format("Gew-ID: %s%nProfilname: %s%nErster Punkt: %s%nErster Obj_Typ: %s%n", //$NON-NLS-1$ getRiverId(), pnam, getComment(), getObjectType())); builder.append(String.format("Aufgenommen am: %s", dateText)); //$NON-NLS-1$ final String pdfUrl = getPdfUrl(); if (pdfUrl != null) { builder.append(String.format("%nPDF: %s ", pdfUrl)); //$NON-NLS-1$ }//from w w w . j av a 2s. co m return builder.toString(); }
From source file:org.xwiki.batchimport.internal.DefaultBatchImport.java
@Override public MappingPreviewResult getMappingPreview(BatchImportConfiguration config, int maxRows, String logHint) throws IOException, XWikiException { XWikiContext xcontext = getXWikiContext(); XWiki xwiki = xcontext.getWiki();//from w w w . ja v a 2s .c o m // log to report how this import goes BatchImportLog log = getLog(logHint); // the file to import ImportFileIterator metadatafilename = null; try { metadatafilename = getImportFileIterator(config); } catch (ComponentLookupException e) { // IOException directly from the getFileIterator method throw new IOException( "Could not find an import file reader for the configuration: " + config.toString(), e); } // mapping from the class fields to source file columns Map<String, String> mapping = config.getFieldsMapping(); // class to map data to (objects of this class will be created) BaseClass defaultClass = xwiki.getXClass( currentDocumentStringResolver.resolve(config.getMappingClassName(), StringUtils.isEmpty(config.getWiki()) ? null : new WikiReference(config.getWiki())), xcontext); // TODO: validate that mapping is correct on top of this class, issue an "Error" if not (more of a warning than // an error): check that fields exist, etc // the locale of the data to read Locale sourceLocale = config.getLocale(); // prepare the default date formatter to process the dates in this row DateFormat defaultDateFormatter = null; String defaultDateFormat = config.getDefaultDateFormat(); if (StringUtils.isEmpty(defaultDateFormat)) { if (sourceLocale != null) { defaultDateFormatter = DateFormat.getDateInstance(DateFormat.MEDIUM, sourceLocale); } // get it from preferences, hoping that it's set defaultDateFormat = xcontext.getWiki().getXWikiPreference("dateformat", xcontext); } defaultDateFormatter = new SimpleDateFormat(defaultDateFormat); // and get a number formatter, we'll use this to process the numbers a bit. NumberFormat numberFormatter = null; if (sourceLocale != null) { numberFormatter = NumberFormat.getInstance(sourceLocale); } // whether this file has header row or not (whether first line needs to be imported or not) boolean hasHeaderRow = config.hasHeaderRow(); // list of document names, used to remember what are the document names that were generated from the // document. Note that for multiple imports from the same document, this list should be identical. List<DocumentReference> docNameList = new ArrayList<DocumentReference>(); // the previewed rows: processed and validated List<Map<String, Object>> previewRows = new LinkedList<Map<String, Object>>(); // start reading the rows and process them one by one metadatafilename.resetFile(config); List<String> currentLine = null; int rowIndex = 0; List<String> headers = null; // if there is no header row the headers are the numbers of the columns as strings if (hasHeaderRow) { headers = getColumnHeaders(metadatafilename, hasHeaderRow); currentLine = metadatafilename.readNextLine(); rowIndex = 1; } else { currentLine = metadatafilename.readNextLine(); headers = new ArrayList<String>(); for (int i = 0; i < currentLine.size(); i++) { headers.add(Integer.toString(i)); } } while (currentLine != null) { // break if we already did the rows if (rowIndex > maxRows) { break; } Map<String, String> data = getData(currentLine, mapping, headers); // generate page name DocumentReference generatedDocName = getPageName(data, rowIndex, config, docNameList); boolean pageNameValid = true; // process the row if (generatedDocName != null) { // check if it's duplicated name boolean isDuplicateName = docNameList.contains(generatedDocName); if (!isDuplicateName) { docNameList.add(generatedDocName); } // validate the page name (check if it fits in the xwiki db, length of fullName, etc) pageNameValid = validatePageName(generatedDocName, rowIndex, currentLine, mapping, data, true, log); } Map<String, Object> parsedData = parseAndValidatePageData(data, rowIndex, currentLine, this.entityReferenceSerializer.serialize(generatedDocName), defaultClass, config, defaultDateFormatter, numberFormatter, true, log, true); // add the generated document reference in the parsed data parsedData.put("doc.reference", pageNameValid ? ((generatedDocName == null) ? "" : generatedDocName) : null); previewRows.add(parsedData); // go to next line currentLine = metadatafilename.readNextLine(); rowIndex++; } log.log("donepreview"); return new MappingPreviewResult(previewRows, log); }
From source file:org.apache.roller.weblogger.ui.struts2.util.UIAction.java
public String getMediumDateFormat() { DateFormat sdf = DateFormat.getDateInstance(DateFormat.MEDIUM, getLocale()); if (sdf instanceof SimpleDateFormat) { return ((SimpleDateFormat) sdf).toPattern(); }/*w ww . j av a 2 s . com*/ return "MMM dd, yyyy"; }
From source file:org.methodize.nntprss.admin.AdminServlet.java
private void writeFooter(Writer writer) throws IOException { DateFormat df = DateFormat.getTimeInstance(DateFormat.MEDIUM); writer.write("<p>"); writer.write("</td></tr></table>"); writer.write("<table cellspacing='0' cellpadding='2' width='100%'><tr><td class='row2'>nntp//rss v" + AppConstants.VERSION + "</td><td class='row2' align='center'>nntp//rss Time: " + df.format(new Date()) + "</td><td class='row2' align='right'><a href='http://www.methodize.org/nntprss'>nntp//rss home page</a> </td></tr></table>"); writer.write("</td></tr></table>"); writer.write("</body></html>"); }
From source file:DateUtil.java
/** * Gets date pattern without time symbols according to given locale in MEDIUM style * * @param locale Locale to searh pattern for * @return Date pattern without time symbols in medium format * @see java.text.DateFormat#MEDIUM//from ww w. j ava 2 s. co m */ public static String getDatePattern(Locale locale) { return getDatePattern(locale, DateFormat.MEDIUM); }