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.vmware.photon.controller.api.client.resource.VmApiTest.java

@Test
public void testPerformStopOperationAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    VmApi vmApi = new VmApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    vmApi.performStopOperationAsync("foo", new FutureCallback<Task>() {
        @Override//from  w  w w.  java  2 s.c  o m
        public void onSuccess(@Nullable Task result) {
            assertEquals(result, responseTask);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:org.noorganization.instalist.server.api.IngredientResourceTest.java

@Test
public void testPutIngredient() throws Exception {
    String url = "/groups/%d/ingredients/%s";
    Instant preUpdate = mIngredient.getUpdated();
    IngredientInfo updatedIngred = new IngredientInfo().withAmount(3f);

    Response notAuthorizedResponse = target(
            String.format(url, mGroup.getId(), mIngredient.getUUID().toString())).request()
                    .put(Entity.json(updatedIngred));
    assertEquals(401, notAuthorizedResponse.getStatus());

    Response wrongAuthResponse = target(String.format(url, mGroup.getId(), mIngredient.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").put(Entity.json(updatedIngred));
    assertEquals(401, wrongAuthResponse.getStatus());

    Response wrongGroupResponse = target(
            String.format(url, mNAGroup.getId(), mNAIngredient.getUUID().toString())).request()
                    .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedIngred));
    assertEquals(401, wrongGroupResponse.getStatus());

    Response wrongListResponse = target(String.format(url, mGroup.getId(), mNAIngredient.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedIngred));
    assertEquals(404, wrongListResponse.getStatus());

    Response goneResponse = target(String.format(url, mGroup.getId(), mDeletedIngredient.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedIngred));
    assertEquals(410, goneResponse.getStatus());
    mManager.refresh(mIngredient);//from   w  w  w .  j  ava  2 s .com
    assertEquals(1f, mIngredient.getAmount(), 0.001f);

    updatedIngred.setLastChanged(new Date(preUpdate.toEpochMilli() - 10000));
    Response conflictResponse = target(String.format(url, mGroup.getId(), mIngredient.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedIngred));
    assertEquals(409, conflictResponse.getStatus());
    mManager.refresh(mIngredient);
    assertEquals(1f, mIngredient.getAmount(), 0.001f);

    updatedIngred.setLastChanged(Date.from(Instant.now()));
    Response okResponse = target(String.format(url, mGroup.getId(), mIngredient.getUUID().toString())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedIngred));
    assertEquals(200, okResponse.getStatus());
    mManager.refresh(mIngredient);
    assertEquals(3f, mIngredient.getAmount(), 0.001f);
    assertTrue(preUpdate + " is not before " + mIngredient.getUpdated(),
            preUpdate.isBefore(mIngredient.getUpdated()));
}

From source file:com.vmware.photon.controller.api.client.resource.VmRestApiTest.java

@Test
public void testPerformStopOperationAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    VmApi vmApi = new VmRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    vmApi.performStopOperationAsync("foo", new FutureCallback<Task>() {
        @Override/*  w w w .ja  v  a 2 s.  co  m*/
        public void onSuccess(@Nullable Task result) {
            assertEquals(result, responseTask);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:org.jboss.pnc.indyrepositorymanager.IndyRepositorySession.java

/**
 * Promote all build dependencies NOT ALREADY CAPTURED to the hosted repository holding store for the shared imports and
 * return dependency artifacts meta data.
 *
 * @param report The tracking report that contains info about artifacts downloaded by the build
 * @return List of dependency artifacts meta data
 * @throws RepositoryManagerException In case of a client API transport error or an error during promotion of artifacts
 *//*from  w  w w. ja va2 s  .c o m*/
private List<Artifact> processDownloads(TrackedContentDTO report) throws RepositoryManagerException {
    Logger logger = LoggerFactory.getLogger(getClass());

    IndyContentClientModule content;
    try {
        content = indy.content();
    } catch (IndyClientException e) {
        throw new RepositoryManagerException("Failed to retrieve Indy content module. Reason: %s", e,
                e.getMessage());
    }

    List<Artifact> deps = new ArrayList<>();

    Set<TrackedContentEntryDTO> downloads = report.getDownloads();
    if (downloads != null) {
        Map<StoreKey, Map<StoreKey, Set<String>>> toPromote = new HashMap<>();

        Map<String, StoreKey> promotionTargets = new HashMap<>();
        for (TrackedContentEntryDTO download : downloads) {
            String path = download.getPath();
            StoreKey source = download.getStoreKey();
            String packageType = source.getPackageType();
            if (ignoreContent(packageType, path)) {
                logger.debug("Ignoring download (matched in ignored-suffixes): {} (From: {})",
                        download.getPath(), source);
                continue;
            }

            // If the entry is from a hosted repository (also shared-imports), it shouldn't be auto-promoted.
            // New binary imports will be coming from a remote repository...
            if (isExternalOrigin(source)) {
                StoreKey target = null;
                Map<StoreKey, Set<String>> sources = null;
                Set<String> paths = null;

                // this has not been captured, so promote it.
                switch (packageType) {
                case MAVEN_PKG_KEY:
                case NPM_PKG_KEY:
                    target = getPromotionTarget(packageType, promotionTargets);
                    sources = toPromote.computeIfAbsent(target, t -> new HashMap<>());
                    paths = sources.computeIfAbsent(source, s -> new HashSet<>());

                    paths.add(download.getPath());
                    if (MAVEN_PKG_KEY.equals(packageType)) {
                        paths.add(download.getPath() + ".md5");
                        paths.add(download.getPath() + ".sha1");
                    }
                    break;

                case GENERIC_PKG_KEY:
                    String remoteName = source.getName();
                    String hostedName;
                    if (remoteName.startsWith("r-")) {
                        hostedName = "h-" + remoteName.substring(2);
                    } else {
                        logger.warn("Unexpected generic http remote repo name {}. Using it for hosted repo "
                                + "without change, but it probably doesn't exist.", remoteName);
                        hostedName = remoteName;
                    }
                    target = new StoreKey(source.getPackageType(), StoreType.hosted, hostedName);
                    sources = toPromote.computeIfAbsent(target, t -> new HashMap<>());
                    paths = sources.computeIfAbsent(source, s -> new HashSet<>());

                    paths.add(download.getPath());
                    break;

                default:
                    // do not promote anything else anywhere
                    break;
                }
            }

            String identifier = computeIdentifier(download);

            logger.info("Recording download: {}", identifier);

            String originUrl = download.getOriginUrl();
            if (originUrl == null) {
                // this is from a hosted repository, either shared-imports or a build, or something like that.
                originUrl = download.getLocalUrl();
            }

            TargetRepository targetRepository = getDownloadsTargetRepository(download, content);

            Artifact.Builder artifactBuilder = Artifact.Builder.newBuilder().md5(download.getMd5())
                    .sha1(download.getSha1()).sha256(download.getSha256()).size(download.getSize())
                    .deployPath(download.getPath()).originUrl(originUrl).importDate(Date.from(Instant.now()))
                    .filename(new File(path).getName()).identifier(identifier)
                    .targetRepository(targetRepository);

            Artifact artifact = validateArtifact(artifactBuilder.build());
            deps.add(artifact);
        }

        for (Map.Entry<StoreKey, Map<StoreKey, Set<String>>> targetToSources : toPromote.entrySet()) {
            StoreKey target = targetToSources.getKey();
            for (Map.Entry<StoreKey, Set<String>> sourceToPaths : targetToSources.getValue().entrySet()) {
                StoreKey source = sourceToPaths.getKey();
                PathsPromoteRequest req = new PathsPromoteRequest(source, target, sourceToPaths.getValue())
                        .setPurgeSource(false);
                // set read-only only the generic http proxy hosted repos, not shared-imports
                doPromoteByPath(req, GENERIC_PKG_KEY.equals(target.getPackageType()));
            }
        }
    }

    return deps;
}

From source file:org.noorganization.instalist.server.api.TaggedProductResourceTest.java

@Test
public void testPutTaggedProduct() throws Exception {
    String url = "/groups/%d/taggedproducts/%s";
    Instant preUpdate = mTaggedProduct.getUpdated();
    TaggedProductInfo updatedTP = new TaggedProductInfo().withTagUUID(mNATag.getUUID());

    Response notAuthorizedResponse = target(
            String.format(url, mGroup.getId(), mTaggedProduct.getUUID().toString())).request()
                    .put(Entity.json(updatedTP));
    assertEquals(401, notAuthorizedResponse.getStatus());

    Response wrongAuthResponse = target(String.format(url, mGroup.getId(), mTaggedProduct.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").put(Entity.json(updatedTP));
    assertEquals(401, wrongAuthResponse.getStatus());

    Response wrongGroupResponse = target(
            String.format(url, mNAGroup.getId(), mNATaggedProduct.getUUID().toString())).request()
                    .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedTP));
    assertEquals(401, wrongGroupResponse.getStatus());

    Response wrongListResponse = target(
            String.format(url, mGroup.getId(), mNATaggedProduct.getUUID().toString())).request()
                    .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedTP));
    assertEquals(404, wrongListResponse.getStatus());

    Response goneResponse = target(String.format(url, mGroup.getId(), mDeletedIngredient.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedTP));
    assertEquals(410, goneResponse.getStatus());

    Response wrongRefResponse = target(String.format(url, mGroup.getId(), mTaggedProduct.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedTP));
    assertEquals(400, wrongRefResponse.getStatus());
    mManager.refresh(mTaggedProduct);//from ww w.  j ava 2  s.c o  m
    assertEquals(mTag.getUUID(), mTaggedProduct.getTag().getUUID());

    updatedTP.setTagUUID(mTag.getUUID());
    updatedTP.setLastChanged(new Date(preUpdate.toEpochMilli() - 10000));
    Response conflictResponse = target(String.format(url, mGroup.getId(), mTaggedProduct.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedTP));
    assertEquals(409, conflictResponse.getStatus());
    mManager.refresh(mTaggedProduct);
    assertEquals(mTag.getUUID(), mTaggedProduct.getTag().getUUID());

    updatedTP.setLastChanged(Date.from(Instant.now()));
    Response okResponse = target(String.format(url, mGroup.getId(), mTaggedProduct.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedTP));
    assertEquals(200, okResponse.getStatus());
    mManager.refresh(mTaggedProduct);
    assertTrue(preUpdate + " is not before " + mTaggedProduct.getUpdated(),
            preUpdate.isBefore(mTaggedProduct.getUpdated()));
}

From source file:org.noorganization.instalist.server.api.ProductResourceTest.java

@Test
public void testPutProduct() throws Exception {
    String url = "/groups/%d/products/%s";
    Instant preUpdate = mProduct.getUpdated();
    ProductInfo updatedProduct = new ProductInfo().withDeleted(false).withName("changedproduct");

    Response notAuthorizedResponse = target(String.format(url, mGroup.getId(), mProduct.getUUID().toString()))
            .request().put(Entity.json(updatedProduct));
    assertEquals(401, notAuthorizedResponse.getStatus());

    Response wrongAuthResponse = target(String.format(url, mGroup.getId(), mProduct.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").put(Entity.json(updatedProduct));
    assertEquals(401, wrongAuthResponse.getStatus());

    Response wrongGroupResponse = target(String.format(url, mNAGroup.getId(), mNAProduct.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedProduct));
    assertEquals(401, wrongGroupResponse.getStatus());

    Response wrongListResponse = target(String.format(url, mGroup.getId(), mNAProduct.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedProduct));
    assertEquals(404, wrongListResponse.getStatus());

    Response goneResponse = target(String.format(url, mGroup.getId(), mDeletedProduct.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedProduct));
    assertEquals(410, goneResponse.getStatus());
    mManager.refresh(mProduct);/*from  w  w  w .j a v  a 2 s .  co  m*/
    assertEquals("product1", mProduct.getName());

    updatedProduct.setLastChanged(new Date(preUpdate.toEpochMilli() - 10000));
    Response conflictResponse = target(String.format(url, mGroup.getId(), mProduct.getUUID().toString()))
            .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedProduct));
    assertEquals(409, conflictResponse.getStatus());
    mManager.refresh(mProduct);
    assertEquals("product1", mProduct.getName());

    updatedProduct.setLastChanged(Date.from(Instant.now()));
    Response okResponse = target(String.format(url, mGroup.getId(), mProduct.getUUID().toString())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).put(Entity.json(updatedProduct));
    assertEquals(200, okResponse.getStatus());
    mManager.refresh(mProduct);
    assertEquals("changedproduct", mProduct.getName());
    assertEquals(1f, mProduct.getDefaultAmount(), 0.001f);
    assertEquals(0.5f, mProduct.getStepAmount(), 0.001f);
    assertNull(mProduct.getUnit());
    assertTrue(preUpdate + " is not before " + mProduct.getUpdated(),
            preUpdate.isBefore(mProduct.getUpdated()));
}

From source file:org.apache.servicecomb.demo.springmvc.tests.SpringMvcIntegrationTestBase.java

@Test
public void ableToPostDate() throws Exception {
    ZonedDateTime date = ZonedDateTime.now().truncatedTo(SECONDS);
    MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
    body.add("date",
            RestObjectMapperFactory.getRestObjectMapper().convertToString(Date.from(date.toInstant())));

    HttpHeaders headers = new HttpHeaders();
    headers.add(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE);

    int seconds = 1;
    Date result = restTemplate.postForObject(codeFirstUrl + "addDate?seconds={seconds}",
            new HttpEntity<>(body, headers), Date.class, seconds);

    assertThat(result, is(Date.from(date.plusSeconds(seconds).toInstant())));

    ListenableFuture<ResponseEntity<Date>> listenableFuture = asyncRestTemplate.postForEntity(
            codeFirstUrl + "addDate?seconds={seconds}", new HttpEntity<>(body, headers), Date.class, seconds);
    ResponseEntity<Date> dateResponseEntity = listenableFuture.get();
    assertThat(dateResponseEntity.getBody(), is(Date.from(date.plusSeconds(seconds).toInstant())));
}

From source file:org.apache.james.transport.mailets.DSNBounceTest.java

@Test
public void serviceShouldAttachTheOriginalMailWhenAttachmentIsEqualToAll() throws Exception {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME)
            .mailetContext(fakeMailContext).setProperty("attachment", "all").build();
    dsnBounce.init(mailetConfig);/*w  w w .j  av  a 2 s  .c  om*/

    MailAddress senderMailAddress = new MailAddress("sender@domain.com");
    MimeMessage mimeMessage = MimeMessageBuilder.mimeMessageBuilder().setText("My content").build();
    FakeMail mail = FakeMail.builder().sender(senderMailAddress).name(MAILET_NAME)
            .recipient("recipient@domain.com").lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z")))
            .mimeMessage(mimeMessage).build();
    MimeMessage mimeMessageCopy = new MimeMessage(mimeMessage);

    dsnBounce.service(mail);

    List<SentMail> sentMails = fakeMailContext.getSentMails();
    assertThat(sentMails).hasSize(1);
    SentMail sentMail = sentMails.get(0);
    assertThat(sentMail.getSender()).isNull();
    assertThat(sentMail.getRecipients()).containsOnly(senderMailAddress);
    MimeMessage sentMessage = sentMail.getMsg();
    MimeMultipart content = (MimeMultipart) sentMessage.getContent();

    assertThat(sentMail.getMsg().getContentType()).startsWith("multipart/report;");
    assertThat(MimeMessageUtil.asString((MimeMessage) content.getBodyPart(2).getContent()))
            .isEqualTo(MimeMessageUtil.asString(mimeMessageCopy));
}

From source file:com.vmware.photon.controller.api.client.resource.VmApiTest.java

@Test
public void testPerformRestartOperation() throws IOException {
    Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    VmApi vmApi = new VmApi(restClient);

    Task task = vmApi.performRestartOperation("foo");
    assertEquals(task, responseTask);/* www . ja v a  2 s.co  m*/
}