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:me.ryanhamshire.griefprevention.migrator.RedProtectMigrator.java

public static void migrate(World world, Path redProtectFilePath, Path gpClaimDataPath)
        throws FileNotFoundException, ClassNotFoundException {
    if (!GriefPreventionPlugin.getGlobalConfig().getConfig().migrator.redProtectMigrator) {
        return;//from   w w w . java  2  s.c  om
    }

    int count = 0;
    try {
        GriefPreventionPlugin.instance.getLogger().info("Starting RedProtect region data migration for world "
                + world.getProperties().getWorldName() + "...");
        ConfigurationLoader<CommentedConfigurationNode> regionManager = HoconConfigurationLoader.builder()
                .setPath(redProtectFilePath).build();
        CommentedConfigurationNode region = regionManager.load();
        GriefPreventionPlugin.instance.getLogger()
                .info("Scanning RedProtect regions in world data file '" + redProtectFilePath + "'...");
        for (Object key : region.getChildrenMap().keySet()) {
            String rname = key.toString();
            if (!region.getNode(rname).hasMapChildren()) {
                continue;
            }
            int maxX = region.getNode(rname, "maxX").getInt();
            int maxY = region.getNode(rname, "maxY").getInt(255);
            int maxZ = region.getNode(rname, "maxZ").getInt();
            int minX = region.getNode(rname, "minX").getInt();
            int minY = region.getNode(rname, "minY").getInt(0);
            int minZ = region.getNode(rname, "minZ").getInt();
            List<String> owners = new ArrayList<String>();
            owners.addAll(region.getNode(rname, "owners").getList(TypeToken.of(String.class)));

            List<String> members = new ArrayList<String>();
            members.addAll(region.getNode(rname, "members").getList(TypeToken.of(String.class)));

            String creator = region.getNode(rname, "creator").getString();
            String welcome = region.getNode(rname, "welcome").getString();

            // create GP claim data file
            GriefPreventionPlugin.instance.getLogger()
                    .info("Migrating RedProtect region data '" + rname + "'...");
            UUID ownerUniqueId = null;
            if (validate(creator)) {
                try {
                    // check cache first
                    ownerUniqueId = PlayerUtils.getUUIDByName(creator);
                    if (ownerUniqueId == null) {
                        ownerUniqueId = UUID.fromString(getUUID(creator));
                    }
                } catch (Throwable e) {
                    // assume admin claim
                }
            }

            UUID claimUniqueId = UUID.randomUUID();
            Location<World> lesserBoundaryCorner = new Location<>(world, minX, minY, minZ);
            Location<World> greaterBoundaryCorner = new Location<>(world, maxX, maxY, maxZ);
            Path claimFilePath = gpClaimDataPath.resolve(claimUniqueId.toString());
            if (!Files.exists(claimFilePath)) {
                Files.createFile(claimFilePath);
            }

            ClaimStorageData claimStorage = new ClaimStorageData(claimFilePath);
            ClaimDataConfig claimDataConfig = claimStorage.getConfig();
            claimDataConfig.setName(Text.of(rname));
            claimDataConfig.setWorldUniqueId(world.getUniqueId());
            claimDataConfig.setOwnerUniqueId(ownerUniqueId);
            claimDataConfig.setLesserBoundaryCorner(BlockUtils.positionToString(lesserBoundaryCorner));
            claimDataConfig.setGreaterBoundaryCorner(BlockUtils.positionToString(greaterBoundaryCorner));
            claimDataConfig.setDateLastActive(Instant.now());
            claimDataConfig.setType(ownerUniqueId == null ? ClaimType.ADMIN : ClaimType.BASIC);
            if (!welcome.equals("")) {
                claimDataConfig.setGreeting(Text.of(welcome));
            }
            List<String> rpUsers = new ArrayList<>(owners);
            rpUsers.addAll(members);
            List<UUID> builders = claimDataConfig.getBuilders();
            for (String builder : rpUsers) {
                if (!validate(builder)) {
                    continue;
                }

                UUID builderUniqueId = null;
                try {
                    builderUniqueId = PlayerUtils.getUUIDByName(builder);
                    if (builderUniqueId == null) {
                        builderUniqueId = UUID.fromString(getUUID(builder));
                    }
                } catch (Throwable e) {
                    GriefPreventionPlugin.instance.getLogger().error("Could not locate a valid UUID for user '"
                            + builder + "' in region '" + rname + "'. Skipping...");
                    continue;
                }
                if (!builders.contains(builderUniqueId) && ownerUniqueId != null
                        && !builderUniqueId.equals(ownerUniqueId)) {
                    builders.add(builderUniqueId);
                }
            }

            claimDataConfig.setRequiresSave(true);
            claimStorage.save();
            GriefPreventionPlugin.instance.getLogger().info(
                    "Successfully migrated RedProtect region data '" + rname + "' to '" + claimFilePath + "'");
            count++;
        }
        GriefPreventionPlugin.instance.getLogger().info("Finished RedProtect region data migration for world '"
                + world.getProperties().getWorldName() + "'." + " Migrated a total of " + count + " regions.");
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ObjectMappingException e) {
        e.printStackTrace();
    }
}

