Example usage for java.time LocalDateTime ofInstant

List of usage examples for java.time LocalDateTime ofInstant

Introduction

In this page you can find the example usage for java.time LocalDateTime ofInstant.

Prototype

public static LocalDateTime ofInstant(Instant instant, ZoneId zone) 

Source Link

Document

Obtains an instance of LocalDateTime from an Instant and zone ID.

Usage

From source file:com.hotelbeds.hotelapimodel.auto.util.AssignUtils.java

public static LocalDateTime getLocalDateTime(Date date) {
    Instant instant = Instant.ofEpochMilli(date.getTime());
    return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}

From source file:com.sastix.cms.server.utils.MultipartFileSender.java

public void serveResource() throws Exception {
    if (response == null || request == null) {
        return;//from ww w.j a  v a  2  s .  c om
    }

    Long length = Files.size(filepath);
    String fileName = filepath.getFileName().toString();
    FileTime lastModifiedObj = Files.getLastModifiedTime(filepath);

    if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    long lastModified = LocalDateTime
            .ofInstant(lastModifiedObj.toInstant(), ZoneId.of(ZoneOffset.systemDefault().getId()))
            .toEpochSecond(ZoneOffset.UTC);

    // Validate request headers for caching ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && HttpUtils.matches(ifNoneMatch, fileName)) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so, then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !HttpUtils.matches(ifMatch, fileName)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(fileName)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                if (ifRangeTime != -1) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                long start = Range.sublong(part, 0, part.indexOf("-"));
                long end = Range.sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response --------------------------------------------------------

    // Get content type by file name and set content disposition.
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    } else if (!contentType.startsWith("image")) {
        // Else, expect for images, determine content disposition. If content type is supported by
        // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
        String accept = request.getHeader("Accept");
        disposition = accept != null && HttpUtils.accepts(accept, contentType) ? "inline" : "attachment";
    }
    LOG.debug("Content-Type : {}", contentType);
    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Type", contentType);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    LOG.debug("Content-Disposition : {}", disposition);
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client ------------------------------------------------

    // Prepare streams.
    try (InputStream input = new BufferedInputStream(Files.newInputStream(filepath));
            OutputStream output = response.getOutputStream()) {

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            LOG.debug("Return full file");
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + full.start + "-" + full.end + "/" + full.total);
            response.setHeader("Content-Length", String.valueOf(full.length));
            Range.copy(input, output, length, full.start, full.length);

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            LOG.debug("Return 1 part of file : from ({}) to ({})", r.start, r.end);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Copy single part range.
            Range.copy(input, output, length, r.start, r.length);

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Cast back to ServletOutputStream to get the easy println methods.
            ServletOutputStream sos = (ServletOutputStream) output;

            // Copy multi part range.
            for (Range r : ranges) {
                LOG.debug("Return multi part of file : from ({}) to ({})", r.start, r.end);
                // Add multipart boundary and header fields for every range.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY);
                sos.println("Content-Type: " + contentType);
                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                // Copy single part range of multi part range.
                Range.copy(input, output, length, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + MULTIPART_BOUNDARY + "--");
        }
    }

}

From source file:retsys.client.controller.PurchaseOrderConfirmController.java

private void populateData(PurchaseOrder po) {
    po_no.setText(po.getId().toString());
    po_date.setValue(LocalDateTime.ofInstant(po.getDate().toInstant(), ZoneId.systemDefault()).toLocalDate());
    po_no.setText(po.getId().toString());
    delivery_address.setText(po.getDeliveryAddress());
    vendor.setText(po.getVendor().getName() + " (ID:" + po.getVendor().getId() + ")");
    project.setText(po.getProject().getName() + " (ID:" + po.getProject().getId() + ")");

    ObservableList<POItem> items = FXCollections.observableArrayList();
    Iterator detailsIt = po.getPurchaseOrderDetail().iterator();
    while (detailsIt.hasNext()) {
        PurchaseOrderDetail detail = (PurchaseOrderDetail) detailsIt.next();
        Item item = detail.getItem();/*from  ww w  .  ja  v  a  2  s.  c  o  m*/
        int id = item.getId();
        String site = item.getSite();
        String name = item.getName();
        String brand = item.getBrand();
        String model = null;
        Double quantity = detail.getQuantity();
        Boolean confirm = "Y".equals(detail.getConfirm());

        items.add(new POItem(detail.getId(), site, name + " (ID:" + id + ")", brand, model, quantity, confirm,
                detail.getReceivedDate()));
    }
    poDetail.setItems(items);
    System.out.println(po.getAudit());
    populateAuditValues(po);
}

