Example usage for java.time Instant ofEpochMilli

List of usage examples for java.time Instant ofEpochMilli

Introduction

In this page you can find the example usage for java.time Instant ofEpochMilli.

Prototype

public static Instant ofEpochMilli(long epochMilli) 

Source Link

Document

Obtains an instance of Instant using milliseconds from the epoch of 1970-01-01T00:00:00Z.

Usage

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

private static String processToDate(Date toValue, RodaConstants.DateGranularity granularity,
        boolean returnStartOnNull) {
    final String ret;
    StringBuilder sb = new StringBuilder();
    if (toValue != null) {
        sb.append(Instant.ofEpochMilli(toValue.getTime()).toString());
        switch (granularity) {
        case YEAR:
            sb.append("+1YEAR-1MILLISECOND");
            break;
        case MONTH:
            sb.append("+1MONTH-1MILLISECOND");
            break;
        case DAY:
            sb.append("+1DAY-1MILLISECOND");
            break;
        case HOUR:
            sb.append("+1HOUR-1MILLISECOND");
            break;
        case MINUTE:
            sb.append("+1MINUTE-1MILLISECOND");
            break;
        case SECOND:
            sb.append("+1SECOND-1MILLISECOND");
            break;
        default:/*w  w w  . jav  a2 s.com*/
            // do nothing
            break;
        }
        ret = sb.toString();
    } else {
        ret = returnStartOnNull ? "*" : null;
    }
    return ret;
}

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

private static <T extends Serializable> void generateRangeValue(StringBuilder ret, Class<T> valueClass,
        T value) {/* ww  w.j  a va2  s .  co  m*/
    if (value != null) {
        if (valueClass.equals(Date.class)) {
            String date = Instant.ofEpochMilli((Date.class.cast(value).getTime())).toString();
            LOGGER.trace("Appending date value \"{}\" to range", date);
            ret.append(date);
        } else if (valueClass.equals(Long.class)) {
            ret.append(Long.class.cast(value));
        } else if (valueClass.equals(String.class)) {
            ret.append(String.class.cast(value));
        } else {
            LOGGER.error("Cannot process range of the type {}", valueClass);
        }
    } else {
        ret.append("*");
    }
}

From source file:sx.blah.discord.api.internal.DiscordUtils.java

/**
 * Gets the timestamp portion of a Snowflake ID as a {@link Instant} using the system's default timezone.
 *
 * @param id The Snowflake ID.//w w w  . ja v a2s . c o  m
 * @return The timestamp portion of the ID.
 */
public static Instant getSnowflakeTimeFromID(long id) {
    return Instant.ofEpochMilli(DISCORD_EPOCH + (id >>> 22));
}

From source file:net.tourbook.photo.Photo.java

private void setupPhoto(final File photoImageFile, final IPath photoImagePath) {

    final String photoImageFilePathName = photoImageFile.getAbsolutePath();
    final long lastModified = photoImageFile.lastModified();

    imageFile = photoImageFile;/*from   w ww.j  a  v a  2  s  . c  o  m*/

    imageFileName = photoImageFile.getName();
    imageFilePathName = photoImageFilePathName;

    imagePathName = photoImagePath.removeLastSegments(1).toOSString();
    imageFileExt = photoImagePath.getFileExtension();

    imageFileSize = photoImageFile.length();
    _imageFileLastModified = LocalDateTime.ofInstant(//
            Instant.ofEpochMilli(lastModified),
            //            ZoneOffset.UTC
            ZoneId.systemDefault()
    //
    );

    // initially sort by file date until exif data are loaded
    imageExifTime = lastModified;

    _uniqueId = photoImageFilePathName;

    /*
     * initialize image keys and loading states
     */
    _imageKeyThumb = getImageKeyThumb(photoImageFilePathName);
    _imageKeyHQ = getImageKeyHQ(photoImageFilePathName);
    _imageKeyOriginal = Util.computeMD5(photoImageFilePathName + "_Original");//$NON-NLS-1$

    _isImageFileAvailable = photoImageFile.exists();

    if (_isImageFileAvailable) {

        _photoLoadingStateThumb = PhotoLoadingState.UNDEFINED;
        _photoLoadingStateHQ = PhotoLoadingState.UNDEFINED;
        _photoLoadingStateOriginal = PhotoLoadingState.UNDEFINED;

        _isLoadingError = false;

    } else {

        _photoLoadingStateThumb = PhotoLoadingState.IMAGE_IS_INVALID;
        _photoLoadingStateHQ = PhotoLoadingState.IMAGE_IS_INVALID;
        _photoLoadingStateOriginal = PhotoLoadingState.IMAGE_IS_INVALID;

        _isLoadingError = true;
    }
}

From source file:org.sakaiproject.contentreview.impl.turnitin.TurnitinReviewServiceImpl.java

/**
 * Syncs an assignment and handles individual student extensions
 *//*from 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.qcert.camp.translator.SemRule2CAMP.java

/**
 * Incomplete but evolving translation for object allocations involving temporal constructs
 * @param ast the object allocation (SemNewObject)
 * @return the translation/*  w w w.j  a  va 2  s. co  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.apache.solr.SolrTestCaseJ4.java

/** 
 * Returns a randomly generated Date in the appropriate Solr external (input) format 
 * @see #randomSkewedDate//w  w w . ja  v  a2 s.  c om
 */
public static String randomDate() {
    return Instant.ofEpochMilli(random().nextLong()).toString();
}

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

