Example usage for java.time Instant now

List of usage examples for java.time Instant now

Introduction

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

Prototype

public static Instant now() 

Source Link

Document

Obtains the current instant from the system clock.

Usage

From source file:com.netflix.genie.web.services.impl.JobKillServiceV3.java

private void killJobOnUnix(final int pid) throws GenieException {
    try {//from w w w  .j av  a 2s.c o m
        // Ensure this process check can't be timed out
        final Instant tomorrow = Instant.now().plus(1, ChronoUnit.DAYS);
        final ProcessChecker processChecker = this.processCheckerFactory.get(pid, tomorrow);
        processChecker.checkProcess();
    } catch (final ExecuteException ee) {
        // This means the job was done already
        log.debug("Process with pid {} is already done", pid);
        return;
    } catch (final IOException ioe) {
        throw new GenieServerException("Unable to check process status for pid " + pid, ioe);
    }

    // TODO: Do we need retries?
    // This means the job client process is still running
    try {
        final CommandLine killCommand;
        if (this.runAsUser) {
            killCommand = new CommandLine("sudo");
            killCommand.addArgument("kill");
        } else {
            killCommand = new CommandLine("kill");
        }
        killCommand.addArguments(Integer.toString(pid));
        this.executor.execute(killCommand);
    } catch (final IOException ioe) {
        throw new GenieServerException("Unable to kill process " + pid, ioe);
    }
}

From source file:org.apache.solr.servlet.SolrDispatchFilter.java

private void logWelcomeBanner() {
    log.info(" ___      _       Welcome to Apache Solr version {}", solrVersion());
    log.info("/ __| ___| |_ _   Starting in {} mode on port {}", isCloudMode() ? "cloud" : "standalone",
            getSolrPort());//w ww  . j  a  v a 2 s.  com
    log.info("\\__ \\/ _ \\ | '_|  Install dir: {}", System.getProperty("solr.install.dir"));
    log.info("|___/\\___/_|_|    Start time: {}", Instant.now().toString());
}

From source file:keywhiz.service.resources.admin.ClientsResource.java

/**
 * Delete Client by ID//from w  ww. jav  a2s. c o  m
 *
 * @excludeParams user
 * @param clientId the ID of the Client to be deleted
 *
 * @description Deletes a single Client if found.
 * Used by Keywhiz CLI and the web ui.
 * @responseMessage 200 Found and deleted Client with given ID
 * @responseMessage 404 Client with given ID not Found
 */
@Path("{clientId}")
@Timed
@ExceptionMetered
@DELETE
public Response deleteClient(@Auth User user, @PathParam("clientId") LongParam clientId) {
    logger.info("User '{}' deleting client id={}.", user, clientId);

    Optional<Client> client = clientDAO.getClientById(clientId.get());
    if (!client.isPresent()) {
        throw new NotFoundException("Client not found.");
    }

    clientDAO.deleteClient(client.get());

    auditLog.recordEvent(
            new Event(Instant.now(), EventTag.CLIENT_DELETE, user.getName(), client.get().getName()));

    return Response.noContent().build();
}

From source file:com.onyxscheduler.domain.SchedulerIT.java

private Instant buildNonReachableFutureDate() {
    return Instant.now().plus(NON_REACHABLE_FUTURE_MINUTES, ChronoUnit.MINUTES);
}

From source file:io.dropwizard.revolver.persistence.AeroSpikePersistenceProvider.java

@Override
public void saveResponse(String requestId, RevolverCallbackResponse response) {
    final Key key = new Key(mailBoxConfig.getNamespace(), MAILBOX_SET_NAME, requestId);
    final Bin state = new Bin(BinNames.STATE, RevolverRequestState.RESPONDED.name());
    try {//ww  w  .  ja  v a 2  s. com
        final Bin responseHeaders = new Bin(BinNames.RESPONSE_HEADERS,
                objectMapper.writeValueAsString(response.getHeaders()));
        final Bin responseBody = new Bin(BinNames.RESPONSE_BODY, response.getBody());
        final Bin responseStatusCode = new Bin(BinNames.RESPONSE_STATUS_CODE, response.getStatusCode());
        final Bin responseTime = new Bin(BinNames.RESPONSE_TIME, Instant.now().toEpochMilli());
        final Bin updated = new Bin(BinNames.UPDATED, Instant.now().toEpochMilli());
        AerospikeConnectionManager.getClient().operate(null, key, Operation.put(state),
                Operation.put(responseHeaders), Operation.put(responseBody), Operation.put(responseStatusCode),
                Operation.put(responseTime), Operation.put(updated));
    } catch (JsonProcessingException e) {
        log.warn("Error encoding response headers", e);
    }
}

