Example usage for java.util Date from

List of usage examples for java.util Date from

Introduction

In this page you can find the example usage for java.util Date from.

Prototype

public static Date from(Instant instant) 

Source Link

Document

Obtains an instance of Date from an Instant object.

Usage

From source file:com.coinblesk.server.controller.AdminController.java

@RequestMapping(value = "/keys", method = GET)
@ResponseBody/*  w ww  .jav a 2  s . c  om*/
public List<KeysDTO> getAllKeys() {
    NetworkParameters params = appConfig.getNetworkParameters();

    // Pre-calculate balances for each address
    Map<Address, Coin> balances = walletService.getBalanceByAddresses();

    List<Keys> keys = keyService.allKeys();

    // ...and summed for each public key
    Map<Keys, Long> balancesPerKeys = keys.stream()
            .collect(Collectors.toMap(Function.identity(), key -> key.timeLockedAddresses().stream()
                    .map(tla -> tla.toAddress(params)).map(balances::get).mapToLong(Coin::longValue).sum()));

    // Map the Keys entities to DTOs including the containing TimeLockedAddresses
    return keys.stream().map(key -> new KeysDTO(SerializeUtils.bytesToHex(key.clientPublicKey()),
            SerializeUtils.bytesToHex(key.serverPublicKey()), SerializeUtils.bytesToHex(key.serverPrivateKey()),
            Date.from(Instant.ofEpochSecond(key.timeCreated())), key.virtualBalance(), balancesPerKeys.get(key),
            key.virtualBalance() + balancesPerKeys.get(key), key.timeLockedAddresses().stream().map(tla -> {
                Instant createdAt = Instant.ofEpochSecond(tla.getTimeCreated());
                Instant lockedUntil = Instant.ofEpochSecond(tla.getLockTime());
                Coin balance = balances.get(tla.toAddress(params));
                return new TimeLockedAddressDTO(tla.toAddress(params).toString(),
                        "http://" + (params.getClass().equals(TestNet3Params.class) ? "tbtc." : "")
                                + "blockr.io/address/info/" + tla.toAddress(params),
                        Date.from(createdAt), Date.from(lockedUntil), lockedUntil.isAfter(Instant.now()),
                        balance.longValue());
            }).collect(Collectors.toList()))).collect(Collectors.toList());
}

From source file:de.alpharogroup.user.service.UserTokensBusinessService.java

/**
 * New user tokens.// w  w w  . ja  v a  2 s . co m
 *
 * @param username
 *            the username
 * @return the user tokens
 */
private UserTokens newUserTokens(String username) {
    UserTokens userTokens;
    // expires in one year
    Date expiry = Date.from(LocalDateTime.now().plusMonths(12).atZone(ZoneId.systemDefault()).toInstant());
    // create a token
    String token = RandomExtensions.randomToken();
    userTokens = UserTokens.builder().expiry(expiry).username(username).token(token).build();
    return userTokens;
}

From source file:com.fluke.data.processor.ReatimeDBReader.java

private boolean tryAgain(String eq, List<RealtimeTicker> list) {
    if (list != null && !list.isEmpty()) {
        return false;
    }/*from  w  ww  .  ja va  2 s .c o  m*/
    Timestamp maxTime = getMaxtimeNoted();
    if (maxTime == null) {
        return true;
        //probably the starting phase
    }
    Timestamp lastUpdated = getLastTimeStamp(eq);
    if (lastUpdated == null) {
        throw new DataStreamLostException();
    }
    int minsReached = Util.getMinutes(Date.from(maxTime.toInstant()));
    int minUpdated = Util.getMinutes(Date.from(lastUpdated.toInstant()));
    if (minsReached - minUpdated > 2) {
        throw new DataStreamLostException();
    }
    return true;
}

From source file:com.esri.geoportal.harvester.waf.WafFile.java

/**
 * Reads last modified date.//from  w w  w. java  2  s  .  co m
 * @param response HTTP response
 * @return last modified date or <code>null</code> if unavailable
 */
private Date readLastModifiedDate(HttpResponse response) {
    try {
        Header lastModifedHeader = response.getFirstHeader("Last-Modified");
        return lastModifedHeader != null ? Date.from(ZonedDateTime
                .from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(lastModifedHeader.getValue())).toInstant())
                : null;
    } catch (Exception ex) {
        return null;
    }
}

From source file:com.querydsl.webhooks.GithubReviewWindow.java

@Bean
public PullRequestHandler reviewWindowHandler(Environment environment) {
    Duration defaultReviewWindow = Duration.parse(environment.getRequiredProperty("duration")); //duration is the default window
    Map<String, ScheduledFuture<?>> asyncTasks = Maps.newConcurrentMap();

    return payload -> {
        PullRequest pullRequest = payload.getPullRequest();
        Ref head = pullRequest.getHead();

        try {//from w  w  w .j  a  v a2  s .c om
            GHRepository repository = github.getRepository(payload.getRepository().getFullName());
            Collection<GHLabel> labels = repository.getIssue(pullRequest.getNumber()).getLabels();

            Duration reviewTime = labels.stream().map(label -> "duration." + label.getName()) //for all duration.[label] properties
                    .map(environment::getProperty).filter(Objects::nonNull) //look for a Duration
                    .findFirst().map(Duration::parse).orElse(defaultReviewWindow); //if none found, use the default window

            ZonedDateTime creationTime = pullRequest.getCreatedAt();
            ZonedDateTime windowCloseTime = creationTime.plus(reviewTime);

            boolean windowPassed = now().isAfter(windowCloseTime);
            logger.info("creationTime({}) + reviewTime({}) = windowCloseTime({}), so windowPassed = {}",
                    creationTime, reviewTime, windowCloseTime, windowPassed);

            if (windowPassed) {
                completeAndCleanUp(asyncTasks, repository, head);
            } else {
                createPendingMessage(repository, head, reviewTime);

                ScheduledFuture<?> scheduledTask = taskScheduler.schedule(
                        () -> completeAndCleanUp(asyncTasks, repository, head),
                        Date.from(windowCloseTime.toInstant()));

                replaceCompletionTask(asyncTasks, scheduledTask, head);
            }
        } catch (IOException ex) {
            throw Throwables.propagate(ex);
        }
    };
}

