Example usage for java.time Instant toEpochMilli

List of usage examples for java.time Instant toEpochMilli

Introduction

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

Prototype

public long toEpochMilli() 

Source Link

Document

Converts this instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z.

Usage

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

@Override
@Transactional//w w w. j  a va  2  s.c  om
public void updateSubmission(AssignmentSubmission submission) throws PermissionException {
    Assert.notNull(submission, "Submission cannot be null");
    Assert.notNull(submission.getId(), "Submission doesn't appear to have been persisted yet");

    String reference = AssignmentReferenceReckoner.reckoner().submission(submission).reckon().getReference();
    if (!allowUpdateSubmission(reference)) {
        throw new PermissionException(sessionManager.getCurrentSessionUserId(),
                SECURE_UPDATE_ASSIGNMENT_SUBMISSION, null);
    }
    eventTrackingService.post(eventTrackingService
            .newEvent(AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_SUBMISSION, reference, true));

    assignmentRepository.updateSubmission(submission);

    // Assignment Submission Notifications
    Instant dateReturned = submission.getDateReturned();
    Instant dateSubmitted = submission.getDateSubmitted();
    if (!submission.getSubmitted()) {
        // if the submission is not submitted then saving a submission event
        eventTrackingService.post(eventTrackingService
                .newEvent(AssignmentConstants.EVENT_SAVE_ASSIGNMENT_SUBMISSION, reference, true));
    } else if (dateReturned == null && !submission.getReturned() && (dateSubmitted == null
            || submission.getDateModified().toEpochMilli() - dateSubmitted.toEpochMilli() > 1000 * 60)) {
        // make sure the last modified time is at least one minute after the submit time
        if (!(StringUtils.trimToNull(submission.getSubmittedText()) == null
                && submission.getAttachments().isEmpty()
                && StringUtils.trimToNull(submission.getGrade()) == null
                && StringUtils.trimToNull(submission.getFeedbackText()) == null
                && StringUtils.trimToNull(submission.getFeedbackComment()) == null
                && submission.getFeedbackAttachments().isEmpty())) {
            if (submission.getGraded()) {
                //TODO: This should use an LRS_Group when that exists rather than firing off individual events for each LRS_Actor KNL-1560
                for (AssignmentSubmissionSubmitter submitter : submission.getSubmitters()) {
                    try {
                        User user = userDirectoryService.getUser(submitter.getSubmitter());
                        LRS_Statement statement = getStatementForAssignmentGraded(reference,
                                submission.getAssignment(), submission, user);
                        // graded and saved before releasing it
                        Event event = eventTrackingService.newEvent(
                                AssignmentConstants.EVENT_GRADE_ASSIGNMENT_SUBMISSION, reference, null, true,
                                NotificationService.NOTI_OPTIONAL, statement);
                        eventTrackingService.post(event);
                    } catch (UserNotDefinedException e) {
                        log.warn("Assignments could not find user ({}) while registering Event for LRSS",
                                submitter.getSubmitter());
                    }
                }
            }
        }
    } else if (dateReturned != null && submission.getGraded() && (dateSubmitted == null
            || dateReturned.isAfter(dateSubmitted)
            || dateSubmitted.isAfter(dateReturned) && submission.getDateModified().isAfter(dateSubmitted))) {
        if (submission.getGraded()) {
            //TODO: This should use an LRS_Group when that exists rather than firing off individual events for each LRS_Actor KNL-1560
            for (AssignmentSubmissionSubmitter submitter : submission.getSubmitters()) {
                try {
                    User user = userDirectoryService.getUser(submitter.getSubmitter());
                    LRS_Statement statement = getStatementForAssignmentGraded(reference,
                            submission.getAssignment(), submission, user);
                    // releasing a submitted assignment or releasing grade to an unsubmitted assignment
                    Event event = eventTrackingService.newEvent(
                            AssignmentConstants.EVENT_GRADE_ASSIGNMENT_SUBMISSION, reference, null, true,
                            NotificationService.NOTI_OPTIONAL, statement);
                    eventTrackingService.post(event);
                } catch (UserNotDefinedException e) {
                    log.warn("Assignments could not find user ({}) while registering Event for LRSS",
                            submitter.getSubmitter());
                }
            }
        }

        // if this is releasing grade, depending on the release grade notification setting, send email notification to student
        sendGradeReleaseNotification(submission);
    } else if (dateSubmitted == null) {
        //TODO: This should use an LRS_Group when that exists rather than firing off individual events for each LRS_Actor KNL-1560
        for (AssignmentSubmissionSubmitter submitter : submission.getSubmitters()) {
            try {
                User user = userDirectoryService.getUser(submitter.getSubmitter());
                LRS_Statement statement = getStatementForUnsubmittedAssignmentGraded(reference,
                        submission.getAssignment(), submission, user);
                // releasing a submitted assignment or releasing grade to an unsubmitted assignment
                Event event = eventTrackingService.newEvent(
                        AssignmentConstants.EVENT_GRADE_ASSIGNMENT_SUBMISSION, reference, null, true,
                        NotificationService.NOTI_OPTIONAL, statement);
                eventTrackingService.post(event);
            } catch (UserNotDefinedException e) {
                log.warn("Assignments could not find user ({}) while registering Event for LRSS",
                        submitter.getSubmitter());
            }
        }
    } else {
        // submitting a submission
        Assignment a = submission.getAssignment();
        LRS_Statement statement = getStatementForSubmitAssignment(a.getId(),
                serverConfigurationService.getAccessUrl(), a.getTitle());
        eventTrackingService
                .post(eventTrackingService.newEvent(AssignmentConstants.EVENT_SUBMIT_ASSIGNMENT_SUBMISSION,
                        reference, null, true, NotificationService.NOTI_OPTIONAL, statement));

        // only doing the notification for real online submissions
        if (submission.getAssignment()
                .getTypeOfSubmission() != Assignment.SubmissionType.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) {
            // instructor notification
            notificationToInstructors(submission, submission.getAssignment());

            // student notification, whether the student gets email notification once he submits an assignment
            notificationToStudent(submission);
        }
    }
}