From source file:com.orange.cepheus.broker.persistence.SubscriptionsRepositoryTest.java

@Test
public void getAllSubscriptionsWithExceptionTest() throws SubscriptionPersistenceException {
    thrown.expect(SubscriptionPersistenceException.class);
    Instant expirationDate = Instant.now().plus(1, ChronoUnit.DAYS);
    jdbcTemplate.update("insert into t_subscriptions(id,expirationDate,subscribeContext) values(?,?,?)",
            "12345", expirationDate.toString(), "aaaaaa");
    Map<String, Subscription> subscriptions = subscriptionsRepository.getAllSubscriptions();
}

From source file:com.netflix.genie.web.controllers.DtoConverters.java

/**
 * Convert a V3 Cluster to a V4 cluster.
 *
 * @param v3Cluster The cluster to convert
 * @return The V4 representation of the cluster
 *///from  www  .j a  va 2 s.c o m
public static Cluster toV4Cluster(final com.netflix.genie.common.dto.Cluster v3Cluster) {
    final ClusterMetadata.Builder metadataBuilder = new ClusterMetadata.Builder(v3Cluster.getName(),
            v3Cluster.getUser(), v3Cluster.getVersion(), v3Cluster.getStatus())
                    .withTags(toV4Tags(v3Cluster.getTags()));

    v3Cluster.getMetadata().ifPresent(metadataBuilder::withMetadata);
    v3Cluster.getDescription().ifPresent(metadataBuilder::withDescription);

    return new Cluster(v3Cluster.getId().orElseThrow(IllegalArgumentException::new),
            v3Cluster.getCreated().orElse(Instant.now()), v3Cluster.getUpdated().orElse(Instant.now()),
            new ExecutionEnvironment(v3Cluster.getConfigs(), v3Cluster.getDependencies(),
                    v3Cluster.getSetupFile().orElse(null)),
            metadataBuilder.build());
}

From source file:keywhiz.service.resources.admin.GroupsResource.java

/**
 * Delete Group by ID/*from   w ww.  ja v  a  2 s. c o  m*/
 *
 * @excludeParams user
 * @param groupId the ID of the Group to be deleted
 *
 * @description Deletes a single Group if found.
 * Used by Keywhiz CLI and the web ui.
 * @responseMessage 200 Found and deleted Group with given ID
 * @responseMessage 404 Group with given ID not Found
 */
@Path("{groupId}")
@Timed
@ExceptionMetered
@DELETE
public Response deleteGroup(@Auth User user, @PathParam("groupId") LongParam groupId) {
    logger.info("User '{}' deleting group id={}.", user, groupId);

    Optional<Group> group = groupDAO.getGroupById(groupId.get());
    if (!group.isPresent()) {
        throw new NotFoundException("Group not found.");
    }

    groupDAO.deleteGroup(group.get());
    auditLog.recordEvent(
            new Event(Instant.now(), EventTag.GROUP_DELETE, user.getName(), group.get().getName()));
    return Response.noContent().build();
}

From source file:com.netflix.genie.common.dto.JobRequestTest.java

/**
 * Test to make sure can build a valid JobRequest with optional parameters.
 *///from  w  ww. ja  v a 2 s.c  o  m
