Example usage for java.util Date from

List of usage examples for java.util Date from

Introduction

In this page you can find the example usage for java.util Date from.

Prototype

public static Date from(Instant instant) 

Source Link

Document

Obtains an instance of Date from an Instant object.

Usage

From source file:org.sakaiproject.contentreview.turnitin.oc.ContentReviewServiceTurnitinOC.java

private void handleSubmissionStatus(JSONObject submissionJSON, ContentReviewItem item, Assignment assignment) {
    try {//from www.jav  a2  s.c o m

        Date assignmentDueDate = Date.from(assignment.getDueDate());
        String reportGenSpeed = assignment.getProperties().get("report_gen_speed");

        String submissionStatus = submissionJSON.getString("status");

        // Handle possible error status
        String errorStr = null;
        // Assume any errors are irrecoverable; flip to true for those we should try again
        boolean recoverable = false;

        switch (submissionStatus) {
        case "COMPLETE":
            // If submission status is complete, start similarity report process
            generateSimilarityReport(item.getExternalId(), item.getTaskId());
            // Update item status for loop 2
            item.setStatus(ContentReviewConstants.CONTENT_REVIEW_SUBMITTED_AWAITING_REPORT_CODE);
            // Reset retry count
            item.setRetryCount(new Long(0));
            Calendar cal = Calendar.getInstance();
            // Reset cal to current time
            cal.setTime(new Date());
            // Reset delay time
            cal.add(Calendar.MINUTE, getDelayTime(item.getRetryCount()));
            // Schedule next retry time
            item.setNextRetryTime(cal.getTime());
            crqs.update(item);
            // Check for items that generate reports both immediately and on due date
            // Create a placeholder item that will regenerate and index report after due date
            if (assignmentDueDate != null && assignmentDueDate.after(new Date())
                    && GENERATE_REPORTS_IMMEDIATELY_AND_ON_DUE_DATE.equals(reportGenSpeed)) {
                createPlaceholderItem(item, assignmentDueDate);
            }
            break;
        case "PROCESSING":
            // do nothing... try again
            break;
        case "CREATED":
            // do nothing... try again
            break;
        default:
            String errorCode = submissionJSON.containsKey("error_code") ? submissionJSON.getString("error_code")
                    : submissionStatus;
            switch (errorCode) {
            case "UNSUPPORTED_FILETYPE":
                errorStr = "The uploaded filetype is not supported";
                break;
            //break on all
            case "PROCESSING_ERROR":
                errorStr = "An unspecified error occurred while processing the submissions";
                break;
            case "TOO_LITTLE_TEXT":
                errorStr = "The submission does not have enough text to generate a Similarity Report (a submission must contain at least 20 words)";
                break;
            case "TOO_MUCH_TEXT":
                errorStr = "The submission has too much text to generate a Similarity Report (after extracted text is converted to UTF-8, the submission must contain less than 2MB of text)";
                break;
            case "TOO_MANY_PAGES":
                errorStr = "The submission has too many pages to generate a Similarity Report (a submission cannot contain more than 400 pages)";
                break;
            case "FILE_LOCKED":
                errorStr = "The uploaded file requires a password in order to be opened";
                break;
            case "CORRUPT_FILE":
                errorStr = "The uploaded file appears to be corrupt";
                break;
            case "ERROR":
                errorStr = "Submission returned with ERROR status";
                break;
            default:
                errorStr = errorCode;
                log.info("Unknown submission status, will retry: " + submissionStatus);
                recoverable = true;
                break;
            }
        }
        if (StringUtils.isNotEmpty(errorStr)) {
            item.setLastError(errorStr);
            Long errorStatus = recoverable ? ContentReviewConstants.CONTENT_REVIEW_SUBMISSION_ERROR_RETRY_CODE
                    : ContentReviewConstants.CONTENT_REVIEW_SUBMISSION_ERROR_NO_RETRY_CODE;
            item.setStatus(errorStatus);
            crqs.update(item);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.apache.james.jmap.methods.integration.SetMessagesMethodTest.java

@Test
public void movingAMessageIsNotSupported() throws Exception {
    String newMailboxName = "heartFolder";
    jmapServer.serverProbe().createMailbox("#private", username, newMailboxName);
    Mailbox heartFolder = jmapServer.serverProbe().getMailbox("#private", username, newMailboxName);
    String heartFolderId = heartFolder.getMailboxId().serialize();

    ZonedDateTime dateTime = ZonedDateTime.parse("2014-10-30T14:12:00Z");
    jmapServer.serverProbe().appendMessage(username, new MailboxPath("#private", username, "inbox"),
            new ByteArrayInputStream("Subject: my test subject\r\n\r\ntestmail".getBytes(Charsets.UTF_8)),
            Date.from(dateTime.toInstant()), false, new Flags());

    String messageToMoveId = "user|inbox|1";

    String requestBody = "[" + "  [" + "    \"setMessages\"," + "    {" + "      \"update\": { \""
            + messageToMoveId + "\" : {" + "        \"mailboxIds\": [\"" + heartFolderId + "\"]" + "      }}"
            + "    }," + "    \"#0\"" + "  ]" + "]";

    given().header("Authorization", this.accessToken.serialize()).body(requestBody).when().post("/jmap").then()
            .statusCode(200).body(NAME, equalTo("messagesSet")).body(NOT_UPDATED, hasKey(messageToMoveId))
            .body(NOT_UPDATED + "[\"" + messageToMoveId + "\"].type", equalTo("invalidProperties"))
            .body(NOT_UPDATED + "[\"" + messageToMoveId + "\"].properties[0]", equalTo("mailboxIds"))
            .body(NOT_UPDATED + "[\"" + messageToMoveId + "\"].description",
                    equalTo("mailboxIds: moving a message is not supported "
                            + "(through reference chain: org.apache.james.jmap.model.Builder[\"mailboxIds\"])"))
            .body(ARGUMENTS + ".updated", hasSize(0));
}

From source file:com.ikanow.aleph2.data_import_manager.analytics.actors.TestAnalyticsTriggerWorkerActor.java

/** Utility to make trigger checks pending
 *//*  w w w .j av a  2 s.c  om*/
protected void resetTriggerCheckTimes(final ICrudService<AnalyticTriggerStateBean> trigger_crud) {
    final UpdateComponent<AnalyticTriggerStateBean> update = CrudUtils.update(AnalyticTriggerStateBean.class)
            .set(AnalyticTriggerStateBean::next_check, Date.from(Instant.now().minusSeconds(2L)));

    trigger_crud
            .updateObjectsBySpec(CrudUtils.allOf(AnalyticTriggerStateBean.class), Optional.of(false), update)
            .join();
}

From source file:org.sleuthkit.autopsy.experimental.autoingest.FileExporterSettingsPanel.java

/**
 * Get the artifact condition from the user's input
 *
 * @return the ArtifactCondition, or null if there isn't one.
 *//* w w w . j  av  a  2s .c  o  m*/
ArtifactCondition getArtifactConditionFromInput(Rule rule) throws IllegalArgumentException {
    ArtifactCondition artifactCondition = null;
    if (cbAttributeType.isSelected()) {
        String selectedAttribute = comboBoxAttributeName.getSelectedItem().toString();
        BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE typeFromComboBox = BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE
                .fromLabel(comboBoxValueType.getSelectedItem().toString());
        BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE intrinsicType = attributeTypeMap
                .get(comboBoxAttributeName.getSelectedItem().toString());

        // if we don't have a type in the map, but they have set the combobox, put it in the map
        if (intrinsicType == null && typeFromComboBox != null) {
            intrinsicType = typeFromComboBox;
            attributeTypeMap.put(selectedAttribute, typeFromComboBox);
        }

        if (intrinsicType == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DATETIME) {
            LocalDateTime localDateTime = dateTimePicker.getDateTime();
            if (localDateTime == null) {
                throw new IllegalArgumentException("Bad date/time combination");
            }
            Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
            String stringValue = Long.toString(Date.from(instant).getTime());
            artifactCondition = new Rule.ArtifactCondition(comboBoxArtifactName.getSelectedItem().toString(),
                    comboBoxAttributeName.getSelectedItem().toString(), stringValue, intrinsicType,
                    RelationalOp.fromSymbol(comboBoxAttributeComparison.getSelectedItem().toString()));
        } else if (intrinsicType == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.BYTE) {
            try {
                String stringValue = tbAttributeValue.getText();
                byte[] hexValue = Hex.decodeHex(stringValue.toCharArray());
                String finalValue = new String(Hex.encodeHex(hexValue));
                artifactCondition = new Rule.ArtifactCondition(
                        comboBoxArtifactName.getSelectedItem().toString(),
                        comboBoxAttributeName.getSelectedItem().toString(), finalValue, intrinsicType,
                        RelationalOp.fromSymbol(comboBoxAttributeComparison.getSelectedItem().toString()));
            } catch (DecoderException ex) {
                throw new IllegalArgumentException(ex);
            }
        } else if (intrinsicType != null) {
            artifactCondition = new Rule.ArtifactCondition(comboBoxArtifactName.getSelectedItem().toString(),
                    comboBoxAttributeName.getSelectedItem().toString(), tbAttributeValue.getText(),
                    intrinsicType,
                    RelationalOp.fromSymbol(comboBoxAttributeComparison.getSelectedItem().toString()));
        } else {
            throw new IllegalArgumentException();
        }
    }
    return artifactCondition;
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

@Override
protected Response doResourceRequestImpl(final Page.Request pageRequest)
        throws WWWEEEPortal.Exception, WebApplicationException {
    final HttpClientContext proxyContext = doProxyRequest(pageRequest, Mode.RESOURCE);
    @SuppressWarnings("resource")
    final CloseableHttpClient proxyClient = Objects
            .requireNonNull((CloseableHttpClient) proxyContext.getAttribute(HTTP_CLIENT_CONTEXT_ID));

    final @NonNull HttpResponse proxyResponse = proxyContext.getResponse();

    try {//  w w w . ja  v  a 2 s  .  c  o m

        final Response.ResponseBuilder responseBuilder = Response.ok();

        responseBuilder.lastModified(getProxyResponseHeader(pageRequest, proxyResponse, "Last-Modified",
                (s) -> Date.from(ZonedDateTime.parse(s, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant())));
        final MimeType responseContentType = getProxyResponseHeader(pageRequest, proxyResponse, "Content-Type",
                IOUtil::newMimeType);
        responseBuilder.type((responseContentType != null) ? RESTUtil.getMediaType(responseContentType) : null);
        responseBuilder.cacheControl(mergeCacheControl(getCacheControlDefault().orElse(null),
                getProxyResponseHeader(pageRequest, proxyResponse, "Cache-Control", CacheControl::valueOf)));
        responseBuilder.expires(getProxyResponseHeader(pageRequest, proxyResponse, "Expires",
                (s) -> Date.from(ZonedDateTime.parse(s, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant())));
        responseBuilder.tag(getProxyResponseHeader(pageRequest, proxyResponse, "ETag", EntityTag::valueOf));
        responseBuilder.language(getProxyResponseHeader(pageRequest, proxyResponse, "Content-Language",
                (h) -> Locale.forLanguageTag(StringUtil.COMMA_SEPARATED_PATTERN.split("")[0]).toString()));

        final HttpEntity proxyResponseEntity = proxyResponse.getEntity();
        final Long contentLength = (proxyResponseEntity != null)
                ? Long.valueOf(proxyResponseEntity.getContentLength())
                : null;
        responseBuilder.header("Content-Length", contentLength);

        if (proxyResponseEntity != null) {
            responseBuilder.entity(HttpUtil.getDataSource(proxyResponseEntity, proxyClient));
        } else {
            try {
                proxyClient.close();
            } catch (IOException ioe) {
                throw new WWWEEEPortal.OperationalException(ioe);
            }
        }

        return responseBuilder.build();

    } catch (WWWEEEPortal.Exception wpe) {
        LogAnnotation.annotate(wpe, "ProxyContext", proxyContext, null, false);
        LogAnnotation.annotate(wpe, "ProxyResponse", proxyResponse, null, false);
        try {
            LogAnnotation.annotate(wpe, "ProxiedFileURL", HttpUtil.getRequestTargetURL(proxyContext), null,
                    false); // This wouldn't be necessary if any of the previous annotations could actually toString() themselves usefully.
        } catch (Exception e) {
        }
        throw wpe;
    }
}

From source file:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java

@Override
@Transactional//from  ww  w  .java  2s .  c  o  m
public Map<String, String> transferCopyEntities(String fromContext, String toContext, List<String> ids,
        List<String> transferOptions) {

    Map<String, String> transversalMap = new HashMap<>();
    Collection<Assignment> assignments = getAssignmentsForContext(fromContext);

    for (Assignment oAssignment : assignments) {
        String oAssignmentId = oAssignment.getId();
        String nAssignmentId = null;

        if (ids == null || ids.isEmpty() || ids.contains(oAssignmentId)) {
            try {
                Assignment nAssignment = addAssignment(toContext);
                nAssignmentId = nAssignment.getId();

                nAssignment.setTitle(oAssignment.getTitle());
                // replace all occurrence of old context with new context inside instruction text
                if (StringUtils.isNotBlank(oAssignment.getInstructions())) {
                    nAssignment
                            .setInstructions(oAssignment.getInstructions().replaceAll(fromContext, toContext));
                }
                nAssignment.setTypeOfGrade(oAssignment.getTypeOfGrade());
                nAssignment.setTypeOfSubmission(oAssignment.getTypeOfSubmission());

                // User supplied publish option takes precedence, then property, then source.
                if (transferOptions != null && transferOptions.contains(EntityTransferrer.PUBLISH_OPTION)) {
                    nAssignment.setDraft(false);
                } else if (serverConfigurationService.getBoolean("import.importAsDraft", true)) {
                    nAssignment.setDraft(true);
                } else {
                    nAssignment.setDraft(oAssignment.getDraft());
                }

                nAssignment.setCloseDate(oAssignment.getCloseDate());
                nAssignment.setDropDeadDate(oAssignment.getDropDeadDate());
                nAssignment.setDueDate(oAssignment.getDueDate());
                nAssignment.setOpenDate(oAssignment.getOpenDate());
                nAssignment.setHideDueDate(oAssignment.getHideDueDate());

                nAssignment.setPosition(oAssignment.getPosition());
                nAssignment.setAllowAttachments(oAssignment.getAllowAttachments());
                nAssignment.setHonorPledge(oAssignment.getHonorPledge());
                nAssignment.setIndividuallyGraded(oAssignment.getIndividuallyGraded());
                nAssignment.setMaxGradePoint(oAssignment.getMaxGradePoint());
                nAssignment.setScaleFactor(oAssignment.getScaleFactor());
                nAssignment.setReleaseGrades(oAssignment.getReleaseGrades());

                // group assignment
                if (oAssignment.getTypeOfAccess() == GROUP) {
                    nAssignment.setTypeOfAccess(GROUP);
                    Site oSite = siteService.getSite(oAssignment.getContext());
                    Site nSite = siteService.getSite(nAssignment.getContext());

                    boolean siteChanged = false;
                    Collection<Group> nGroups = nSite.getGroups();
                    for (String groupId : oAssignment.getGroups()) {
                        Group oGroup = oSite.getGroup(groupId);
                        Optional<Group> existingGroup = nGroups.stream()
                                .filter(g -> StringUtils.equals(g.getTitle(), oGroup.getTitle())).findAny();
                        Group nGroup;
                        if (existingGroup.isPresent()) {
                            // found a matching group
                            nGroup = existingGroup.get();
                        } else {
                            // create group
                            nGroup = nSite.addGroup();
                            nGroup.setTitle(oGroup.getTitle());
                            nGroup.setDescription(oGroup.getDescription());
                            nGroup.getProperties().addProperty("group_prop_wsetup_created",
                                    Boolean.TRUE.toString());
                            siteChanged = true;
                        }
                        nAssignment.getGroups().add(nGroup.getReference());
                    }
                    if (siteChanged)
                        siteService.save(nSite);
                    nAssignment.setIsGroup(oAssignment.getIsGroup());
                }

                // review service
                nAssignment.setContentReview(oAssignment.getContentReview());

                // attachments
                Set<String> oAttachments = oAssignment.getAttachments();
                List<Reference> nAttachments = entityManager.newReferenceList();
                for (String oAttachment : oAttachments) {
                    Reference oReference = entityManager.newReference(oAttachment);
                    String oAttachmentId = oReference.getId();
                    // transfer attachment, replace the context string if necessary and add new attachment
                    String nReference = transferAttachment(fromContext, toContext, oAttachmentId);
                    nAssignment.getAttachments().add(nReference);
                }

                // peer review
                nAssignment.setAllowPeerAssessment(oAssignment.getAllowPeerAssessment());
                nAssignment.setPeerAssessmentAnonEval(oAssignment.getPeerAssessmentAnonEval());
                nAssignment.setPeerAssessmentInstructions(oAssignment.getPeerAssessmentInstructions());
                nAssignment.setPeerAssessmentNumberReviews(oAssignment.getPeerAssessmentNumberReviews());
                nAssignment.setPeerAssessmentStudentReview(oAssignment.getPeerAssessmentStudentReview());
                nAssignment.setPeerAssessmentPeriodDate(oAssignment.getPeerAssessmentPeriodDate());
                if (nAssignment.getPeerAssessmentPeriodDate() == null && nAssignment.getCloseDate() != null) {
                    // set the peer period time to be 10 mins after accept until date
                    Instant tenMinutesAfterCloseDate = Instant
                            .from(nAssignment.getCloseDate().plus(Duration.ofMinutes(10)));
                    nAssignment.setPeerAssessmentPeriodDate(tenMinutesAfterCloseDate);
                }

                // properties
                Map<String, String> nProperties = nAssignment.getProperties();
                nProperties.putAll(oAssignment.getProperties());
                // remove the link btw assignment and announcement item. One can announce the open date afterwards
                nProperties.remove(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
                nProperties.remove(AssignmentConstants.NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED);
                nProperties.remove(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID);

                // remove the link btw assignment and calendar item. One can add the due date to calendar afterwards
                nProperties.remove(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
                nProperties.remove(AssignmentConstants.NEW_ASSIGNMENT_DUE_DATE_SCHEDULED);
                nProperties.remove(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);

                if (!nAssignment.getDraft()) {
                    Map<String, String> oProperties = oAssignment.getProperties();

                    String fromCalendarEventId = oProperties
                            .get(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);

                    if (fromCalendarEventId != null) {
                        String fromCalendarId = calendarService.calendarReference(oAssignment.getContext(),
                                SiteService.MAIN_CONTAINER);
                        Calendar fromCalendar = calendarService.getCalendar(fromCalendarId);
                        CalendarEvent fromEvent = fromCalendar.getEvent(fromCalendarEventId);
                        String toCalendarId = calendarService.calendarReference(nAssignment.getContext(),
                                SiteService.MAIN_CONTAINER);
                        Calendar toCalendar = null;
                        try {
                            toCalendar = calendarService.getCalendar(toCalendarId);
                        } catch (IdUnusedException iue) {
                            calendarService.commitCalendar(calendarService.addCalendar(toCalendarId));
                            toCalendar = calendarService.getCalendar(toCalendarId);
                        }

                        String fromDisplayName = fromEvent.getDisplayName();
                        CalendarEvent toCalendarEvent = toCalendar.addEvent(fromEvent.getRange(),
                                fromEvent.getDisplayName(), fromEvent.getDescription(), fromEvent.getType(),
                                fromEvent.getLocation(), fromEvent.getAccess(), fromEvent.getGroups(),
                                fromEvent.getAttachments());
                        nProperties.put(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID,
                                toCalendarEvent.getId());
                        nProperties.put(AssignmentConstants.NEW_ASSIGNMENT_DUE_DATE_SCHEDULED,
                                Boolean.TRUE.toString());
                        nProperties.put(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE,
                                Boolean.TRUE.toString());
                    }

                    String openDateAnnounced = StringUtils.trimToNull(
                            oProperties.get(AssignmentConstants.NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED));
                    String fromAnnouncementId = StringUtils.trimToNull(oProperties
                            .get(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID));
                    AnnouncementChannel fromChannel = getAnnouncementChannel(oAssignment.getContext());
                    if (fromChannel != null && fromAnnouncementId != null) {
                        AnnouncementMessage fromAnnouncement = fromChannel
                                .getAnnouncementMessage(fromAnnouncementId);
                        AnnouncementChannel toChannel = getAnnouncementChannel(nAssignment.getContext());
                        if (toChannel == null) {
                            // Create the announcement channel
                            String toChannelId = announcementService.channelReference(nAssignment.getContext(),
                                    siteService.MAIN_CONTAINER);
                            announcementService
                                    .commitChannel(announcementService.addAnnouncementChannel(toChannelId));
                            toChannel = getAnnouncementChannel(nAssignment.getContext());
                        }
                        AnnouncementMessage toAnnouncement = toChannel.addAnnouncementMessage(
                                fromAnnouncement.getAnnouncementHeader().getSubject(),
                                fromAnnouncement.getAnnouncementHeader().getDraft(),
                                fromAnnouncement.getAnnouncementHeader().getAttachments(),
                                fromAnnouncement.getBody());
                        nProperties.put(AssignmentConstants.NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED,
                                Boolean.TRUE.toString());
                        nProperties.put(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID,
                                toAnnouncement.getId());
                        nProperties.put(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE,
                                Boolean.TRUE.toString());
                    }
                }

                // gradebook-integration link
                String associatedGradebookAssignment = nProperties
                        .get(PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
                if (StringUtils.isBlank(associatedGradebookAssignment)) {
                    // if the association property is empty then set gradebook integration to not integrated
                    nProperties.put(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, GRADEBOOK_INTEGRATION_NO);
                } else {
                    // see if the old assignment's associated gradebook item is an internal gradebook entry or externally defined
                    boolean isExternalAssignmentDefined = gradebookExternalAssessmentService
                            .isExternalAssignmentDefined(oAssignment.getContext(),
                                    associatedGradebookAssignment);
                    if (isExternalAssignmentDefined) {
                        if (!nAssignment.getDraft()) {
                            String gbUid = nAssignment.getContext();
                            if (!gradebookFrameworkService.isGradebookDefined(gbUid)) {
                                gradebookFrameworkService.addGradebook(gbUid, gbUid);
                            }
                            // This assignment has been published, make sure the associated gb item is available
                            org.sakaiproject.service.gradebook.shared.Assignment gbAssignment = gradebookService
                                    .getAssignmentByNameOrId(nAssignment.getContext(),
                                            associatedGradebookAssignment);

                            if (gbAssignment == null) {
                                // The associated gb item hasn't been created here yet.
                                gbAssignment = gradebookService.getExternalAssignment(oAssignment.getContext(),
                                        associatedGradebookAssignment);

                                Optional<Long> categoryId = createCategoryForGbAssignmentIfNecessary(
                                        gbAssignment, oAssignment.getContext(), nAssignment.getContext());

                                String assignmentRef = AssignmentReferenceReckoner.reckoner()
                                        .assignment(nAssignment).reckon().getReference();

                                gradebookExternalAssessmentService.addExternalAssessment(
                                        nAssignment.getContext(), assignmentRef, null, nAssignment.getTitle(),
                                        nAssignment.getMaxGradePoint() / (double) nAssignment.getScaleFactor(),
                                        Date.from(nAssignment.getDueDate()), this.getToolTitle(), null, false,
                                        categoryId.isPresent() ? categoryId.get() : null);

                                nProperties.put(PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, assignmentRef);
                            }
                        } else {
                            // if this is an external defined (came from assignment)
                            // mark the link as "add to gradebook" for the new imported assignment, since the assignment is still of draft state
                            // later when user posts the assignment, the corresponding assignment will be created in gradebook.
                            nProperties.remove(PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
                            nProperties.put(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, GRADEBOOK_INTEGRATION_ADD);
                        }
                    } else {
                        // If this is an internal gradebook item then it should be associated with the assignment
                        try {
                            org.sakaiproject.service.gradebook.shared.Assignment gbAssignment = gradebookService
                                    .getAssignmentByNameOrId(nAssignment.getContext(),
                                            associatedGradebookAssignment);

                            if (gbAssignment == null) {
                                if (!nAssignment.getDraft()) {
                                    // The target gb item doesn't exist and we're in publish mode, so copy it over.
                                    gbAssignment = gradebookService.getAssignmentByNameOrId(
                                            oAssignment.getContext(), associatedGradebookAssignment);
                                    gbAssignment.setId(null);

                                    Optional<Long> categoryId = createCategoryForGbAssignmentIfNecessary(
                                            gbAssignment, oAssignment.getContext(), nAssignment.getContext());

                                    if (categoryId.isPresent()) {
                                        gbAssignment.setCategoryId(categoryId.get());
                                    }

                                    gradebookService.addAssignment(nAssignment.getContext(), gbAssignment);
                                    nProperties.put(PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT,
                                            gbAssignment.getName());
                                } else {
                                    nProperties.put(PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT,
                                            AssignmentReferenceReckoner.reckoner().assignment(nAssignment)
                                                    .reckon().getReference());
                                    nProperties.put(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, GRADEBOOK_INTEGRATION_ADD);
                                }
                            } else {
                                // migrate to gradebook assignment id (vs title)
                                associatedGradebookAssignment = gbAssignment.getId().toString();
                                nProperties.put(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK,
                                        GRADEBOOK_INTEGRATION_ASSOCIATE);
                                nProperties.put(PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT,
                                        associatedGradebookAssignment);
                            }
                        } catch (AssessmentNotFoundException anfe) {
                            log.info(
                                    "While importing assignment {} the associated gradebook item {} was missing, "
                                            + "switching assignment linkage to added by assignments",
                                    nAssignmentId, associatedGradebookAssignment);
                        }
                    }
                }

                updateAssignment(nAssignment);

                transversalMap.put("assignment/" + oAssignmentId, "assignment/" + nAssignmentId);
                log.info("Old assignment id: {} - new assignment id: {}", oAssignmentId, nAssignmentId);

                try {
                    if (taggingManager.isTaggable()) {
                        for (TaggingProvider provider : taggingManager.getProviders()) {
                            provider.transferCopyTags(assignmentActivityProducer.getActivity(oAssignment),
                                    assignmentActivityProducer.getActivity(nAssignment));
                        }
                    }
                } catch (PermissionException pe) {
                    log.error("{} oAssignmentId={} nAssignmentId={}", pe.toString(), oAssignmentId,
                            nAssignmentId);
                }

                // Import supplementary items if they are present in the assignment to be imported
                // Model Answer
                AssignmentModelAnswerItem oModelAnswerItem = assignmentSupplementItemService
                        .getModelAnswer(oAssignmentId);
                if (oModelAnswerItem != null) {
                    AssignmentModelAnswerItem nModelAnswerItem = assignmentSupplementItemService
                            .newModelAnswer();
                    assignmentSupplementItemService.saveModelAnswer(nModelAnswerItem);
                    nModelAnswerItem.setAssignmentId(nAssignmentId);
                    nModelAnswerItem.setText(oModelAnswerItem.getText());
                    nModelAnswerItem.setShowTo(oModelAnswerItem.getShowTo());
                    Set<AssignmentSupplementItemAttachment> oModelAnswerItemAttachments = oModelAnswerItem
                            .getAttachmentSet();
                    Set<AssignmentSupplementItemAttachment> nModelAnswerItemAttachments = new HashSet<>();
                    for (AssignmentSupplementItemAttachment oAttachment : oModelAnswerItemAttachments) {
                        AssignmentSupplementItemAttachment nAttachment = assignmentSupplementItemService
                                .newAttachment();
                        // New attachment creation
                        String nAttachmentId = transferAttachment(fromContext, toContext,
                                removeReferencePrefix(oAttachment.getAttachmentId()));
                        if (StringUtils.isNotEmpty(nAttachmentId)) {
                            nAttachment.setAssignmentSupplementItemWithAttachment(nModelAnswerItem);
                            nAttachment.setAttachmentId(nAttachmentId);
                            assignmentSupplementItemService.saveAttachment(nAttachment);
                            nModelAnswerItemAttachments.add(nAttachment);
                        }
                    }
                    nModelAnswerItem.setAttachmentSet(nModelAnswerItemAttachments);
                    assignmentSupplementItemService.saveModelAnswer(nModelAnswerItem);
                }

                // Private Note
                AssignmentNoteItem oNoteItem = assignmentSupplementItemService.getNoteItem(oAssignmentId);
                if (oNoteItem != null) {
                    AssignmentNoteItem nNoteItem = assignmentSupplementItemService.newNoteItem();
                    //assignmentSupplementItemService.saveNoteItem(nNoteItem);
                    nNoteItem.setAssignmentId(nAssignment.getId());
                    nNoteItem.setNote(oNoteItem.getNote());
                    nNoteItem.setShareWith(oNoteItem.getShareWith());
                    nNoteItem.setCreatorId(userDirectoryService.getCurrentUser().getId());
                    assignmentSupplementItemService.saveNoteItem(nNoteItem);
                }

                // All Purpose
                AssignmentAllPurposeItem oAllPurposeItem = assignmentSupplementItemService
                        .getAllPurposeItem(oAssignmentId);
                if (oAllPurposeItem != null) {
                    AssignmentAllPurposeItem nAllPurposeItem = assignmentSupplementItemService
                            .newAllPurposeItem();
                    assignmentSupplementItemService.saveAllPurposeItem(nAllPurposeItem);
                    nAllPurposeItem.setAssignmentId(nAssignment.getId());
                    nAllPurposeItem.setTitle(oAllPurposeItem.getTitle());
                    nAllPurposeItem.setText(oAllPurposeItem.getText());
                    nAllPurposeItem.setHide(oAllPurposeItem.getHide());
                    nAllPurposeItem.setReleaseDate(null);
                    nAllPurposeItem.setRetractDate(null);
                    Set<AssignmentSupplementItemAttachment> oAllPurposeItemAttachments = oAllPurposeItem
                            .getAttachmentSet();
                    Set<AssignmentSupplementItemAttachment> nAllPurposeItemAttachments = new HashSet<>();
                    for (AssignmentSupplementItemAttachment oAttachment : oAllPurposeItemAttachments) {
                        AssignmentSupplementItemAttachment nAttachment = assignmentSupplementItemService
                                .newAttachment();
                        // New attachment creation
                        String nAttachId = transferAttachment(fromContext, toContext,
                                removeReferencePrefix(oAttachment.getAttachmentId()));
                        if (StringUtils.isNotEmpty(nAttachId)) {
                            nAttachment.setAssignmentSupplementItemWithAttachment(nAllPurposeItem);
                            nAttachment.setAttachmentId(nAttachId);
                            assignmentSupplementItemService.saveAttachment(nAttachment);
                            nAllPurposeItemAttachments.add(nAttachment);
                        }
                    }
                    nAllPurposeItem.setAttachmentSet(nAllPurposeItemAttachments);
                    assignmentSupplementItemService.cleanAllPurposeItemAccess(nAllPurposeItem);
                    Set<AssignmentAllPurposeItemAccess> accessSet = new HashSet<>();
                    AssignmentAllPurposeItemAccess access = assignmentSupplementItemService
                            .newAllPurposeItemAccess();
                    access.setAccess(userDirectoryService.getCurrentUser().getId());
                    access.setAssignmentAllPurposeItem(nAllPurposeItem);
                    assignmentSupplementItemService.saveAllPurposeItemAccess(access);
                    accessSet.add(access);
                    nAllPurposeItem.setAccessSet(accessSet);
                    assignmentSupplementItemService.saveAllPurposeItem(nAllPurposeItem);
                }
            } catch (Exception e) {
                log.error("{} oAssignmentId={} nAssignmentId={}", e.toString(), oAssignmentId, nAssignmentId);
            }
        }
    }
    return transversalMap;
}