List of usage examples for java.time ZonedDateTime format
@Override
public String format(DateTimeFormatter formatter)
From source file:org.cgiar.ccafs.marlo.action.summaries.StudySummaryAction.java
@Override public String execute() throws Exception { if (projectExpectedStudyID == null || projectExpectedStudyManager.getProjectExpectedStudyById(projectExpectedStudyID) == null || projectExpectedStudyManager.getProjectExpectedStudyById(projectExpectedStudyID) .getProjectExpectedStudyInfo(this.getSelectedPhase()) == null) { LOG.error("ProjectExpectedStudy " + projectExpectedStudyID + " Not found"); return NOT_FOUND; } else {//from ww w .ja v a 2s . c o m projectExpectedStudyInfo = projectExpectedStudyManager .getProjectExpectedStudyById(projectExpectedStudyID) .getProjectExpectedStudyInfo(this.getSelectedPhase()); } ByteArrayOutputStream os = new ByteArrayOutputStream(); try { Resource reportResource = resourceManager .createDirectly(this.getClass().getResource("/pentaho/crp/StudyPDF.prpt"), MasterReport.class); MasterReport masterReport = (MasterReport) reportResource.getResource(); String center = this.getLoggedCrp().getAcronym(); // Get datetime ZonedDateTime timezone = ZonedDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm "); String zone = timezone.getOffset() + ""; if (zone.equals("Z")) { zone = "+0"; } String date = timezone.format(format) + "(GMT" + zone + ")"; // Set Main_Query CompoundDataFactory cdf = CompoundDataFactory.normalize(masterReport.getDataFactory()); String masterQueryName = "main"; TableDataFactory sdf = (TableDataFactory) cdf.getDataFactoryForQuery(masterQueryName); TypedTableModel model = this.getMasterTableModel(center, date, String.valueOf(this.getSelectedYear())); sdf.addTable(masterQueryName, model); masterReport.setDataFactory(cdf); // Set i8n for pentaho masterReport = this.addi8nParameters(masterReport); // Get details band ItemBand masteritemBand = masterReport.getItemBand(); // Create new empty subreport hash map HashMap<String, Element> hm = new HashMap<String, Element>(); // method to get all the subreports in the prpt and store in the HashMap this.getAllSubreports(hm, masteritemBand); // Uncomment to see which Subreports are detecting the method getAllSubreports // System.out.println("Pentaho SubReports: " + hm); this.fillSubreport((SubReport) hm.get("study"), "study"); PdfReportUtil.createPDF(masterReport, os); bytesPDF = os.toByteArray(); os.close(); } catch (Exception e) { LOG.error("Error generating Study Summary: " + e.getMessage()); throw e; } // Calculate time of generation long stopTime = System.currentTimeMillis(); stopTime = stopTime - startTime; LOG.info("Downloaded successfully: " + this.getFileName() + ". User: " + this.getDownloadByUser() + ". CRP: " + this.getLoggedCrp().getAcronym() + ". Time to generate: " + stopTime + "ms."); return SUCCESS; }
From source file:org.openhab.binding.darksky.internal.handler.DarkSkyWeatherAndForecastHandler.java
/** * Applies the given configuration to the given timestamp. * * @param dateTime timestamp represented as {@link ZonedDateTime} * @param config {@link DarkSkyChannelConfiguration} instance * @return the modified timestamp//from ww w . j ava 2 s .com */ private ZonedDateTime applyChannelConfig(ZonedDateTime dateTime, @Nullable DarkSkyChannelConfiguration config) { ZonedDateTime modifiedDateTime = dateTime; if (config != null) { if (config.getOffset() != 0) { if (logger.isTraceEnabled()) { logger.trace("Apply offset of {} min to timestamp '{}'.", config.getOffset(), modifiedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); } modifiedDateTime = modifiedDateTime.plusMinutes(config.getOffset()); } long earliestInMinutes = config.getEarliestInMinutes(); if (earliestInMinutes > 0) { ZonedDateTime earliestDateTime = modifiedDateTime.truncatedTo(ChronoUnit.DAYS) .plusMinutes(earliestInMinutes); if (modifiedDateTime.isBefore(earliestDateTime)) { if (logger.isTraceEnabled()) { logger.trace("Use earliest timestamp '{}' instead of '{}'.", earliestDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME), modifiedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); } return earliestDateTime; } } long latestInMinutes = config.getLatestInMinutes(); if (latestInMinutes > 0) { ZonedDateTime latestDateTime = modifiedDateTime.truncatedTo(ChronoUnit.DAYS) .plusMinutes(latestInMinutes); if (modifiedDateTime.isAfter(latestDateTime)) { if (logger.isTraceEnabled()) { logger.trace("Use latest timestamp '{}' instead of '{}'.", latestDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME), modifiedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); } return latestDateTime; } } } return modifiedDateTime; }
From source file:org.cgiar.ccafs.marlo.action.center.summaries.CapdevSummaryAction.java
@Override public String execute() throws Exception { final ByteArrayOutputStream os = new ByteArrayOutputStream(); final Resource reportResource = resourceManager .createDirectly(this.getClass().getResource("/pentaho/center/Capdev.prpt"), MasterReport.class); final MasterReport masterReport = (MasterReport) reportResource.getResource(); String center = this.getCurrentCrp().getAcronym(); // Get datetime ZonedDateTime timezone = ZonedDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm "); String zone = timezone.getOffset() + ""; if (zone.equals("Z")) { zone = "+0"; }//from w w w .java2 s . co m String currentDate = timezone.format(format) + "(GMT" + zone + ")"; // Set Main_Query CompoundDataFactory cdf = CompoundDataFactory.normalize(masterReport.getDataFactory()); String masterQueryName = "main"; TableDataFactory sdf = (TableDataFactory) cdf.getDataFactoryForQuery(masterQueryName); TypedTableModel model = this.getMasterTableModel(center, currentDate); sdf.addTable(masterQueryName, model); masterReport.setDataFactory(cdf); // Get details band final ItemBand masteritemBand = masterReport.getItemBand(); // Create new empty subreport hash map final HashMap<String, Element> hm = new HashMap<String, Element>(); // method to get all the subreports in the prpt and store in the HashMap this.getAllSubreports(hm, masteritemBand); // Uncomment to see which Subreports are detecting the method getAllSubreports // Subreport list of capdev this.fillSubreport((SubReport) hm.get("capdev_interventions"), "capdev_interventions"); this.fillSubreport((SubReport) hm.get("capdev_participants"), "capdev_participants"); this.fillSubreport((SubReport) hm.get("individual_types"), "individual_types"); this.fillSubreport((SubReport) hm.get("groupTypes"), "groupTypes"); this.fillSubreport((SubReport) hm.get("disciplines"), "disciplines"); this.fillSubreport((SubReport) hm.get("target_groups"), "target_groups"); this.fillSubreport((SubReport) hm.get("programs"), "programs"); this.fillSubreport((SubReport) hm.get("crp"), "crp"); this.fillSubreport((SubReport) hm.get("capdevSummary"), "capdevSummary"); this.fillSubreport((SubReport) hm.get("citizenship"), "citizenship"); this.fillSubreport((SubReport) hm.get("funding_type"), "funding_type"); this.fillSubreport((SubReport) hm.get("institution"), "institution"); this.fillSubreport((SubReport) hm.get("institutions_type"), "institutions_type"); ExcelReportUtil.createXLSX(masterReport, os); bytesXLS = os.toByteArray(); os.close(); return SUCCESS; }
From source file:org.cgiar.ccafs.marlo.action.summaries.StudiesSummaryAction.java
@Override public String execute() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); try {//from w w w .j a v a2 s.c o m Resource reportResource; if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) { reportResource = resourceManager.createDirectly( this.getClass().getResource("/pentaho/crp/CaseStudiesExcel.prpt"), MasterReport.class); } else { reportResource = resourceManager.createDirectly( this.getClass().getResource("/pentaho/crp/StudiesPDF.prpt"), MasterReport.class); } MasterReport masterReport = (MasterReport) reportResource.getResource(); String center = this.getLoggedCrp().getAcronym(); // Get datetime ZonedDateTime timezone = ZonedDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm "); String zone = timezone.getOffset() + ""; if (zone.equals("Z")) { zone = "+0"; } String date = timezone.format(format) + "(GMT" + zone + ")"; // Set Main_Query CompoundDataFactory cdf = CompoundDataFactory.normalize(masterReport.getDataFactory()); String masterQueryName = "main"; TableDataFactory sdf = (TableDataFactory) cdf.getDataFactoryForQuery(masterQueryName); TypedTableModel model = this.getMasterTableModel(center, date, String.valueOf(this.getSelectedYear())); sdf.addTable(masterQueryName, model); masterReport.setDataFactory(cdf); // Set i8n for pentaho masterReport = this.addi8nParameters(masterReport); // Get details band ItemBand masteritemBand = masterReport.getItemBand(); // Create new empty subreport hash map HashMap<String, Element> hm = new HashMap<String, Element>(); // method to get all the subreports in the prpt and store in the HashMap this.getAllSubreports(hm, masteritemBand); // Uncomment to see which Subreports are detecting the method getAllSubreports // System.out.println("Pentaho SubReports: " + hm); this.fillSubreport((SubReport) hm.get("case_studies"), "case_studies"); if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) { ExcelReportUtil.createXLSX(masterReport, os); bytesXLSX = os.toByteArray(); } else { PdfReportUtil.createPDF(masterReport, os); bytesPDF = os.toByteArray(); } os.close(); } catch (Exception e) { LOG.error("Error generating CaseStudy" + this.getSelectedFormat() + ": " + e.getMessage()); throw e; } // Calculate time of generation long stopTime = System.currentTimeMillis(); stopTime = stopTime - startTime; LOG.info("Downloaded successfully: " + this.getFileName() + ". User: " + this.getCurrentUser().getComposedCompleteName() + ". CRP: " + this.getLoggedCrp().getAcronym() + ". Time to generate: " + stopTime + "ms."); return SUCCESS; }
From source file:org.openhab.binding.darksky.internal.handler.DarkSkyWeatherAndForecastHandler.java
/** * Schedules or reschedules a job for the channel with the given id if the given timestamp is in the future. * * @param channelId id of the channel// w w w . jav a 2 s . c om * @param dateTime timestamp of the job represented as {@link ZonedDateTime} */ @SuppressWarnings("null") private synchronized void scheduleJob(String channelId, ZonedDateTime dateTime) { long delay = dateTime.toEpochSecond() - ZonedDateTime.now().toEpochSecond(); if (delay > 0) { Job job = JOBS.get(channelId); if (job == null || job.getFuture().isCancelled()) { if (logger.isDebugEnabled()) { logger.debug("Schedule job for '{}' in {} s (at '{}').", channelId, delay, dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); } JOBS.put(channelId, new Job(channelId, delay)); } else { if (delay != job.getDelay()) { if (logger.isDebugEnabled()) { logger.debug("Reschedule job for '{}' in {} s (at '{}').", channelId, delay, dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); } job.getFuture().cancel(true); JOBS.put(channelId, new Job(channelId, delay)); } } } }
From source file:org.cgiar.ccafs.marlo.action.summaries.SearchTermsSummaryAction.java
@Override public String execute() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); try {/*from w w w . j av a 2s.c o m*/ Resource reportResource = resourceManager.createDirectly( this.getClass().getResource("/pentaho/crp/SearchTerms.prpt"), MasterReport.class); MasterReport masterReport = (MasterReport) reportResource.getResource(); String center = this.getLoggedCrp().getAcronym(); // Get datetime ZonedDateTime timezone = ZonedDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm "); String zone = timezone.getOffset() + ""; if (zone.equals("Z")) { zone = "+0"; } String currentDate = timezone.format(format) + "(GMT" + zone + ")"; String parameters = this.getRequest().getParameter("keys"); if (parameters != null) { if (parameters.isEmpty()) { // Empty keys } else { // String parametersNotEspecialChar = parameters.replaceAll("[^a-zA-Z0-9]+", ""); keys = Arrays.asList(parameters.split(",")); } } // Set Main_Query CompoundDataFactory cdf = CompoundDataFactory.normalize(masterReport.getDataFactory()); String masterQueryName = "main"; TableDataFactory sdf = (TableDataFactory) cdf.getDataFactoryForQuery(masterQueryName); TypedTableModel model = this.getMasterTableModel(center, currentDate); sdf.addTable(masterQueryName, model); masterReport.setDataFactory(cdf); // Set i8n for pentaho masterReport = this.addi8nParameters(masterReport); // Get details band ItemBand masteritemBand = masterReport.getItemBand(); // Create new empty subreport hash map HashMap<String, Element> hm = new HashMap<String, Element>(); // method to get all the subreports in the prpt and store in the HashMap this.getAllSubreports(hm, masteritemBand); // Uncomment to see which Subreports are detecting the method getAllSubreports // System.out.println("Pentaho SubReports: " + hm); this.fillSubreport((SubReport) hm.get("projects_details"), "project"); this.fillSubreport((SubReport) hm.get("projects_activities"), "activities"); this.fillSubreport((SubReport) hm.get("projects_deliverables"), "deliverables"); ExcelReportUtil.createXLSX(masterReport, os); bytesXLSX = os.toByteArray(); os.close(); } catch (Exception e) { LOG.error("Error generating PDF " + e.getMessage()); throw e; } // Calculate time of generation long stopTime = System.currentTimeMillis(); stopTime = stopTime - startTime; LOG.info("Downloaded successfully: " + this.getFileName() + ". User: " + this.getCurrentUser().getComposedCompleteName() + ". CRP: " + this.getLoggedCrp().getAcronym() + ". Cycle: " + this.getSelectedCycle() + ". Time to generate: " + stopTime + "ms."); return SUCCESS; }
From source file:org.cgiar.ccafs.marlo.action.summaries.ExpectedDeliverablesSummaryAction.java
private TypedTableModel getMasterTableModel() { // Initialization of Model TypedTableModel model = new TypedTableModel( new String[] { "center", "date", "year", "regionalAvalaible", "showDescription", "cycle" }, new Class[] { String.class, String.class, String.class, Boolean.class, Boolean.class, String.class }); String center = this.getLoggedCrp().getAcronym(); ZonedDateTime timezone = ZonedDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm "); String zone = timezone.getOffset() + ""; if (zone.equals("Z")) { zone = "+0"; }//from w w w . j a v a2 s. c o m String date = timezone.format(format) + "(GMT" + zone + ")"; String year = this.getSelectedYear() + ""; model.addRow(new Object[] { center, date, year, this.hasProgramnsRegions(), this.hasSpecificities(APConstants.CRP_REPORTS_DESCRIPTION), this.getSelectedCycle() }); return model; }
From source file:com.teradata.benchto.service.TagControllerTest.java
@Test public void tagsHappyPath() throws Exception { ZonedDateTime start = currentDateTime(); // create env mvc.perform(post("/v1/environment/env").contentType(APPLICATION_JSON).content("{}")) .andExpect(status().isOk()); // create tag1 mvc.perform(post("/v1/tag/env").contentType(APPLICATION_JSON) .content(storeTagRequest("tag1", "description for tag1"))).andExpect(status().isOk()); ZonedDateTime afterTag1 = currentDateTime(); // create tag2 mvc.perform(/*from ww w . j a va 2s. c o m*/ post("/v1/tag/env").contentType(APPLICATION_JSON).content(storeTagRequest("tag2 - no description"))) .andExpect(status().isOk()); // create tag3 mvc.perform(post("/v1/tag/env").contentType(APPLICATION_JSON) .content(storeTagRequest("tag3", "description for tag3"))).andExpect(status().isOk()); // get all tags mvc.perform(get("/v1/tags/env").contentType(APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(3))).andExpect(jsonPath("$[0].name", is("tag1"))) .andExpect(jsonPath("$[0].description", is("description for tag1"))) .andExpect(jsonPath("$[1].name", is("tag2 - no description"))) .andExpect(jsonPath("$[1].description", isEmptyOrNullString())) .andExpect(jsonPath("$[2].name", is("tag3"))) .andExpect(jsonPath("$[2].description", is("description for tag3"))); // get tag2, get3 mvc.perform(get("/v1/tags/env").contentType(APPLICATION_JSON) .content("{\"start\": \"" + afterTag1.format(ISO_ZONED_DATE_TIME) + "\"}")) .andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(2))) .andExpect(jsonPath("$[0].name", is("tag2 - no description"))) .andExpect(jsonPath("$[0].description", isEmptyOrNullString())) .andExpect(jsonPath("$[1].name", is("tag3"))) .andExpect(jsonPath("$[1].description", is("description for tag3"))); // get tag1 mvc.perform(get("/v1/tags/env").contentType(APPLICATION_JSON) .content("{\"start\": \"" + start.format(ISO_ZONED_DATE_TIME) + "\", \"end\": \"" + afterTag1.format(ISO_ZONED_DATE_TIME) + "\"}")) .andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(1))) .andExpect(jsonPath("$[0].name", is("tag1"))) .andExpect(jsonPath("$[0].description", is("description for tag1"))); // get latest tag mvc.perform(get("/v1/tags/env/latest").contentType(APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(jsonPath("$.name", is("tag3"))) .andExpect(jsonPath("$.description", is("description for tag3"))); // get latest tag but not older than afterTat1 timestamp mvc.perform(get("/v1/tags/env/latest?until={until}", afterTag1.toInstant().toEpochMilli()) .contentType(APPLICATION_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$.name", is("tag1"))) .andExpect(jsonPath("$.description", is("description for tag1"))); // get latest tag but not older than start timestamp mvc.perform(get("/v1/tags/env/latest?until={until}", start.toInstant().toEpochMilli()) .contentType(APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(result -> jsonPath("$.name", is("tag1"))).andExpect(content().string("")); }
From source file:org.sakaiproject.contentreview.impl.turnitin.TurnitinReviewServiceImpl.java
/** * Syncs an assignment and handles individual student extensions *///www . j a va 2s.co m public void syncAssignment(String siteId, String taskId, Map<String, Object> extraAsnnOpts, Date extensionDate) throws SubmissionException, TransientSubmissionException { Site s = null; try { s = siteService.getSite(siteId); } catch (IdUnusedException iue) { log.warn("createAssignment: Site " + siteId + " not found!" + iue.getMessage()); throw new TransientSubmissionException( "Create Assignment not successful. Site " + siteId + " not found"); } org.sakaiproject.assignment.api.Assignment asn; try { asn = assignmentService.getAssignment(taskId); } catch (IdUnusedException | PermissionException e) { asn = null; } ////////////////////////////// NEW LTI INTEGRATION /////////////////////////////// Optional<Date> asnCreationDateOpt = getAssignmentCreationDate(asn); if (asnCreationDateOpt.isPresent() && siteAdvisor.siteCanUseLTIReviewServiceForAssignment(s, asnCreationDateOpt.get())) { log.debug("Creating new TII assignment using the LTI integration"); String asnId = asnRefToId(taskId); // taskId is an assignment reference, but we sometimes only want the assignment id String ltiId = getActivityConfigValue(TurnitinConstants.STEALTHED_LTI_ID, asnId, TurnitinConstants.SAKAI_ASSIGNMENT_TOOL_ID, TurnitinConstants.PROVIDER_ID); String ltiReportsId = null; ltiReportsId = s.getProperties().getProperty("turnitin_reports_lti_id"); log.debug("This assignment has associated the following LTI Reports id: " + ltiReportsId); Map<String, String> ltiProps = new HashMap<>(); if (extraAsnnOpts == null) { throw new TransientSubmissionException("Create Assignment not successful. Empty extraAsnnOpts map"); } ltiProps.put("context_id", siteId); ltiProps.put("context_title", s.getTitle()); String contextLabel = s.getTitle(); if (s.getShortDescription() != null) { contextLabel = s.getShortDescription(); } ltiProps.put("context_label", contextLabel); ltiProps.put("resource_link_id", taskId); String title = extraAsnnOpts.get("title").toString(); ltiProps.put("resource_link_title", title); String description = extraAsnnOpts.get("instructions").toString(); if (description != null) { description = description.replaceAll("\\<.*?>", "");//TODO improve this int instructionsMax = serverConfigurationService.getInt("contentreview.instructions.max", 1000); if (description.length() > instructionsMax) { description = description.substring(0, instructionsMax); } } ltiProps.put("resource_link_description", description); // TII-245 if (!StringUtils.isBlank(ltiId)) { // This is an existing LTI instance, need to handle student extensions handleIndividualExtension(extensionDate, taskId, extraAsnnOpts); } String custom = BasicLTIConstants.RESOURCE_LINK_ID + "=" + taskId; custom += "\n" + BasicLTIConstants.RESOURCE_LINK_TITLE + "=" + title; custom += "\n" + BasicLTIConstants.RESOURCE_LINK_DESCRIPTION + "=" + description; try { long timestampOpen = (Long) extraAsnnOpts.get("timestampOpen"); long timestampDue = (Long) extraAsnnOpts.get("timestampDue"); // TII-245 - add a buffer to the TII due date to give time for the process queue job timestampDue += serverConfigurationService.getInt("contentreview.due.date.queue.job.buffer.minutes", 0) * 60000; ZonedDateTime open = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestampOpen), ZoneOffset.UTC); ZonedDateTime due = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestampDue), ZoneOffset.UTC); // Turnitin requires dates in ISO8601 format. The example from their documentation is "2014-12-10T07:43:43Z". // This matches the Java formatter ISO_INSTANT String isoStart = open.format(DateTimeFormatter.ISO_INSTANT); String isoDue = due.format(DateTimeFormatter.ISO_INSTANT); ltiProps.put("startdate", isoStart); ltiProps.put("duedate", isoDue); ltiProps.put("feedbackreleasedate", isoDue); custom += "\n" + "startdate=" + isoStart; custom += "\n" + "duedate=" + isoDue; custom += "\n" + "feedbackreleasedate=" + isoDue; } catch (DateTimeException e) { log.error(e); throw new TransientSubmissionException( "Create Assignment not successful. Invalid open and/or due date."); } ltiProps = putInstructorInfo(ltiProps, siteId); /* * Force TII max points to 100 so we can interpret the result as a direct percentage. * This is done because Assignments now has the ability to grade to an arbitrary number of decimal places. * Due to the limitation of TII requiring whole integers for grading, we would have to inflate the grade by a * factor to the power of the number of decimal places allowed. This would result in unusually large numbers * on the TII, which could be confusing for the end user. */ ltiProps.put("maxpoints", "100"); custom += "\n" + "maxpoints=100"; ltiProps.put("studentpapercheck", extraAsnnOpts.get("s_paper_check").toString()); ltiProps.put("journalcheck", extraAsnnOpts.get("journal_check").toString()); ltiProps.put("internetcheck", extraAsnnOpts.get("internet_check").toString()); ltiProps.put("institutioncheck", extraAsnnOpts.get("institution_check").toString()); ltiProps.put("allow_non_or_submissions", extraAsnnOpts.get("allow_any_file").toString()); //ONLY FOR TII UK //ltiProps.setProperty("anonymous_marking_enabled", extraAsnnOpts.get("s_paper_check")); custom += "\n" + "studentpapercheck=" + extraAsnnOpts.get("s_paper_check").toString(); custom += "\n" + "journalcheck=" + extraAsnnOpts.get("journal_check").toString(); custom += "\n" + "internetcheck=" + extraAsnnOpts.get("internet_check").toString(); custom += "\n" + "institutioncheck=" + extraAsnnOpts.get("institution_check").toString(); custom += "\n" + "allow_non_or_submissions=" + extraAsnnOpts.get("allow_any_file").toString(); if (extraAsnnOpts.containsKey("exclude_type") && extraAsnnOpts.containsKey("exclude_value")) { //exclude type 0=none, 1=words, 2=percentages String typeAux = "words"; if (extraAsnnOpts.get("exclude_type").toString().equals("2")) { typeAux = "percentage"; } ltiProps.put("exclude_type", typeAux); ltiProps.put("exclude_value", extraAsnnOpts.get("exclude_value").toString()); custom += "\n" + "exclude_type=" + typeAux; custom += "\n" + "exclude_value=" + extraAsnnOpts.get("exclude_value").toString(); } ltiProps.put("late_accept_flag", extraAsnnOpts.get("late_accept_flag").toString()); ltiProps.put("report_gen_speed", extraAsnnOpts.get("report_gen_speed").toString()); ltiProps.put("s_view_reports", extraAsnnOpts.get("s_view_report").toString()); ltiProps.put("submit_papers_to", extraAsnnOpts.get("submit_papers_to").toString()); custom += "\n" + "late_accept_flag=" + extraAsnnOpts.get("late_accept_flag").toString(); custom += "\n" + "report_gen_speed=" + extraAsnnOpts.get("report_gen_speed").toString(); custom += "\n" + "s_view_reports=" + extraAsnnOpts.get("s_view_report").toString(); custom += "\n" + "submit_papers_to=" + extraAsnnOpts.get("submit_papers_to").toString(); if (extraAsnnOpts.containsKey("exclude_biblio")) { ltiProps.put("use_biblio_exclusion", extraAsnnOpts.get("exclude_biblio").toString()); custom += "\n" + "use_biblio_exclusion=" + extraAsnnOpts.get("exclude_biblio").toString(); } if (extraAsnnOpts.containsKey("exclude_quoted")) { ltiProps.put("use_quoted_exclusion", extraAsnnOpts.get("exclude_quoted").toString()); custom += "\n" + "use_quoted_exclusion=" + extraAsnnOpts.get("exclude_quoted").toString(); } //adding callback url String callbackUrl = serverConfigurationService.getServerUrl() + "/sakai-contentreview-tool-tii/tii-servlet"; log.debug("callbackUrl: " + callbackUrl); ltiProps.put("ext_resource_tool_placement_url", callbackUrl); TurnitinReturnValue result = tiiUtil.makeLTIcall(TurnitinLTIUtil.BASIC_ASSIGNMENT, null, ltiProps); if (result.getResult() < 0) { log.error("Error making LTI call"); throw new TransientSubmissionException( "Create Assignment not successful. Check the logs to see message."); } Properties sakaiProps = new Properties(); String globalId = tiiUtil.getGlobalTurnitinLTIToolId(); String globalReportsId = tiiUtil.getGlobalTurnitinReportsLTIToolId(); if (globalId == null) { throw new TransientSubmissionException( "Create Assignment not successful. TII LTI global id not set"); } if (globalReportsId == null) { throw new TransientSubmissionException( "Create Assignment not successful. TII Reports LTI global id not set"); } sakaiProps.setProperty(LTIService.LTI_SITE_ID, siteId); sakaiProps.setProperty(LTIService.LTI_TITLE, title); log.debug("Storing custom params: " + custom); sakaiProps.setProperty(LTIService.LTI_CUSTOM, custom); SecurityAdvisor advisor = new SimpleSecurityAdvisor(sessionManager.getCurrentSessionUserId(), "site.upd", "/site/!admin"); Object ltiContent = null; Object ltiReportsContent = null; try { securityService.pushAdvisor(advisor); sakaiProps.setProperty(LTIService.LTI_TOOL_ID, globalId); if (StringUtils.isEmpty(ltiId)) { ltiContent = tiiUtil.insertTIIToolContent(globalId, sakaiProps); } else {//don't create lti tool if exists ltiContent = tiiUtil.updateTIIToolContent(ltiId, sakaiProps); } // replace the property sakaiProps.setProperty(LTIService.LTI_TOOL_ID, globalReportsId); if (StringUtils.isEmpty(ltiReportsId)) { ltiReportsContent = tiiUtil.insertTIIToolContent(globalReportsId, sakaiProps); } else { ltiReportsContent = tiiUtil.updateTIIToolContent(ltiReportsId, sakaiProps); } } catch (Exception e) { throw new TransientSubmissionException( "Create Assignment not successful. Error trying to insert TII tool content: " + e.getMessage()); } finally { securityService.popAdvisor(advisor); } if (ltiContent == null) { throw new TransientSubmissionException( "Create Assignment not successful. Could not create LTI tool for the task: " + custom); } else if (ltiReportsContent == null) { throw new TransientSubmissionException( "Create Assignment not successful. Could not create LTI Reports tool for the task: " + custom); } else if (!StringUtils.isEmpty(ltiId) && !Boolean.TRUE.equals(ltiContent)) { // if ltiId is not empty, the lti already exists, so we did an update. ltiContent is Boolean.TRUE if the update was successful throw new TransientSubmissionException( "Update Assignment not successful. Error updating LTI stealthed tool: " + ltiId); } else if (ltiReportsId != null && !Boolean.TRUE.equals(ltiReportsContent)) { throw new TransientSubmissionException( "Update Assignment not successful. Error updating LTI reports stealthed tool: " + ltiReportsContent); } else if (StringUtils.isEmpty(ltiId) && !(ltiContent instanceof Long)) { // if ltiId is empty, the lti is new, so we did an insert. ltiContent is a Long primary key if the update was successful throw new TransientSubmissionException( "Create Assignment not successful. Error creating LTI stealthed tool: " + ltiContent); } else if (ltiReportsId == null && !(ltiReportsContent instanceof Long)) { throw new TransientSubmissionException( "Create Assignment not successful. Error creating LTI stealthed tool: " + ltiReportsContent); } if (StringUtils.isEmpty(ltiId) || ltiReportsId == null) {//we inserted, need to record the IDs log.debug("LTI content tool id: " + ltiContent); try { if (ltiReportsId == null) { ResourcePropertiesEdit rpe = s.getPropertiesEdit(); rpe.addProperty("turnitin_reports_lti_id", String.valueOf(ltiReportsContent)); siteService.save(s); } } catch (IdUnusedException e) { log.error("Could not store reports LTI tool ID " + ltiReportsContent + " for site " + s.getId(), e); throw new TransientSubmissionException( "Create Assignment not successful. Error storing LTI stealthed reports tool: " + ltiReportsContent); } catch (PermissionException e) { log.error("Could not store reports LTI tool ID " + ltiReportsContent + " for site " + s.getId(), e); throw new TransientSubmissionException( "Create Assignment not successful. Error storing LTI stealthed reports tool: " + ltiReportsContent); } boolean added = saveOrUpdateActivityConfigEntry(TurnitinConstants.STEALTHED_LTI_ID, String.valueOf(ltiContent), asnId, TurnitinConstants.SAKAI_ASSIGNMENT_TOOL_ID, TurnitinConstants.PROVIDER_ID, true); if (!added) { log.error("Could not store LTI tool ID " + ltiContent + " for assignment " + taskId); throw new TransientSubmissionException( "Create Assignment not successful. Error storing LTI stealthed tool: " + ltiContent); } } //add submissions to the queue if there is any try { log.debug("Adding previous submissions"); //this will be done always - no problem, extra checks log.debug("Assignment " + asn.getId() + " - " + asn.getTitle()); List<AssignmentSubmission> submissions = assignmentService.getSubmissions(asn); if (submissions != null) { for (AssignmentSubmission sub : submissions) { //if submitted if (sub.getSubmitted()) { log.debug("Submission " + sub.getId()); boolean allowAnyFile = asn.getContent().isAllowAnyFile(); List<ContentResource> resources = getAllAcceptableAttachments(sub, allowAnyFile); // determine the owner of the submission for purposes of content review String ownerId = asn.isGroup() ? sub.getSubmittedForGroupByUserId() : sub.getSubmitterId(); if (ownerId.isEmpty()) { String msg = "Unable to submit content items to review service for submission %s to assignment %s. " + "An appropriate owner for the submission cannot be determined."; log.warn(String.format(msg, sub.getId(), asn.getId())); continue; } for (ContentResource resource : resources) { //if it wasnt added if (getFirstItemByContentId(resource.getId()) == null) { log.debug("was not added"); queueContent(ownerId, null, asn.getReference(), resource.getId(), sub.getId(), false); } //else - is there anything or any status we should check? } } } } } catch (Exception e) { log.warn("Error while tying to queue previous submissions."); } return; } ////////////////////////////// OLD API INTEGRATION /////////////////////////////// //get the assignment reference String taskTitle = ""; if (extraAsnnOpts.containsKey("title")) { taskTitle = extraAsnnOpts.get("title").toString(); } else { getAssignmentTitle(taskId); } log.debug("Creating assignment for site: " + siteId + ", task: " + taskId + " tasktitle: " + taskTitle); SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); dform.applyPattern(TURNITIN_DATETIME_FORMAT); Calendar cal = Calendar.getInstance(); //set this to yesterday so we avoid timezone problems etc //TII-143 seems this now causes problems may need a finner tweak than 1 day like midnight +1 min or something cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 1); //cal.add(Calendar.DAY_OF_MONTH, -1); String dtstart = dform.format(cal.getTime()); String today = dtstart; //set the due dates for the assignments to be in 5 month's time //turnitin automatically sets each class end date to 6 months after it is created //the assignment end date must be on or before the class end date String fcmd = "2"; //new assignment boolean asnnExists = false; // If this assignment already exists, we should use fcmd 3 to update it. Map tiiresult = this.getAssignment(siteId, taskId); if (tiiresult.get("rcode") != null && tiiresult.get("rcode").equals("85")) { fcmd = "3"; asnnExists = true; } /* Some notes about start and due dates. This information is * accurate as of Nov 12, 2009 and was determined by testing * and experimentation with some Sash scripts. * * A turnitin due date, must be after the start date. This makes * sense and follows the logic in both Assignments 1 and 2. * * When *creating* a new Turnitin Assignment, the start date * must be todays date or later. The format for dates only * includes the day, and not any specific times. I believe that, * in order to make up for time zone differences between your * location and the turnitin cloud, it can be basically the * current day anywhere currently, with some slack. For instance * I can create an assignment for yesterday, but not for 2 days * ago. Doing so causes an error. * * However! For an existing turnitin assignment, you appear to * have the liberty of changing the start date to sometime in * the past. You can also change an assignment to have a due * date in the past as long as it is still after the start date. * * So, to avoid errors when syncing information, or adding * turnitin support to new or existing assignments we will: * * 1. If the assignment already exists we'll just save it. * * 2. If the assignment does not exist, we will save it once using * todays date for the start and due date, and then save it again with * the proper dates to ensure we're all tidied up and in line. * * Also, with our current class creation, due dates can be 5 * years out, but not further. This seems a bit lower priortity, * but we still should figure out an appropriate way to deal * with it if it does happen. * */ //TODO use the 'secret' function to change this to longer cal.add(Calendar.MONTH, 5); String dtdue = dform.format(cal.getTime()); log.debug("Set date due to: " + dtdue); if (extraAsnnOpts != null && extraAsnnOpts.containsKey("dtdue")) { dtdue = extraAsnnOpts.get("dtdue").toString(); log.debug("Settign date due from external to: " + dtdue); extraAsnnOpts.remove("dtdue"); } String fid = "4"; //function id String utp = "2"; //user type 2 = instructor String s_view_report = "1"; if (extraAsnnOpts != null && extraAsnnOpts.containsKey("s_view_report")) { s_view_report = extraAsnnOpts.get("s_view_report").toString(); extraAsnnOpts.remove("s_view_report"); } //erater String erater = (serverConfigurationService.getBoolean("turnitin.option.erater.default", false)) ? "1" : "0"; String ets_handbook = "1"; String ets_dictionary = "en"; String ets_spelling = "1"; String ets_style = "1"; String ets_grammar = "1"; String ets_mechanics = "1"; String ets_usage = "1"; try { if (extraAsnnOpts != null && extraAsnnOpts.containsKey("erater")) { erater = extraAsnnOpts.get("erater").toString(); extraAsnnOpts.remove("erater"); ets_handbook = extraAsnnOpts.get("ets_handbook").toString(); extraAsnnOpts.remove("ets_handbook"); ets_dictionary = extraAsnnOpts.get("ets_dictionary").toString(); extraAsnnOpts.remove("ets_dictionary"); ets_spelling = extraAsnnOpts.get("ets_spelling").toString(); extraAsnnOpts.remove("ets_spelling"); ets_style = extraAsnnOpts.get("ets_style").toString(); extraAsnnOpts.remove("ets_style"); ets_grammar = extraAsnnOpts.get("ets_grammar").toString(); extraAsnnOpts.remove("ets_grammar"); ets_mechanics = extraAsnnOpts.get("ets_mechanics").toString(); extraAsnnOpts.remove("ets_mechanics"); ets_usage = extraAsnnOpts.get("ets_usage").toString(); extraAsnnOpts.remove("ets_usage"); } } catch (Exception e) { log.info("(createAssignment)erater extraAsnnOpts. " + e); } String cid = siteId; String assignid = taskId; String ctl = siteId; Map params = TurnitinAPIUtil.packMap(turnitinConn.getBaseTIIOptions(), "assign", taskTitle, "assignid", assignid, "cid", cid, "ctl", ctl, "dtdue", dtdue, "dtstart", dtstart, "fcmd", "3", "fid", fid, "s_view_report", s_view_report, "utp", utp, "erater", erater, "ets_handbook", ets_handbook, "ets_dictionary", ets_dictionary, "ets_spelling", ets_spelling, "ets_style", ets_style, "ets_grammar", ets_grammar, "ets_mechanics", ets_mechanics, "ets_usage", ets_usage); // Save instructorInfo up here to reuse for calls in this // method, since theoretically getInstructorInfo could return // different instructors for different invocations and we need // the same one since we're using a session id. Map instructorInfo = getInstructorInfo(siteId); params.putAll(instructorInfo); if (extraAsnnOpts != null) { for (Object key : extraAsnnOpts.keySet()) { if (extraAsnnOpts.get(key) == null) { continue; } params = TurnitinAPIUtil.packMap(params, key.toString(), extraAsnnOpts.get(key).toString()); } } // We only need to use a session id if we are creating this // assignment for the first time. String sessionid = null; Map sessionParams = null; if (!asnnExists) { // Try adding the user in case they don't exist TII-XXX addTurnitinInstructor(instructorInfo); sessionParams = turnitinConn.getBaseTIIOptions(); sessionParams.putAll(instructorInfo); sessionParams.put("utp", utp); sessionid = TurnitinSessionFuncs.getTurnitinSession(turnitinConn, sessionParams); Map firstparams = new HashMap(); firstparams.putAll(params); firstparams.put("session-id", sessionid); firstparams.put("dtstart", today); // Make the due date in the future Calendar caldue = Calendar.getInstance(); caldue.add(Calendar.MONTH, 5); String dtdue_first = dform.format(caldue.getTime()); firstparams.put("dtdue", dtdue_first); log.debug("date due is: " + dtdue); log.debug("Start date: " + today); firstparams.put("fcmd", "2"); Document firstSaveDocument = turnitinConn.callTurnitinReturnDocument(firstparams); Element root = firstSaveDocument.getDocumentElement(); int rcode = new Integer(((CharacterData) (root.getElementsByTagName("rcode").item(0).getFirstChild())) .getData().trim()); if ((rcode > 0 && rcode < 100) || rcode == 419) { log.debug("Create FirstDate Assignment successful"); log.debug("tii returned " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())) .getData().trim() + ". Code: " + rcode); } else { log.debug("FirstDate Assignment creation failed with message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())) .getData().trim() + ". Code: " + rcode); //log.debug(root); throw new TransientSubmissionException("FirstDate Create Assignment not successful. Message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())) .getData().trim() + ". Code: " + rcode, rcode); } } log.debug("going to attempt second update"); if (sessionid != null) { params.put("session-id", sessionid); } Document document = turnitinConn.callTurnitinReturnDocument(params); Element root = document.getDocumentElement(); int rcode = new Integer( ((CharacterData) (root.getElementsByTagName("rcode").item(0).getFirstChild())).getData().trim()); if ((rcode > 0 && rcode < 100) || rcode == 419) { log.debug("Create Assignment successful"); log.debug("tii returned " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData() .trim() + ". Code: " + rcode); } else { log.debug("Assignment creation failed with message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData() .trim() + ". Code: " + rcode); //log.debug(root); throw new TransientSubmissionException("Create Assignment not successful. Message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData() .trim() + ". Code: " + rcode, rcode); } if (sessionid != null) { TurnitinSessionFuncs.logoutTurnitinSession(turnitinConn, sessionid, sessionParams); } }
From source file:org.cgiar.ccafs.marlo.action.summaries.ReportingSummaryAction.java
private TypedTableModel getMasterTableModel(List<CrpProgram> flagships, List<CrpProgram> regions, ProjectPartner projectLeader) {// ww w. java 2s . c o m // Initialization of Model TypedTableModel model = new TypedTableModel( new String[] { "title", "center", "current_date", "project_submission", "cycle", "isNew", "isAdministrative", "type", "isGlobal", "isPhaseOne", "budget_gender", "hasTargetUnit", "hasW1W2Co", "hasActivities", "phaseID" }, new Class[] { String.class, String.class, String.class, String.class, String.class, Boolean.class, Boolean.class, String.class, Boolean.class, Boolean.class, Boolean.class, Boolean.class, Boolean.class, Boolean.class, Long.class }); // Filling title String title = ""; if (projectLeader != null) { if (projectLeader.getInstitution() != null && projectLeader.getInstitution().getAcronym() != "" && projectLeader.getInstitution().getAcronym() != null) { title += projectLeader.getInstitution().getAcronym() + "-"; } } if (projectInfo.getAdministrative() == false) { if (flagships != null) { if (!flagships.isEmpty()) { for (CrpProgram crpProgram : flagships) { title += crpProgram.getAcronym() + "-"; } } } if (projectInfo.getNoRegional() != null && projectInfo.getNoRegional()) { title += "Global" + "-"; } else { if (regions != null && !regions.isEmpty()) { for (CrpProgram crpProgram : regions) { title += crpProgram.getAcronym() + "-"; } } } } title += "P" + Long.toString(projectID); // Get datetime ZonedDateTime timezone = ZonedDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm "); String zone = timezone.getOffset() + ""; if (zone.equals("Z")) { zone = "+0"; } String currentDate = timezone.format(format) + "(GMT" + zone + ")"; // Filling submission List<Submission> submissions = new ArrayList<>(); for (Submission submission : project .getSubmissions().stream().filter(c -> c.getCycle().equals(this.getSelectedCycle()) && c.getYear() == this.getSelectedYear() && c.getUnSubmitUser() == null) .collect(Collectors.toList())) { submissions.add(submission); } String submission = ""; if (!submissions.isEmpty()) { if (submissions.size() > 1) { LOG.error("More than one submission was found, the report will retrieve the first one"); } Submission fisrtSubmission = submissions.get(0); String submissionDate = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm") .format(fisrtSubmission.getDateTime()); submission = "Submitted on " + submissionDate + " (" + fisrtSubmission.getCycle() + " cycle " + fisrtSubmission.getYear() + ")"; } else { if (!this.getSelectedCycle().isEmpty() && this.getSelectedYear() != 0) { if (this.getSelectedCycle().equals("Reporting")) { submission = "Submission for " + this.getSelectedCycle() + " cycle " + this.getSelectedYear() + ": <not submited>"; } else { submission = "Submission for " + this.getSelectedCycle() + " cycle " + this.getSelectedYear() + ": <pending>"; } } else { submission = "Submission for " + "<Not Defined>" + " cycle " + "<Not Defined>" + " year" + ": <Not Defined>"; } } // TODO: Get image from repository String centerURL = ""; // set CRP imgage URL from repo // centerURL = this.getBaseUrl() + "/global/images/crps/" + project.getCrp().getAcronym() + ".png"; // Add center url to LOG // LOG.info("Center URL is: " + centerURL); // Get The Crp/Center/Platform where the project was created GlobalUnitProject globalUnitProject = project.getGlobalUnitProjects().stream() .filter(gu -> gu.isActive() && gu.isOrigin()).collect(Collectors.toList()).get(0); centerURL = globalUnitProject.getGlobalUnit().getAcronym(); Boolean isAdministrative = false; String type = "Research Project"; if (projectInfo.getAdministrative() != null) { if (projectInfo.getAdministrative() == true) { type = "Management Project"; } isAdministrative = projectInfo.getAdministrative(); } else { isAdministrative = false; } Boolean isNew = this.isProjectNew(projectID); Boolean hasGender = false; try { hasGender = this.hasSpecificities(APConstants.CRP_BUDGET_GENDER); } catch (Exception e) { LOG.warn("Failed to get " + APConstants.CRP_BUDGET_GENDER + " parameter. Parameter will be set as false. Exception: " + e.getMessage()); hasGender = false; } Boolean hasTargetUnit = false; if (targetUnitList.size() > 0) { hasTargetUnit = true; } Boolean hasActivities = false; try { hasActivities = this.hasSpecificities(APConstants.CRP_ACTIVITES_MODULE); } catch (Exception e) { LOG.warn("Failed to get " + APConstants.CRP_ACTIVITES_MODULE + " parameter. Parameter will be set as false. Exception: " + e.getMessage()); hasActivities = false; } Long phaseID = this.getSelectedPhase().getId(); model.addRow(new Object[] { title, centerURL, currentDate, submission, this.getSelectedCycle(), isNew, isAdministrative, type, projectInfo.getLocationGlobal(), this.isPhaseOne(), hasGender, hasTargetUnit, hasW1W2Co, hasActivities, phaseID }); return model; }