Example usage for java.time.temporal ChronoUnit SECONDS

List of usage examples for java.time.temporal ChronoUnit SECONDS

Introduction

In this page you can find the example usage for java.time.temporal ChronoUnit SECONDS.

Prototype

ChronoUnit SECONDS

To view the source code for java.time.temporal ChronoUnit SECONDS.

Click Source Link

Document

Unit that represents the concept of a second.

Usage

From source file:org.janusgraph.diskstorage.configuration.CommonConfigTest.java

@Test
public void testDateParsing() {
    BaseConfiguration base = new BaseConfiguration();
    CommonsConfiguration config = new CommonsConfiguration(base);

    for (ChronoUnit unit : Arrays.asList(ChronoUnit.NANOS, ChronoUnit.MICROS, ChronoUnit.MILLIS,
            ChronoUnit.SECONDS, ChronoUnit.MINUTES, ChronoUnit.HOURS, ChronoUnit.DAYS)) {
        base.setProperty("test", "100 " + unit.toString());
        Duration d = config.get("test", Duration.class);
        assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(unit)), d.toNanos());
    }/*from   w w w  . j  a v a 2s . c  om*/

    Map<ChronoUnit, String> mapping = ImmutableMap.of(ChronoUnit.MICROS, "us", ChronoUnit.DAYS, "d");
    for (Map.Entry<ChronoUnit, String> entry : mapping.entrySet()) {
        base.setProperty("test", "100 " + entry.getValue());
        Duration d = config.get("test", Duration.class);
        assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(entry.getKey())), d.toNanos());
    }

}

From source file:org.jboss.pnc.coordinator.test.AbstractDependentBuildTest.java

protected void waitForEmptyBuildQueue() throws InterruptedException, TimeoutException {
    Wait.forCondition(() -> buildQueue.isEmpty(), 10, ChronoUnit.SECONDS,
            "Tired waiting for BuildQueue to be empty.");
}

From source file:org.sonar.core.issue.DefaultIssue.java

@CheckForNull
private static Date truncateToSeconds(@Nullable Date d) {
    if (d == null) {
        return null;
    }/*from  w  w  w. j a  v a  2s  .  c o m*/
    Instant instant = d.toInstant();
    instant = instant.truncatedTo(ChronoUnit.SECONDS);
    return Date.from(instant);
}

From source file:org.sonar.server.computation.task.projectanalysis.step.PeriodResolver.java

private static String formatDate(long date) {
    return DateUtils.formatDate(Date.from(new Date(date).toInstant().truncatedTo(ChronoUnit.SECONDS)));
}

From source file:org.sonar.server.issue.IssueFieldsSetter.java

private static Date truncateMillis(@Nullable Date d) {
    if (d == null) {
        return null;
    }/*from  w ww  .jav  a2  s .com*/
    return Date.from(d.toInstant().truncatedTo(ChronoUnit.SECONDS));
}

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

@RequestMapping(method = { RequestMethod.GET, RequestMethod.HEAD })
void getMediaFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    WeblogRequest incomingRequest = WeblogRequest.create(request);

    Weblog weblog = weblogRepository.findByHandleAndVisibleTrue(incomingRequest.getWeblogHandle());
    if (weblog == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/* w w w .j a  v  a  2s  .com*/
    } else {
        incomingRequest.setWeblog(weblog);
    }

    MediaFile mediaFile = null;
    // path info here is the resourceId
    String pathInfo = incomingRequest.getExtraPathInfo();
    if (StringUtils.isNotBlank(pathInfo)) {
        mediaFile = mediaManager.getMediaFileWithContent(pathInfo);
    }

    if (mediaFile == null) {
        log.info("Could not obtain media file for resource path: ", request.getRequestURL());
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    weblogMediaCache.incrementIncomingRequests();

    // DB stores last modified in millis, browser if-modified-since in seconds, so need to truncate millis from the former.
    long inDb = mediaFile.getLastUpdated().truncatedTo(ChronoUnit.SECONDS).toEpochMilli();
    long inBrowser = getBrowserCacheExpireDate(request);

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

    boolean useThumbnail = false;
    if (mediaFile.isImageFile() && "true".equals(request.getParameter("tn"))) {
        useThumbnail = true;
    }

    File desiredFile = useThumbnail ? mediaFile.getThumbnail() : mediaFile.getContent();
    if (desiredFile == null) {
        log.info("Could not obtain {} file content for resource path: ", useThumbnail ? "thumbnail" : "",
                request.getRequestURL());
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    try (InputStream resourceStream = new FileInputStream(desiredFile);
            OutputStream out = response.getOutputStream()) {

        byte[] buf = new byte[Utilities.EIGHT_KB_IN_BYTES];
        int length;
        while ((length = resourceStream.read(buf)) > 0) {
            out.write(buf, 0, length);
        }
        response.setContentType(useThumbnail ? MediaFile.THUMBNAIL_CONTENT_TYPE : mediaFile.getContentType());
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Last-Modified", mediaFile.getLastUpdated().toEpochMilli());
    } catch (IOException ex) {
        log.error("Error obtaining media file {}", desiredFile.getAbsolutePath(), ex);
        if (!response.isCommitted()) {
            response.reset();
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}

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  w w  w .jav a 2  s .  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.unitedinternet.cosmo.model.hibernate.HibPasswordRecovery.java

/**
 * //from   w w  w .  ja v  a  2 s .c  o  m
 */
public HibPasswordRecovery(User user, String key, long timeout) {
    this.user = user;
    this.key = key;
    this.timeout = timeout;
    this.created = Timestamp.from(Instant.now().truncatedTo(ChronoUnit.SECONDS));
}

From source file:password.pwm.util.java.JavaHelper.java

public static String toIsoDate(final Instant instant) {
    return instant == null ? "" : instant.truncatedTo(ChronoUnit.SECONDS).toString();
}