@Test
@SuppressWarnings("deprecation")
public void canBuildJobRequestWithOptionalsDeprecated() {
    final JobRequest.Builder builder = new JobRequest.Builder(NAME, USER, VERSION, CLUSTER_CRITERIAS,
            COMMAND_CRITERIA);

    builder.withCommandArgs(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE));

    final int cpu = 5;
    builder.withCpu(cpu);

    final boolean disableLogArchival = true;
    builder.withDisableLogArchival(disableLogArchival);

    final String email = UUID.randomUUID().toString() + "@netflix.com";
    builder.withEmail(email);

    final Set<String> configs = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString(),
            UUID.randomUUID().toString());
    builder.withConfigs(configs);

    final Set<String> dependencies = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString(),
            UUID.randomUUID().toString());
    builder.withDependencies(dependencies);

    final String group = UUID.randomUUID().toString();
    builder.withGroup(group);

    final int memory = 2048;
    builder.withMemory(memory);

    final String setupFile = UUID.randomUUID().toString();
    builder.withSetupFile(setupFile);

    final Instant created = Instant.now();
    builder.withCreated(created);

    final String description = UUID.randomUUID().toString();
    builder.withDescription(description);

    final String id = UUID.randomUUID().toString();
    builder.withId(id);

    final Set<String> tags = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString(),
            UUID.randomUUID().toString());
    builder.withTags(tags);

    final Instant updated = Instant.now();
    builder.withUpdated(updated);

    final List<String> applications = Lists.newArrayList(UUID.randomUUID().toString(),
            UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString());
    builder.withApplications(applications);

    final int timeout = 8970243;
    builder.withTimeout(timeout);

    final String grouping = UUID.randomUUID().toString();
    builder.withGrouping(grouping);

    final String groupingInstance = UUID.randomUUID().toString();
    builder.withGroupingInstance(groupingInstance);

    final JobRequest request = builder.build();
    Assert.assertThat(request.getName(), Matchers.is(NAME));
    Assert.assertThat(request.getUser(), Matchers.is(USER));
    Assert.assertThat(request.getVersion(), Matchers.is(VERSION));
    Assert.assertThat(request.getCommandArgs().orElseThrow(IllegalArgumentException::new),
            Matchers.is(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE)));
    Assert.assertThat(request.getClusterCriterias(), Matchers.is(CLUSTER_CRITERIAS));
    Assert.assertThat(request.getCommandCriteria(), Matchers.is(COMMAND_CRITERIA));
    Assert.assertThat(request.getCpu().orElseThrow(IllegalArgumentException::new), Matchers.is(cpu));
    Assert.assertThat(request.isDisableLogArchival(), Matchers.is(disableLogArchival));
    Assert.assertThat(request.getEmail().orElseThrow(IllegalArgumentException::new), Matchers.is(email));
    Assert.assertThat(request.getConfigs(), Matchers.is(configs));
    Assert.assertThat(request.getDependencies(), Matchers.is(dependencies));
    Assert.assertThat(request.getGroup().orElseThrow(IllegalArgumentException::new), Matchers.is(group));
    Assert.assertThat(request.getMemory().orElseThrow(IllegalArgumentException::new), Matchers.is(memory));
    Assert.assertThat(request.getSetupFile().orElseThrow(IllegalArgumentException::new),
            Matchers.is(setupFile));
    Assert.assertThat(request.getCreated().orElseThrow(IllegalArgumentException::new), Matchers.is(created));
    Assert.assertThat(request.getDescription().orElseThrow(IllegalArgumentException::new),
            Matchers.is(description));
    Assert.assertThat(request.getId().orElseThrow(IllegalArgumentException::new), Matchers.is(id));
    Assert.assertThat(request.getTags(), Matchers.is(tags));
    Assert.assertThat(request.getUpdated().orElseThrow(IllegalArgumentException::new), Matchers.is(updated));
    Assert.assertThat(request.getApplications(), Matchers.is(applications));
    Assert.assertThat(request.getTimeout().orElseThrow(IllegalArgumentException::new), Matchers.is(timeout));
    Assert.assertThat(request.getGrouping().orElseThrow(IllegalArgumentException::new), Matchers.is(grouping));
    Assert.assertThat(request.getGroupingInstance().orElseThrow(IllegalArgumentException::new),
            Matchers.is(groupingInstance));
}

From source file:de.siegmar.securetransfer.controller.SendController.java

private List<SecretFile> handleStream(final HttpServletRequest req, final KeyIv encryptionKey,
        final DataBinder binder) throws FileUploadException, IOException {

    final BindingResult errors = binder.getBindingResult();

    final MutablePropertyValues propertyValues = new MutablePropertyValues();
    final List<SecretFile> tmpFiles = new ArrayList<>();

    @SuppressWarnings("checkstyle:anoninnerlength")
    final AbstractMultipartVisitor visitor = new AbstractMultipartVisitor() {

        private OptionalInt expiration = OptionalInt.empty();

        @Override/*from w  w  w .  j a  v a 2s  .  c  o m*/
        void emitField(final String name, final String value) {
            propertyValues.addPropertyValue(name, value);

            if ("expirationDays".equals(name)) {
                expiration = OptionalInt.of(Integer.parseInt(value));
            }
        }

        @Override
        void emitFile(final String fileName, final InputStream inStream) {
            final Integer expirationDays = expiration
                    .orElseThrow(() -> new IllegalStateException("No expirationDays configured"));

            tmpFiles.add(messageService.encryptFile(fileName, inStream, encryptionKey,
                    Instant.now().plus(expirationDays, ChronoUnit.DAYS)));
        }

    };

    try {
        visitor.processRequest(req);
        binder.bind(propertyValues);
        binder.validate();
    } catch (final IllegalStateException ise) {
        errors.reject(null, ise.getMessage());
    }

    return tmpFiles;
}