List of usage examples for java.time ZoneOffset UTC
ZoneOffset UTC
To view the source code for java.time ZoneOffset UTC.
Click Source Link
From source file:org.apache.drill.test.TestBuilder.java
/** * Helper method for the timestamp values that depend on the local timezone * @param value expected timestamp value in UTC * @return LocalDateTime value for the local timezone *///from w w w . ja v a 2s . co m public static LocalDateTime convertToLocalDateTime(String value) { OffsetDateTime utcDateTime = LocalDateTime.parse(value, DateUtility.getDateTimeFormatter()) .atOffset(ZoneOffset.UTC); return utcDateTime.atZoneSameInstant(ZoneOffset.systemDefault()).toLocalDateTime(); }
From source file:org.wso2.carbon.apimgt.core.impl.APIPublisherImpl.java
/** * Updates design and implementation of an existing API. This method must not be used to change API status. * Implementations should throw an exceptions when such attempts are made. All life cycle state changes * should be carried out using the changeAPIStatus method of this interface. * * @param apiBuilder {@code org.wso2.carbon.apimgt.core.models.API.APIBuilder} model object * @throws APIManagementException if failed to update API *///w w w . java 2 s . c om @Override public void updateAPI(API.APIBuilder apiBuilder) throws APIManagementException { APIGateway gateway = getApiGateway(); apiBuilder.provider(getUsername()); apiBuilder.updatedBy(getUsername()); try { API originalAPI = getAPIbyUUID(apiBuilder.getId()); if (originalAPI != null) { //Checks whether the logged in user has the "UPDATE" permission for the API verifyUserPermissionsToUpdateAPI(getUsername(), originalAPI); apiBuilder.createdTime(originalAPI.getCreatedTime()); //workflow status is an internal property and shouldn't be allowed to update externally apiBuilder.workflowStatus(originalAPI.getWorkflowStatus()); if ((originalAPI.getName().equals(apiBuilder.getName())) && (originalAPI.getVersion().equals(apiBuilder.getVersion())) && (originalAPI.getProvider().equals(apiBuilder.getProvider())) && originalAPI.getLifeCycleStatus().equalsIgnoreCase(apiBuilder.getLifeCycleStatus())) { if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) { apiBuilder.apiPermission(replaceGroupNamesWithId(apiBuilder.getApiPermission())); Map<String, Integer> roleNamePermissionList; roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission()); apiBuilder.permissionMap(roleNamePermissionList); } Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint(); validateEndpoints(apiEndpointMap, true); createUriTemplateList(apiBuilder, true); validateApiPolicy(apiBuilder.getApiPolicy()); validateSubscriptionPolicies(apiBuilder); String updatedSwagger = apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder); String gatewayConfig = getApiGatewayConfig(apiBuilder.getId()); GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator(); APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName()); gatewaySourceGenerator.setApiConfigContext(apiConfigContext); String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(gatewayConfig, updatedSwagger); API api = apiBuilder.build(); //Add API to gateway gateway.updateAPI(api); if (log.isDebugEnabled()) { log.debug("API : " + apiBuilder.getName() + " has been successfully updated in gateway"); } if (originalAPI.getContext() != null && !originalAPI.getContext().equals(apiBuilder.getContext())) { if (!checkIfAPIContextExists(api.getContext())) { //if the API has public visibility, update the API without any role checking if (API.Visibility.PUBLIC == api.getVisibility()) { getApiDAO().updateAPI(api.getId(), api); } else if (API.Visibility.RESTRICTED == api.getVisibility()) { //get all the roles in the system Set<String> availableRoles = APIUtils.getAllAvailableRoles(); //get the roles needed to be associated with the API Set<String> apiRoleList = api.getVisibleRoles(); //if the API has role based visibility, update the API with role checking if (APIUtils.checkAllowedRoles(availableRoles, apiRoleList)) { getApiDAO().updateAPI(api.getId(), api); } } getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy()); getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy()); } else { throw new APIManagementException("Context already Exist", ExceptionCodes.API_ALREADY_EXISTS); } } else { //if the API has public visibility, update the API without any role checking if (API.Visibility.PUBLIC == api.getVisibility()) { getApiDAO().updateAPI(api.getId(), api); } else if (API.Visibility.RESTRICTED == api.getVisibility()) { //get all the roles in the system Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles(); //get the roles needed to be associated with the API Set<String> apiRoleList = api.getVisibleRoles(); //if the API has role based visibility, update the API with role checking if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) { getApiDAO().updateAPI(api.getId(), api); } } getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy()); getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy()); } if (log.isDebugEnabled()) { log.debug("API " + api.getName() + "-" + api.getVersion() + " was updated successfully."); // 'API_M Functions' related code //Create a payload with event specific details Map<String, String> eventPayload = new HashMap<>(); eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, api.getId()); eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, api.getName()); eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, api.getVersion()); eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, api.getDescription()); eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, api.getContext()); eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, api.getLifeCycleStatus()); // This will notify all the EventObservers(Asynchronous) ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_UPDATE, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this); ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier); } } else { APIUtils.verifyValidityOfApiUpdate(apiBuilder, originalAPI); } } else { log.error("Couldn't found API with ID " + apiBuilder.getId()); throw new APIManagementException("Couldn't found API with ID " + apiBuilder.getId(), ExceptionCodes.API_NOT_FOUND); } } catch (APIMgtDAOException e) { String errorMsg = "Error occurred while updating the API - " + apiBuilder.getName(); log.error(errorMsg, e); throw new APIManagementException(errorMsg, e, e.getErrorHandler()); } catch (ParseException e) { String errorMsg = "Error occurred while parsing the permission json from swagger - " + apiBuilder.getName(); log.error(errorMsg, e); throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION); } catch (GatewayException e) { String message = "Error occurred while updating API - " + apiBuilder.getName() + " in gateway"; log.error(message, e); throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION); } }
From source file:org.silverpeas.core.calendar.CalendarEventOccurrenceGenerationTest.java
private static OffsetDateTime dateTimeInUTC(int year, int month, int day, int hour, int minute) { return OffsetDateTime.of(year, month, day, hour, minute, 0, 0, ZoneOffset.UTC); }
From source file:org.silverpeas.core.calendar.CalendarEventOccurrenceGenerationTest.java
private Period in(Year year) { return Period.between(year.atDay(1).atStartOfDay().atOffset(ZoneOffset.UTC), year.atMonth(DECEMBER) .atEndOfMonth().plusDays(1).atStartOfDay().minusMinutes(1).atOffset(ZoneOffset.UTC)); }
From source file:org.silverpeas.core.calendar.CalendarEventOccurrenceGenerationTest.java
private Period in(YearMonth yearMonth) { return Period.between(yearMonth.atDay(1).atStartOfDay().atOffset(ZoneOffset.UTC), yearMonth.atEndOfMonth().plusDays(1).atStartOfDay().minusMinutes(1).atOffset(ZoneOffset.UTC)); }
From source file:org.sakaiproject.contentreview.impl.turnitin.TurnitinReviewServiceImpl.java
/** * Syncs an assignment and handles individual student extensions *//* w w w. j ava 2s . c o 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.wso2.carbon.apimgt.core.impl.APIPublisherImpl.java
/** * Delete an API/* www .j av a 2 s.co m*/ * * @param identifier UUID of the API. * @throws APIManagementException if failed to remove the API */ @Override public void deleteAPI(String identifier) throws APIManagementException { APIGateway gateway = getApiGateway(); try { if (getAPISubscriptionCountByAPI(identifier) == 0) { API api = getAPIbyUUID(identifier); if (api != null) { //Checks whether the user has required permissions to delete the API verifyUserPermissionsToDeleteAPI(getUsername(), api); String apiWfStatus = api.getWorkflowStatus(); API.APIBuilder apiBuilder = new API.APIBuilder(api); //Delete API in gateway gateway.deleteAPI(api); if (log.isDebugEnabled()) { log.debug("API : " + api.getName() + " has been successfully removed from the gateway"); } getApiDAO().deleteAPI(identifier); getApiLifecycleManager().removeLifecycle(apiBuilder.getLifecycleInstanceId()); APIUtils.logDebug("API with id " + identifier + " was deleted successfully.", log); if (APILCWorkflowStatus.PENDING.toString().equals(apiWfStatus)) { cleanupPendingTaskForAPIStateChange(identifier); } // 'API_M Functions' related code //Create a payload with event specific details Map<String, String> eventPayload = new HashMap<>(); eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, api.getId()); eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, api.getName()); eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, api.getVersion()); eventPayload.put(APIMgtConstants.FunctionsConstants.API_PROVIDER, api.getProvider()); eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, api.getDescription()); // This will notify all the EventObservers(Asynchronous) ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_DELETION, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this); ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier); } } else { throw new ApiDeleteFailureException("API with " + identifier + " already have subscriptions"); } } catch (APIMgtDAOException e) { String errorMsg = "Error occurred while deleting the API with id " + identifier; log.error(errorMsg, e); throw new APIManagementException(errorMsg, e, e.getErrorHandler()); } catch (LifecycleException e) { String errorMsg = "Error occurred while Disassociating the API with Lifecycle id " + identifier; log.error(errorMsg, e); throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION); } catch (GatewayException e) { String message = "Error occurred while deleting API with id - " + identifier + " from gateway"; log.error(message, e); throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION); } }
From source file:org.qcert.camp.translator.SemRule2CAMP.java
/** * Incomplete but evolving translation for object allocations involving temporal constructs * @param ast the object allocation (SemNewObject) * @return the translation/*from w w w .ja va 2s. c o m*/ */ private CampPattern translateTemporalAllocation(SemNewObject ast) { List<SemValue> args = ast.getArguments(); if (DATE_TYPE.equals(ast.getType().getDisplayName())) { Iterator<SemValue> argIter = args.iterator(); ZonedDateTime translation = ZonedDateTime.ofInstant(Instant.EPOCH, ZoneId.systemDefault()) .withYear(intFrom(argIter.next())).withMonth(intFrom(argIter.next())) .withDayOfMonth(intFrom(argIter.next())); if (argIter.hasNext()) translation = translation.withHour(intFrom(argIter.next())); if (argIter.hasNext()) translation = translation.withMinute(intFrom(argIter.next())); if (argIter.hasNext()) translation = translation.withSecond(intFrom(argIter.next())); ConstPattern constant = new ConstPattern(translation.toString()); return new UnaryPattern(UnaryOperator.ATimeFromString, constant); } if (TIME_TYPE.equals(ast.getType().getDisplayName()) && args.size() == 1) { long epochMilli = longFrom(args.get(0)); LocalTime translation = ZonedDateTime.ofInstant(Instant.ofEpochMilli(epochMilli), ZoneOffset.UTC) .toLocalTime(); // TODO this should really be a unique CAMP type corresponding to the TTRL type for LocalTimeComponentValue return new ConstPattern(translation.toString()); } return notImplemented("Translation of temporal allocation: " + ast); }
From source file:org.wso2.carbon.apimgt.core.impl.APIPublisherImplTestCase.java
@Test(description = "Event Observers for event listening") public void testObserverEventListener() throws APIManagementException { EventLogger observer = Mockito.mock(EventLogger.class); APIPublisherImpl apiPub = getApiPublisherImpl(); apiPub.registerObserver(observer);/* w w w .java 2 s . co m*/ Event event = Event.APP_CREATION; String username = USER; Map<String, String> metaData = new HashMap<>(); ZonedDateTime eventTime = ZonedDateTime.now(ZoneOffset.UTC); apiPub.notifyObservers(event, username, eventTime, metaData); Mockito.verify(observer, Mockito.times(1)).captureEvent(event, username, eventTime, metaData); }