@Override
public boolean canSubmit(Assignment a, String userId) {
    if (a == null)
        return false;
    // submissions are never allowed to non-electronic assignments
    if (a.getTypeOfSubmission() == Assignment.SubmissionType.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) {
        return false;
    }//www. j ava2  s.  c  om

    // return false only if the user is not allowed to submit and not allowed to add to the assignment
    if (!allowAddSubmissionCheckGroups(a) && !allowAddAssignment(a.getContext()))
        return false;

    //If userId is not defined look it up
    if (userId == null) {
        userId = sessionManager.getCurrentSessionUserId();
    }

    try {
        // if user the user can access this assignment
        checkAssignmentAccessibleForUser(a, userId);

        // get user
        User u = userDirectoryService.getUser(userId);

        Instant currentTime = Instant.now();

        // return false if the assignment is draft or is not open yet
        Instant openTime = a.getOpenDate();
        if (a.getDraft() || openTime.isAfter(currentTime)) {
            return false;
        }

        // whether the current time is after the assignment close date inclusive
        boolean isBeforeAssignmentCloseDate = !currentTime.isAfter(a.getCloseDate());

        // get user's submission
        AssignmentSubmission submission = getSubmission(
                AssignmentReferenceReckoner.reckoner().assignment(a).reckon().getId(), u);

        if (submission != null) {
            // check for allow resubmission or not first
            // return true if resubmission is allowed and current time is before resubmission close time
            // get the resubmit settings from submission object first
            String allowResubmitNumString = submission.getProperties()
                    .get(AssignmentConstants.ALLOW_RESUBMIT_NUMBER);
            if (NumberUtils.isParsable(allowResubmitNumString) && submission.getSubmitted()
                    && submission.getDateSubmitted() != null) {
                String allowResubmitCloseTime = submission.getProperties()
                        .get(AssignmentConstants.ALLOW_RESUBMIT_CLOSETIME);
                try {
                    int allowResubmitNumber = Integer.parseInt(allowResubmitNumString);

                    Instant resubmitCloseTime;
                    if (NumberUtils.isParsable(allowResubmitCloseTime)) {
                        // see if a resubmission close time is set on submission level
                        resubmitCloseTime = Instant.ofEpochMilli(Long.parseLong(allowResubmitCloseTime));
                    } else {
                        // otherwise, use assignment close time as the resubmission close time
                        resubmitCloseTime = a.getCloseDate();
                    }
                    return (allowResubmitNumber > 0 || allowResubmitNumber == -1)
                            && !currentTime.isAfter(resubmitCloseTime);
                } catch (NumberFormatException e) {
                    log.warn("allowResubmitNumString = {}, allowResubmitCloseTime = {}", allowResubmitNumString,
                            allowResubmitCloseTime, e);
                }
            }

            if (isBeforeAssignmentCloseDate
                    && (submission.getDateSubmitted() == null || !submission.getSubmitted())) {
                // before the assignment close date
                // and if no date then a submission was never never submitted
                // or if there is a submitted date and its a not submitted then it is considered a draft
                return true;
            }
        } else {
            // there is no submission yet so only check if before assignment close date
            return isBeforeAssignmentCloseDate;
        }
    } catch (UserNotDefinedException e) {
        log.warn("The user {} could not be found while checking if they can submit to assignment {}, {}",
                userId, a.getId(), e.getMessage());
    } catch (PermissionException e) {
        log.warn("The user {} cannot submit to assignment {}, {}", userId, a.getId(), e.getMessage());
    }
    return false;
}

From source file:net.yacy.peers.Protocol.java

/**
 * put in all the essentials for routing and network authentication
 * @param sb//  w w w  .  j a  v a  2 s.  co m
 * @param targetHash
 * @param salt
 * @return
 */
public static final LinkedHashMap<String, ContentBody> basicRequestParts(final Switchboard sb,
        final String targetHash, final String salt) {
    final LinkedHashMap<String, ContentBody> parts = new LinkedHashMap<String, ContentBody>();

    // just standard identification essentials
    if (sb.peers.mySeed().hash != null) {
        parts.put("iam", UTF8.StringBody(sb.peers.mySeed().hash));
        if (targetHash != null)
            parts.put("youare", UTF8.StringBody(targetHash));

        // time information for synchronization
        final long myTime = System.currentTimeMillis();
        String formattedTime;
        try {
            /* Prefer using first the shared and thread-safe DateTimeFormatter instance */
            formattedTime = GenericFormatter.FORMAT_SHORT_SECOND.format(Instant.ofEpochMilli(myTime));
        } catch (final DateTimeException e) {
            /* This should not happen, but rather than failing we fallback to the old formatter wich uses synchronization locks */
            formattedTime = GenericFormatter.SHORT_SECOND_FORMATTER.format(new Date(myTime));
        }
        parts.put("mytime", UTF8.StringBody(formattedTime));
        parts.put("myUTC", UTF8.StringBody(Long.toString(myTime)));

        // network identification
        parts.put(SwitchboardConstants.NETWORK_NAME, UTF8.StringBody(Switchboard.getSwitchboard()
                .getConfig(SwitchboardConstants.NETWORK_NAME, Seed.DFLT_NETWORK_UNIT)));
    }
    parts.put("key", UTF8.StringBody(salt));

    // authentication essentials
    final String authenticationControl = sb.getConfig("network.unit.protocol.control", "uncontrolled");
    final String authenticationMethod = sb.getConfig("network.unit.protocol.request.authentication.method", "");
    if ((authenticationControl.equals("controlled")) && (authenticationMethod.length() > 0)) {
        if (authenticationMethod.equals("salted-magic-sim")) {
            // generate an authentication essential using the salt, the iam-hash and the network magic
            final String magic = sb.getConfig("network.unit.protocol.request.authentication.essentials", "");
            final String md5 = Digest.encodeMD5Hex(salt + sb.peers.mySeed().hash + magic);
            parts.put("magicmd5", UTF8.StringBody(md5));
        }
    }
    return parts;
}