From source file:com.epam.catgenome.controller.util.MultipartFileSender.java

public void serveResource() throws IOException {
    if (response == null || request == null) {
        return;/*from   w  w w  .  j  a  v a  2 s.  co  m*/
    }

    if (!Files.exists(filepath)) {
        logger.error("File doesn't exist at URI : {}", filepath.toAbsolutePath().toString());
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    Long length = Files.size(filepath);
    String fileName = filepath.getFileName().toString();
    FileTime lastModifiedObj = Files.getLastModifiedTime(filepath);

    if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    long lastModified = LocalDateTime
            .ofInstant(lastModifiedObj.toInstant(), ZoneId.of(ZoneOffset.systemDefault().getId()))
            .toEpochSecond(ZoneOffset.UTC);
    //String contentType = MimeTypeUtils.probeContentType(filepath);
    String contentType = null;

    // Validate request headers for caching ---------------------------------------------------
    if (!validateHeadersCaching(fileName, lastModified)) {
        return;
    }

    // Validate request headers for resume ----------------------------------------------------
    if (!validateHeadersResume(fileName, lastModified)) {
        return;
    }

    // Validate and process range -------------------------------------------------------------
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = processRange(length, fileName, full);
    if (ranges == null) {
        return;
    }

    // Prepare and initialize response --------------------------------------------------------

    // Get content type by file name and set content disposition.
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    } else if (!contentType.startsWith("image")) {
        // Else, expect for images, determine content disposition. If content type is supported by
        // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
        String accept = request.getHeader("Accept");
        disposition = accept != null && HttpUtils.accepts(accept, contentType) ? "inline" : "attachment";
    }
    logger.debug("Content-Type : {}", contentType);
    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Type", contentType);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    logger.debug("Content-Disposition : {}", disposition);
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client ------------------------------------------------

    // Prepare streams.
    try (InputStream input = new BufferedInputStream(Files.newInputStream(filepath));
            OutputStream output = response.getOutputStream()) {

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            logger.info("Return full file");
            response.setContentType(contentType);
            response.setHeader(CONTENT_RANGE_HEADER, "bytes " + full.start + "-" + full.end + "/" + full.total);
            response.setHeader("Content-Length", String.valueOf(full.length));
            Range.copy(input, output, length, full.start, full.length);

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            logger.info("Return 1 part of file : from ({}) to ({})", r.start, r.end);
            response.setContentType(contentType);
            response.setHeader(CONTENT_RANGE_HEADER, "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Copy single part range.
            Range.copy(input, output, length, r.start, r.length);

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Cast back to ServletOutputStream to get the easy println methods.
            ServletOutputStream sos = (ServletOutputStream) output;

            // Copy multi part range.
            for (Range r : ranges) {
                logger.info("Return multi part of file : from ({}) to ({})", r.start, r.end);
                // Add multipart boundary and header fields for every range.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY);
                sos.println("Content-Type: " + contentType);
                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                // Copy single part range of multi part range.
                Range.copy(input, output, length, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + MULTIPART_BOUNDARY + "--");
        }
    }

}

From source file:org.wallride.service.PostService.java

@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void updatePostViews() {
    LocalDateTime now = LocalDateTime.now();
    Set<JobExecution> jobExecutions = jobExplorer.findRunningJobExecutions("updatePostViewsJob");
    for (JobExecution jobExecution : jobExecutions) {
        LocalDateTime startTime = LocalDateTime.ofInstant(jobExecution.getStartTime().toInstant(),
                ZoneId.systemDefault());
        Duration d = Duration.between(now, startTime);
        if (Math.abs(d.toMinutes()) == 0) {
            logger.info("Skip processing because the job is running.");
            return;
        }/*from   w  w  w .j a va 2  s . co  m*/
    }

    JobParameters params = new JobParametersBuilder()
            .addDate("now", Date.from(now.atZone(ZoneId.systemDefault()).toInstant())).toJobParameters();
    try {
        jobLauncher.run(updatePostViewsJob, params);
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:dhbw.clippinggorilla.external.twitter.TwitterUtils.java

private static Article fillArticle(Status status) {
    Article article = new Article();
    article.setTitle(status.getUser().getName());
    article.setDescription(status.getText());
    article.setBody(status.getText());/*from ww  w. jav  a2s .  c o m*/
    article.setSource(SourceUtils.TWITTER);
    for (MediaEntity mediaEntity : status.getMediaEntities()) {
        if (!mediaEntity.getType().equals("video")) {
            article.setUrlToImage(mediaEntity.getMediaURL());
            break;
        }
    }
    if (article.getUrlToImage().isEmpty()) {
        article.setUrlToImage(status.getUser().getBiggerProfileImageURL());
    }
    article.setUrl("https://twitter.com/" + status.getUser().getScreenName() + "/status/" + status.getId());
    article.setId(status.getId() + "");
    article.setAuthor("@" + status.getUser().getScreenName());
    Date date = status.getCreatedAt();
    Instant instant = Instant.ofEpochMilli(date.getTime());
    LocalDateTime createdAt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
    article.setPublishedAt(createdAt.toString());
    return article;
}

From source file:org.codice.ddf.admin.insecure.defaults.service.DefaultUsersDeletionScheduler.java

private String cronCalculator(Instant firstInstall) {
    Instant threeDayTimestamp = firstInstall.plus(Duration.ofDays(3).minus(Duration.ofMinutes(30)));
    LocalDateTime localDateTime = LocalDateTime.ofInstant(threeDayTimestamp, ZoneId.systemDefault());

    return String.format("%d+%d+%d+%d+%d+?+%d", localDateTime.getSecond(), localDateTime.getMinute(),
            localDateTime.getHour(), localDateTime.getDayOfMonth(), localDateTime.getMonthValue(),
            localDateTime.getYear());/*w  w  w .j  a v  a 2  s  . c  o m*/
}

From source file:com.fantasy.stataggregator.workers.GameDataRetrieverTask.java

/**
 * Determines if a game has already been played, No current game data<br>
 * will be pulled, since the statistics aren't final.
 *
 * @param sched/* ww w . java  2  s  . c  om*/
 * @return
 */
private boolean hasBeenPlayed(GameSchedule sched) throws ParseException {
    Date gameDate = sched.getGamedate();
    if (Objects.nonNull(gameDate)) {
        LocalDate dateOnly = LocalDateTime.ofInstant(gameDate.toInstant(), ZoneId.systemDefault())
                .toLocalDate();

        return dateOnly.isBefore(LocalDate.now());
    }
    return false;
}

From source file:reactivity.SseController.java

/**
 * <p>//from   w  ww . j a v  a 2  s. com
 * Retrieves and pushes the timeseries associated to the given artifact.
 * </p>
 *
 * @param a the artifact associated to timeseries
 */
private void timeseries(final Artifact a) {

    // Compute the key
    final LocalDateTime i = LocalDateTime.ofInstant(Instant.ofEpochMilli(a.getTimestamp()),
            ZoneId.systemDefault());
    final Object[] key = new Object[] { a.getGroup().getType() + "/" + a.getGroup().getName(), i.getYear(),
            i.getMonthValue(), i.getDayOfMonth() };

    repository.color(key).subscribe((item) -> replayProcessor.onNext(sse(Artifact.class.cast(item))));
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceTest.java

private void modifyResourceInformationBasedOnPathInformation(OwncloudTestResourceImpl owncloudResource) {
    Path resourcePath = resolveRelativePath(Paths.get(owncloudResource.getHref().getPath()));
    try {//from  w  w w.  j  a  v  a2 s  .c o  m
        LocalDateTime lastModifiedAt = LocalDateTime
                .ofInstant(Files.getLastModifiedTime(resourcePath).toInstant(), ZoneId.systemDefault());
        owncloudResource.setLastModifiedAt(lastModifiedAt);
    } catch (IOException e) {
        e.printStackTrace(System.err);
        throw new IllegalStateException("Error while getting last modified time of Resource " + resourcePath,
                e);
    }
}