From source file:org.codice.ddf.registry.schemabindings.helper.SlotTypeHelper.java

/**
 * This is a convenience method that will get the values from a SlotType1
 *
 * @param slot the SlotType1 to get the values from, null returns empty List
 * @return a List of Date values found in the SlotType1
 *///from  w w w.j a v a  2 s.c  o m
public List<Date> getDateValues(SlotType1 slot) {
    return getStringValues(slot).stream()
            .map(dateString -> Date.from(ZonedDateTime.parse(dateString).toInstant()))
            .collect(Collectors.toList());
}

From source file:com.esri.geoportal.harvester.api.base.DataReferenceSerializer.java

/**
 * De-serializes data reference/*from   w  ww.ja  va  2  s . c o m*/
 *
 * @param input input stream
 * @return data reference
 * @throws IOException if de-serialization fails
 * @throws URISyntaxException if de-serialization fails
 */
public DataReference deserialize(InputStream input) throws IOException, URISyntaxException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
    String line = reader.readLine();
    if (line != null) {
        String[] split = line.split(",");
        if (split.length == 7) {
            int i = 0;
            byte[] bBrokerUri = DECODER.decode(split[i++].getBytes("UTF-8"));
            byte[] bBrokerName = DECODER.decode(split[i++].getBytes("UTF-8"));
            byte[] bId = DECODER.decode(split[i++].getBytes("UTF-8"));
            byte[] bLastModifiedDate = DECODER.decode(split[i++].getBytes("UTF-8"));
            byte[] bSourceUri = DECODER.decode(split[i++].getBytes("UTF-8"));
            byte[] bContentType = DECODER.decode(split[i++].getBytes("UTF-8"));
            byte[] bContent = DECODER.decode(split[i++].getBytes("UTF-8"));

            URI brokerUri = URI.create(new String(bBrokerUri, "UTF-8"));
            String sBrokerName = new String(bBrokerName, "UTF-8");
            String sId = new String(bId, "UTF-8");
            String sLastModifiedDate = new String(bLastModifiedDate, "UTF-8");
            URI sourceUri = URI.create(new String(bSourceUri, "UTF-8"));

            Date lastModifiedDate = !sLastModifiedDate.isEmpty()
                    ? Date.from(OffsetDateTime.from(FORMATTER.parse(sLastModifiedDate)).toInstant())
                    : null;
            MimeType contentType = MimeType.parse(new String(bContentType, "UTF-8"));

            return new SimpleDataReference(brokerUri, sBrokerName, sId, lastModifiedDate, sourceUri, bContent,
                    contentType);
        }
    }
    return null;
}

From source file:net.ljcomputing.ecsr.security.service.impl.JwtTokenServiceImpl.java

/**
 * Calculate the new refresh date.//from   w w w . jav a  2 s  .  c  o m
 *
 * @return the date
 */
@SuppressWarnings("unused")
private Date refreshDate() {
    final LocalDateTime refreshLdt = ldtNow.plusMinutes(refreshTokenExpTime); // NOPMD
    final ZonedDateTime zdt = refreshLdt.atZone(ZONE_ID); // NOPMD
    final Instant instant = zdt.toInstant(); // NOPMD
    return Date.from(instant); // NOPMD
}

From source file:org.nuxeo.ecm.blob.azure.AzureBinaryManager.java

@Override
protected URI getRemoteUri(String digest, ManagedBlob blob, HttpServletRequest servletRequest)
        throws IOException {
    try {//from w w w.  j  ava  2s.c  om
        CloudBlockBlob blockBlobReference = container.getBlockBlobReference(digest);
        SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
        policy.setPermissionsFromString("r");

        Instant endDateTime = LocalDateTime.now().plusSeconds(directDownloadExpire)
                .atZone(ZoneId.systemDefault()).toInstant();
        policy.setSharedAccessExpiryTime(Date.from(endDateTime));

        SharedAccessBlobHeaders headers = new SharedAccessBlobHeaders();
        headers.setContentDisposition(getContentDispositionHeader(blob, servletRequest));
        headers.setContentType(getContentTypeHeader(blob));

        String sas = blockBlobReference.generateSharedAccessSignature(policy, headers, null);

        CloudBlockBlob signedBlob = new CloudBlockBlob(blockBlobReference.getUri(),
                new StorageCredentialsSharedAccessSignature(sas));
        return signedBlob.getQualifiedUri();
    } catch (URISyntaxException | InvalidKeyException | StorageException e) {
        throw new IOException(e);
    }
}

From source file:co.runrightfast.core.security.cert.X509V3CertRequest.java

public X509v3CertificateBuilder x509v3CertificateBuilder() {
    final JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerPrincipal, serialNumber,
            Date.from(notBefore), Date.from(notAfter), subjectPrincipal, subjectPublicKey);

    extensions.stream().forEach(ext -> {
        try {//from w w  w  .j  a v  a2  s .co m
            builder.addExtension(ext.getOid(), ext.isCritical(), ext.getValue());
        } catch (final CertIOException ex) {
            throw new ApplicationException(String.format("Failed to add extenstion: %s", ext), ex);
        }
    });

    return builder;
}