Example usage for java.time Instant truncatedTo

List of usage examples for java.time Instant truncatedTo

Introduction

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

Prototype

public Instant truncatedTo(TemporalUnit unit) 

Source Link

Document

Returns a copy of this Instant truncated to the specified unit.

Usage

From source file:Main.java

public static void main(String[] args) {
    Instant instant = Instant.parse("2014-12-03T10:15:30.00Z");
    instant = instant.truncatedTo(ChronoUnit.DAYS);
    System.out.println(instant);/*from   w ww  .j  a va2  s  . c  o  m*/

}

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

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

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  . j  a  v  a  2s. com*/
@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.trellisldp.file.FileMementoService.java

/**
 * Create a Memento from a resource at a particular time.
 * @param resource the resource//from  www .jav  a  2  s  .c  om
 * @param time the time to which the Memento corresponds
 * @return the completion stage representing that the operation has completed
 */
public CompletionStage<Void> put(final Resource resource, final Instant time) {
    return runAsync(() -> {
        final File resourceDir = FileUtils.getResourceDirectory(directory, resource.getIdentifier());
        if (!resourceDir.exists()) {
            resourceDir.mkdirs();
        }
        FileUtils.writeMemento(resourceDir, resource, time.truncatedTo(SECONDS));
    });
}

From source file:org.trellisldp.file.FileMementoService.java

@Override
public CompletionStage<Resource> get(final IRI identifier, final Instant time) {
    return supplyAsync(() -> {
        final Instant mementoTime = time.truncatedTo(SECONDS);
        final File resourceDir = FileUtils.getResourceDirectory(directory, identifier);
        final File file = FileUtils.getNquadsFile(resourceDir, mementoTime);
        if (file.exists()) {
            return new FileResource(identifier, file);
        }/*  w  w  w. ja v  a2  s . c om*/
        final SortedSet<Instant> possible = listMementos(identifier).headSet(mementoTime);
        if (possible.isEmpty()) {
            return MISSING_RESOURCE;
        }
        return new FileResource(identifier, FileUtils.getNquadsFile(resourceDir, possible.last()));
    });
}

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

/**
 * Check for a conditional operation./* w  w w .  j  a v a  2 s.  c  o m*/
 * @param method the HTTP method
 * @param ifModifiedSince the If-Modified-Since header
 * @param modified the resource modification date
 */
public static void checkIfModifiedSince(final String method, final String ifModifiedSince,
        final Instant modified) {
    if (isGetOrHead(method)) {
        parseDate(ifModifiedSince).filter(d -> d.isAfter(modified.truncatedTo(SECONDS))).ifPresent(date -> {
            throw new RedirectionException(notModified().build());
        });
    }
}

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

/**
 * Check for a conditional operation.//from  w  ww .j  a v a 2  s .  c  o  m
 * @param ifUnmodifiedSince the If-Unmodified-Since header
 * @param modified the resource modification date
 */
public static void checkIfUnmodifiedSince(final String ifUnmodifiedSince, final Instant modified) {
    parseDate(ifUnmodifiedSince).filter(modified.truncatedTo(SECONDS)::isAfter).ifPresent(date -> {
        throw new ClientErrorException(status(PRECONDITION_FAILED).build());
    });
}

From source file:org.trellisldp.rosid.file.RDFPatch.java

/**
 * Write RDF Patch statements to the specified file
 * @param file the file//from w w  w  .j  ava  2  s . com
 * @param delete the quads to delete
 * @param add the quads to add
 * @param time the time
 * @return true if the write succeeds; false otherwise
 */
public static Boolean write(final File file, final Stream<? extends Quad> delete,
        final Stream<? extends Quad> add, final Instant time) {
    try (final BufferedWriter writer = newBufferedWriter(file.toPath(), UTF_8, CREATE, APPEND)) {
        writer.write(BEGIN + time.truncatedTo(MILLIS) + lineSeparator());
        final Iterator<String> delIter = delete.map(quadToString).iterator();
        while (delIter.hasNext()) {
            writer.write("D " + delIter.next() + lineSeparator());
        }
        final Iterator<String> addIter = add.map(quadToString).iterator();
        while (addIter.hasNext()) {
            writer.write("A " + addIter.next() + lineSeparator());
        }
        writer.write(END + time.truncatedTo(MILLIS) + lineSeparator());
    } catch (final IOException ex) {
        LOGGER.error("Error writing data to resource {}: {}", file, ex.getMessage());
        return false;
    }
    return true;
}

From source file:org.trellisldp.rosid.file.RDFPatchTest.java

@Test
public void testPatchWriter() throws IOException {
    final File file = new File(resDir1, RESOURCE_JOURNAL);
    final Instant time = now();
    final List<Quad> delete = new ArrayList<>();
    final List<Quad> add = new ArrayList<>();
    final Quad title = rdf.createQuad(Trellis.PreferUserManaged, identifier, DC.title,
            rdf.createLiteral("Title"));
    add.add(title);/*from  w ww .j  a  v a2s. c  om*/
    add.add(rdf.createQuad(Trellis.PreferUserManaged, identifier, DC.description,
            rdf.createLiteral("A longer description")));
    RDFPatch.write(file, delete.stream(), add.stream(), time);
    final List<Quad> data1 = RDFPatch.asStream(rdf, file, identifier, time).collect(toList());
    assertEquals(add.size() + 1, data1.size());
    add.forEach(q -> assertTrue(data1.contains(q)));

    final Instant later = time.plusSeconds(10L);
    add.clear();
    delete.add(title);
    add.add(rdf.createQuad(Trellis.PreferUserManaged, identifier, DC.title, rdf.createLiteral("Other Title")));
    add.add(rdf.createQuad(Trellis.PreferUserManaged, identifier, RDFS.label, rdf.createLiteral("Label")));
    RDFPatch.write(file, delete.stream(), add.stream(), later);
    final List<Quad> data2 = RDFPatch.asStream(rdf, file, identifier, later).collect(toList());
    assertEquals(data2.size(), data1.size() - delete.size() + add.size());
    add.forEach(q -> assertTrue(data2.contains(q)));
    delete.forEach(q -> assertFalse(data2.contains(q)));
    assertFalse(data2.contains(title));

    RDFPatch.write(file, empty(), of(rdf.createQuad(LDP.PreferContainment, identifier, LDP.contains,
            rdf.createIRI("trellis:repository/resource/1"))), later.plusSeconds(10L));

    final List<VersionRange> versions = RDFPatch.asTimeMap(file);
    assertEquals(1L, versions.size());
    assertEquals(time.truncatedTo(MILLIS), versions.get(0).getFrom().truncatedTo(MILLIS));
    assertEquals(later.truncatedTo(MILLIS), versions.get(0).getUntil().truncatedTo(MILLIS));
}

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

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