From source file:io.kamax.mxisd.controller.DefaultExceptionHandler.java

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(RuntimeException.class)
public String handle(HttpServletRequest req, RuntimeException e) {
    log.error("Unknown error when handling {}", req.getRequestURL(), e);
    return handle(req, "M_UNKNOWN", StringUtils.defaultIfBlank(e.getMessage(),
            "An internal server error occurred. If this error persists, please contact support with reference #"
                    + Instant.now().toEpochMilli()));
}

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

@Test
public void removeRegistrationTest() throws URISyntaxException, RegistrationPersistenceException {
    RegisterContext registerContext = createRegisterContextTemperature();
    registerContext.setRegistrationId("12345");
    Registration registration = new Registration(Instant.now().plus(1, ChronoUnit.DAYS), registerContext);
    registrationsRepository.saveRegistration(registration);
    Assert.assertEquals(1, registrationsRepository.getAllRegistrations().size());
    registrationsRepository.removeRegistration("12345");
    Assert.assertEquals(0, registrationsRepository.getAllRegistrations().size());
}

From source file:com.orange.cepheus.broker.Subscriptions.java

/**
 * Removed all expired subscriptions every minute.
 *//*from w ww .j a v  a2  s  .  c o  m*/
@Scheduled(fixedDelay = 60000)
public void purgeExpiredSubscriptions() {
    final Instant now = Instant.now();
    subscriptions.forEach((subscriptionId, subscribeContext) -> {
        if (subscribeContext.getExpirationDate().isBefore(now)) {
            subscriptions.remove(subscriptionId);
            try {
                subscriptionsRepository.removeSubscription(subscriptionId);
            } catch (SubscriptionPersistenceException e) {
                logger.error("Failed to remove subscription from database", e);
            }
        }
    });
}

From source file:com.searchcode.app.jobs.repository.IndexBaseRepoJob.java

/**
 * The main method used for finding jobs to index and actually doing the work
 *//* w w  w. j ava  2 s. co m*/
public void execute(JobExecutionContext context) throws JobExecutionException {
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();

    this.LOWMEMORY = Boolean.parseBoolean(jobDataMap.get("LOWMEMORY").toString());
    String repoLocations = jobDataMap.get("REPOLOCATIONS").toString();

    if (!isEnabled() || !this.sharedService.getBackgroundJobsEnabled()) {
        return;
    }

    if (this.codeIndexer.shouldPauseAdding()) {
        Singleton.getLogger().info("Pausing parser.");
        return;
    }

    // Pull the next repo to index from the queue
    RepoResult repoResult = this.getNextQueuedRepo().poll();

    if (repoResult != null && Singleton.getRunningIndexRepoJobs().containsKey(repoResult.getName()) == false) {
        this.haveRepoResult = true;
        Singleton.getLogger().info("Indexing " + repoResult.getName());
        repoResult.getData().indexStatus = "indexing";
        repoResult.getData().jobRunTime = Instant.now();
        Singleton.getRepo().saveRepo(repoResult);

        try {
            Singleton.getRunningIndexRepoJobs().put(repoResult.getName(),
                    new RunningIndexJob("Indexing", Singleton.getHelpers().getCurrentTimeSeconds()));

            this.checkCloneSuccess(repoResult.getName(), repoLocations);

            String repoGitLocation = repoLocations + "/" + repoResult.getName() + "/.git/";

            File file = new File(repoGitLocation);
            boolean existingRepo = file.exists();
            boolean useCredentials = repoResult.getUsername() != null && !repoResult.getUsername().isEmpty();
            RepositoryChanged repositoryChanged;

            if (existingRepo) {
                repositoryChanged = this.updateExistingRepository(repoResult.getName(), repoResult.getUrl(),
                        repoResult.getUsername(), repoResult.getPassword(), repoLocations,
                        repoResult.getBranch(), useCredentials);
            } else {
                repositoryChanged = this.getNewRepository(repoResult.getName(), repoResult.getUrl(),
                        repoResult.getUsername(), repoResult.getPassword(), repoLocations,
                        repoResult.getBranch(), useCredentials);
            }

            // Write file indicating we have sucessfully cloned
            this.createCloneUpdateSuccess(repoLocations + "/" + repoResult.getName());
            this.triggerIndex(repoResult, repoResult.getName(), repoResult.getUrl(), repoLocations,
                    repoGitLocation, existingRepo, repositoryChanged);
        } finally {
            // Clean up the job
            Singleton.getRunningIndexRepoJobs().remove(repoResult.getName());
        }
    }
}

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

/**
 * {@inheritDoc}//from  w  w w.ja v a 2  s .  co  m
 */