From source file:org.tightblog.rendering.processors.PageProcessor.java

/**
 * Handle requests for weblog pages. GETs are for standard read-only retrieval of blog pages,
 * POSTs are for handling responses from the CommentProcessor, those will have a commentForm
 * attribute that translates to a WeblogEntryComment instance containing the comment.
 *//*from   ww  w  .j a  va  2s.  c  o m*/
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    WeblogPageRequest incomingRequest = WeblogPageRequest.Creator.create(request, pageModel);

    Weblog weblog = weblogRepository.findByHandleAndVisibleTrue(incomingRequest.getWeblogHandle());
    if (weblog == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } else {
        incomingRequest.setWeblog(weblog);
    }

    weblogPageCache.incrementIncomingRequests();

    // is this the site-wide weblog?
    incomingRequest
            .setSiteWide(themeManager.getSharedTheme(incomingRequest.getWeblog().getTheme()).isSiteWide());
    Instant lastModified = (incomingRequest.isSiteWide()) ? dp.getLastSitewideChange()
            : weblog.getLastModified();

    // Respond with 304 Not Modified if it is not modified.
    // DB stores last modified in millis, browser if-modified-since in seconds, so need to truncate millis from the former.
    long inDb = lastModified.truncatedTo(ChronoUnit.SECONDS).toEpochMilli();
    long inBrowser = getBrowserCacheExpireDate(request);

    if (inDb <= inBrowser) {
        weblogPageCache.incrementRequestsHandledBy304();
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // cache key to retrieve earlier generated content
    String cacheKey = null;

    // Check cache for content except during comment feedback/preview (i.e., commentForm present)
    WeblogEntryComment commentForm = (WeblogEntryComment) request.getAttribute("commentForm");

    // pages containing user-specific comment forms aren't cached
    CachedContent rendererOutput = null;
    boolean newContent = false;
    if (commentForm == null) {
        cacheKey = generateKey(incomingRequest);
        rendererOutput = weblogPageCache.get(cacheKey, lastModified);
    }

    try {
        if (rendererOutput == null) {
            newContent = true;

            // not using cache so need to generate page from scratch
            // figure out what template to use
            if (incomingRequest.getCustomPageName() != null) {
                Template template = themeManager.getWeblogTheme(weblog)
                        .getTemplateByName(incomingRequest.getCustomPageName());

                // block internal custom pages from appearing directly
                if (template != null && template.getRole().isAccessibleViaUrl()) {
                    incomingRequest.setTemplate(template);
                }
            } else {
                boolean invalid = false;

                if (incomingRequest.getWeblogEntryAnchor() != null) {
                    WeblogEntry entry = weblogEntryManager.getWeblogEntryByAnchor(weblog,
                            incomingRequest.getWeblogEntryAnchor());

                    if (entry == null || !entry.isPublished()) {
                        invalid = true;
                    } else {
                        incomingRequest.setWeblogEntry(entry);
                        incomingRequest.setTemplate(
                                themeManager.getWeblogTheme(weblog).getTemplateByRole(Role.PERMALINK));
                    }
                }

                // use default template for other contexts (or, for entries, if PERMALINK template is undefined)
                if (!invalid && incomingRequest.getTemplate() == null) {
                    incomingRequest
                            .setTemplate(themeManager.getWeblogTheme(weblog).getTemplateByRole(Role.WEBLOG));
                }
            }

            if (incomingRequest.getTemplate() == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // populate the rendering model
            Map<String, Object> initData = new HashMap<>();
            initData.put("parsedRequest", incomingRequest);

            // if we're handling comments, add the comment form
            if (commentForm != null) {
                incomingRequest.setCommentForm(commentForm);
            }

            Map<String, Object> model = getModelMap("pageModelSet", initData);
            model.put("model", incomingRequest);

            // Load special models for site-wide blog
            if (incomingRequest.isSiteWide()) {
                model.put("site", siteModelFactory.apply(incomingRequest));
            }

            // render content
            rendererOutput = thymeleafRenderer.render(incomingRequest.getTemplate(), model);
        }

        // write rendered content to response
        response.setContentType(rendererOutput.getRole().getContentType());
        response.setContentLength(rendererOutput.getContent().length);
        // no-cache: browser may cache but must validate with server each time before using (check for 304 response)
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Last-Modified", lastModified.toEpochMilli());
        response.getOutputStream().write(rendererOutput.getContent());

        if (rendererOutput.getRole().isIncrementsHitCount()) {
            weblogManager.incrementHitCount(weblog);
        }

        if (newContent && cacheKey != null) {
            log.debug("PUT {}", cacheKey);
            weblogPageCache.put(cacheKey, rendererOutput);
        }

    } catch (Exception e) {
        log.error("Error during rendering for {}", incomingRequest, e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.tightblog.service.indexer.IndexWeblogTask.java

public void doRun() {
    if (weblog == null && deleteOnly) {
        log.error("Weblog must be provided for delete task, skipping indexing");
        return;//from  w  w w.  j a v a  2 s .  c  o  m
    }

    Instant start = Instant.now();

    if (weblog == null) {
        log.info("Starting reindex of all weblogs...");
    }

    try (IndexWriter writer = beginWriting()) {
        if (writer != null) {

            // Delete all entries from given weblog(s)
            if (weblog != null) {
                Term tWebsite = getTerm(FieldConstants.WEBLOG_HANDLE, weblog.getHandle());

                if (tWebsite != null) {
                    writer.deleteDocuments(tWebsite);
                }
            } else {
                Term all = getTerm(FieldConstants.CONSTANT, FieldConstants.CONSTANT_V);
                writer.deleteDocuments(all);
            }

            if (!deleteOnly) {
                // Add entries from weblog(s)
                WeblogEntrySearchCriteria wesc = new WeblogEntrySearchCriteria();
                wesc.setWeblog(weblog);
                wesc.setStatus(PubStatus.PUBLISHED);
                List<WeblogEntry> entries = weblogEntryManager.getWeblogEntries(wesc);

                log.debug("Entries to index: {}", entries.size());

                for (WeblogEntry entry : entries) {
                    writer.addDocument(getDocument(entry));
                    log.debug("Indexed entry {0}: {1}", entry.getPubTime(), entry.getAnchor());
                }
            }
        }
    } catch (Exception e) {
        log.error("ERROR adding/deleting doc to index", e);
    }

    Instant end = Instant.now();
    double length = (end.toEpochMilli() - start.toEpochMilli()) / (double) DateUtils.MILLIS_PER_SECOND;

    if (weblog == null) {
        log.info("Indexed all weblogs in {} secs", length);
    } else {
        log.info("Indexed weblog '{}' in {} secs", weblog.getHandle(), length);
    }
}

From source file:org.trellisldp.http.impl.HttpUtils.java

/**
 * Build a hash value suitable for generating an ETag.
 * @param identifier the resource identifier
 * @param modified the last modified value
 * @param prefer a prefer header, may be null
 * @return a corresponding hash value/*from  w w w .  j  a  v  a2 s.  co m*/
 */
public static String buildEtagHash(final String identifier, final Instant modified, final Prefer prefer) {
    final String sep = ".";
    final String hash = nonNull(prefer) ? prefer.getInclude().hashCode() + sep + prefer.getOmit().hashCode()
            : "";
    return md5Hex(modified.toEpochMilli() + sep + modified.getNano() + sep + hash + sep + identifier);
}

From source file:org.trellisldp.triplestore.TriplestoreResourceServiceTest.java

private static boolean isReallyLaterThan(final Instant time) {
    final Instant t = now();
    return t.isAfter(time) && (t.toEpochMilli() > time.toEpochMilli() || t.getNano() > time.getNano());
}

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

/**
 * Gets a snowflake from a unix timestamp.
 * <p>//from  w w w . j av  a  2  s  .  c  o m
 * This snowflake only contains accurate information about the timestamp (not about other parts of the snowflake).
 * The returned snowflake is only one of many that could exist at the given timestamp.
 *
 * @param date The date that should be converted to a unix timestamp for use in the snowflake.
 * @return A snowflake with the given timestamp.
 */
public static long getSnowflakeFromTimestamp(Instant date) {
    return (date.toEpochMilli() - DISCORD_EPOCH) << 22;
}