@Override
public long getLastModifiedTime(final String path) throws GenieException {
    final long start = System.nanoTime();
    try {
        final URL url = new URL(path);
        final long time = this.restTemplate.headForHeaders(url.toURI()).getLastModified();
        // Returns now if there was no last modified header as best we can do is assume file is brand new
        return time != -1 ? time : Instant.now().toEpochMilli();
    } catch (final MalformedURLException | URISyntaxException e) {
        log.error(e.getLocalizedMessage(), e);
        throw new GenieServerException(e);
    } finally {
        this.getLastModifiedTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    }
}

From source file:co.runrightfast.vertx.core.eventbus.ProtobufMessageProducer.java

public <RESPONSE> void send(@NonNull final A msg,
        @NonNull final Handler<AsyncResult<io.vertx.core.eventbus.Message<RESPONSE>>> handler) {
    eventBus.send(address, msg, addRunRightFastHeaders(new DeliveryOptions()), handler);
    this.messageSent.mark();
    this.messageLastSent = Instant.now();
}

From source file:com.khartec.waltz.data.application.ApplicationDao.java

public AppRegistrationResponse registerApp(AppRegistrationRequest request) {

    checkNotEmptyString(request.name(), "Cannot register app with no name");

    LOG.info("Registering new application: " + request);

    ApplicationRecord record = dsl.newRecord(APPLICATION);

    record.setName(request.name());//ww w. ja  v  a2  s  . com
    record.setDescription(request.description().orElse("TBC"));
    record.setAssetCode(request.assetCode().orElse(""));
    record.setParentAssetCode(request.parentAssetCode().orElse(""));
    record.setOrganisationalUnitId(request.organisationalUnitId());
    record.setKind(request.kind().name());
    record.setLifecyclePhase(request.lifecyclePhase().name());
    record.setOverallRating(request.overallRating().name());
    record.setUpdatedAt(Timestamp.from(Instant.now()));

    try {
        int count = record.insert();

        if (count == 1) {
            return ImmutableAppRegistrationResponse.builder().id(record.getId()).message("created")
                    .originalRequest(request).build();
        } else {
            return ImmutableAppRegistrationResponse.builder().message("Failed").originalRequest(request)
                    .build();
        }

    } catch (DataAccessException dae) {
        return ImmutableAppRegistrationResponse.builder()
                .message("Could not create app because: " + dae.getMessage()).originalRequest(request).build();
    }
}

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

/**
 * Create Client/*www. ja  v a2s .  c  o m*/
 *
 * @excludeParams user
 * @param createClientRequest the JSON client request used to formulate the Client
 *
 * @description Creates a Client with the name from a valid client request.
 * Used by Keywhiz CLI and the web ui.
 * @responseMessage 200 Successfully created Client
 * @responseMessage 409 Client with given name already exists
 */
@Timed
@ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Response createClient(@Auth User user, @Valid CreateClientRequest createClientRequest) {

    logger.info("User '{}' creating client '{}'.", user, createClientRequest.name);

    long clientId;
    try {
        clientId = clientDAO.createClient(createClientRequest.name, user.getName(), "");
    } catch (DataAccessException e) {
        logger.warn("Cannot create client {}: {}", createClientRequest.name, e);
        throw new ConflictException("Conflict creating client.");
    }

    URI uri = UriBuilder.fromResource(ClientsResource.class).path("{clientId}").build(clientId);
    Response response = Response.created(uri).entity(clientDetailResponseFromId(clientId)).build();
    if (response.getStatus() == HttpStatus.SC_CREATED) {
        auditLog.recordEvent(
                new Event(Instant.now(), EventTag.CLIENT_CREATE, user.getName(), createClientRequest.name));
    }
    return response;
}

From source file:be.neutrinet.ispng.vpn.api.VPNClientConfig.java

protected Representation finalizeZip(List<String> config, ZipOutputStream zip, ByteArrayOutputStream baos)
        throws Exception {
    String file = "";
    for (String s : config) {
        file += s + '\n';
    }/* w w w  . j  av  a2 s . c o m*/

    if (caCert == null) {
        caCert = IOUtils.toByteArray(new FileInputStream(VPN.cfg.getProperty("ca.crt")));
    }

    ZipEntry configFile = new ZipEntry("neutrinet.ovpn");
    configFile.setCreationTime(FileTime.from(Instant.now()));
    zip.putNextEntry(configFile);
    zip.write(file.getBytes());
    zip.putNextEntry(new ZipEntry("ca.crt"));
    zip.write(caCert);

    zip.close();

    ByteArrayRepresentation rep = new ByteArrayRepresentation(baos.toByteArray());
    rep.setMediaType(MediaType.APPLICATION_ZIP);
    rep.setSize(baos.size());
    rep.setCharacterSet(CharacterSet.UTF_8);
    rep.setDisposition(new Disposition(Disposition.TYPE_ATTACHMENT));
    return rep;
}