Example usage for java.time ZonedDateTime now

List of usage examples for java.time ZonedDateTime now

Introduction

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

Prototype

public static ZonedDateTime now() 

Source Link

Document

Obtains the current date-time from the system clock in the default time-zone.

Usage

From source file:org.hawkular.accounts.api.model.BaseEntity.java

public void setUpdatedAt() {
    this.updatedAt = ZonedDateTime.now();
}

From source file:com.amazon.alexa.avs.AlertsFileDataStore.java

@Override
public synchronized void loadFromDisk(AlertManager manager, final ResultListener listener) {
    sExecutor.execute(new Runnable() {
        @Override/*from   w ww  . jav a 2  s.  c  o m*/
        public void run() {
            FileReader fis = null;
            BufferedReader br = null;
            JsonReader parser = null;

            ObjectReader reader = ObjectMapperFactory.getObjectReader()
                    .withType(new TypeReference<List<Alert>>() {
                    });
            List<Alert> droppedAlerts = new LinkedList<Alert>();
            try {
                fis = new FileReader(ALARM_FILE);
                br = new BufferedReader(fis);

                List<Alert> alerts = reader.readValue(br);
                for (Alert alert : alerts) {
                    // Only add alerts that are within the expiration window
                    if (alert.getScheduledTime()
                            .isAfter(ZonedDateTime.now().minusMinutes(MINUTES_AFTER_PAST_ALERT_EXPIRES))) {
                        manager.add(alert, true);
                    } else {
                        droppedAlerts.add(alert);
                    }
                }
                // Now that all the valid alerts have been re-added to the alarm manager,
                // go through and explicitly drop all the alerts that were not added
                for (Alert alert : droppedAlerts) {
                    manager.drop(alert);
                }
                listener.onSuccess();
            } catch (FileNotFoundException e) {
                // This is not a fatal error
                // The alarm file might not have been created yet
                listener.onSuccess();
            } catch (IOException e) {
                log.error("Failed to load alerts from disk.", e);
                listener.onFailure();
            } finally {
                IOUtils.closeQuietly(parser);
                IOUtils.closeQuietly(br);
            }
        }
    });
}

From source file:tld.mydomain.example.core.service.ExampleAccountService.java

@Transactional
public void createAccount(ExampleAccount newAccount, String newPassword) {
    if (null != newAccount.getId()) {
        throw new RuntimeException("Cannot create account: account already persisted.");
    }//w w w.  j a  v  a  2  s .com

    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    newAccount.setPassword(encoder.encode(newPassword));

    newAccount.setEmailConfirmCode(UUID.randomUUID().toString());
    newAccount.setEmailConfirmed(true);
    newAccount.setEmailConfirmedDate(ZonedDateTime.now());

    newAccount.setEnabled(true);

    accountRepository.save(newAccount);
}

From source file:com.github.ibm.domino.client.CalendarClientTest.java

/**
 * Test of getEvents method, of class CalendarClient.
 *//*  w  w w .  j  a va  2  s  .c om*/
@Test
public void test2GetEvents() {
    System.out.println("getEvents");
    DominoRestClient instance = initClient();
    instance.since(ZonedDateTime.now());
    List<CalendarEvent> result = instance.getEvents();
    assertTrue(result != null && !result.isEmpty());
    result.stream().forEach((calendarEvent) -> {
        System.out.println(calendarEvent.toString());
        System.out.println(calendarEvent.getStart().getEventDateTime());
    });
}

From source file:org.sonatype.nexus.tasklog.TaskLogCleanupTest.java

private File createFile(final String name, final int ageInDays) throws IOException {
    File file = new File(tempTaskFolder, name);
    file.createNewFile();//www  .ja va  2 s .c om
    file.setLastModified(ZonedDateTime.now().minusDays(ageInDays).toInstant().toEpochMilli());
    return file;
}

From source file:org.craftercms.deployer.impl.TargetImpl.java

public TargetImpl(String env, String siteName, DeploymentPipeline deploymentPipeline, File configurationFile,
        Configuration configuration, ConfigurableApplicationContext applicationContext) {
    this.env = env;
    this.siteName = siteName;
    this.deploymentPipeline = deploymentPipeline;
    this.configurationFile = configurationFile;
    this.configuration = configuration;
    this.applicationContext = applicationContext;
    this.loadDate = ZonedDateTime.now();
    this.deploymentExecutor = Executors.newSingleThreadExecutor();
    this.pendingDeployments = new ConcurrentLinkedQueue<>();
}

From source file:keepinchecker.network.PacketSniffer.java

private void sendPacketsToDatabase(Map<Timestamp, Packet> packetMap) throws Exception {
    Set<KeepInCheckerPacket> objectionablePackets = new HashSet<>();

    for (Map.Entry<Timestamp, Packet> entry : packetMap.entrySet()) {
        Timestamp packetTime = entry.getKey();
        ZoneId currentTimezone = ZonedDateTime.now().getZone();
        String packetString = PacketParser.convertToHumanReadableFormat(entry.getValue());

        for (String objectionableWord : Constants.OBJECTIONABLE_WORDS) {
            if (StringUtils.contains(packetString, objectionableWord)) {
                KeepInCheckerPacket packet = new KeepInCheckerPacket();

                packet.setTimestamp(packetTime.getTime());
                packet.setTimezone(currentTimezone.getId());

                String parsedGetValue = PacketParser.parse(PacketParser.GET, packetString);
                String parsedHostValue = PacketParser.parse(PacketParser.HOST, packetString);
                String parsedReferValue = PacketParser.parse(PacketParser.REFERER, packetString);
                packet.setGetValue(parsedGetValue.getBytes(StandardCharsets.UTF_8));
                packet.setHostValue(parsedHostValue.getBytes(StandardCharsets.UTF_8));
                packet.setRefererValue(parsedReferValue.getBytes(StandardCharsets.UTF_8));

                if (!areGetHostAndRefererValuesEmpty(packet)) {
                    objectionablePackets.add(packet);
                }//from  w w w.java2  s  .co  m

                break;
            }
        }
    }

    if (!objectionablePackets.isEmpty()) {
        packetManager.savePackets(objectionablePackets);
    }
}

From source file:com.cosmicpush.pub.push.LqNotificationPush.java

@Deprecated
public static LqNotificationPush newPushV1(String summary, String callbackUrl, String remoteHost,
        String remoteAddress, Map<String, String> traits) {

    return new LqNotificationPush("unit-test", summary, null, ZonedDateTime.now(), null,
            Collections.emptyList(), callbackUrl, remoteHost, remoteAddress, traits);
}

From source file:de.rkl.tools.tzconv.model.ApplicationModel.java

@SuppressWarnings("unused")
@PostConstruct//from   w w w .j a  v a2 s.c  om
public void fillProperties() {
    mainDateTime.setValue(ZonedDateTime.now().withHour(DEFAULT_INITIAL_HOUR).withMinute(DEFAULT_INITIAL_MINUTE)
            .withZoneSameLocal(preferencesProvider.getPreferredReferenceZoneIdIfSet()));
    selectedZoneIds.setValue(getInitialZoneIds());
    templateFile.setValue(preferencesProvider.getPreferredTemplateFile());
    sortSelectedZoneIds();
}

From source file:org.thingsboard.server.service.security.model.token.JwtTokenFactory.java

/**
 * Factory method for issuing new JWT Tokens.
 *//*w w  w  .ja v a 2  s. co  m*/
public AccessJwtToken createAccessJwtToken(SecurityUser securityUser) {
    if (StringUtils.isBlank(securityUser.getEmail()))
        throw new IllegalArgumentException("Cannot create JWT Token without username/email");

    if (securityUser.getAuthority() == null)
        throw new IllegalArgumentException("User doesn't have any privileges");

    UserPrincipal principal = securityUser.getUserPrincipal();
    String subject = principal.getValue();
    Claims claims = Jwts.claims().setSubject(subject);
    claims.put(SCOPES, securityUser.getAuthorities().stream().map(GrantedAuthority::getAuthority)
            .collect(Collectors.toList()));
    claims.put(USER_ID, securityUser.getId().getId().toString());
    claims.put(FIRST_NAME, securityUser.getFirstName());
    claims.put(LAST_NAME, securityUser.getLastName());
    claims.put(ENABLED, securityUser.isEnabled());
    claims.put(IS_PUBLIC, principal.getType() == UserPrincipal.Type.PUBLIC_ID);
    if (securityUser.getTenantId() != null) {
        claims.put(TENANT_ID, securityUser.getTenantId().getId().toString());
    }
    if (securityUser.getCustomerId() != null) {
        claims.put(CUSTOMER_ID, securityUser.getCustomerId().getId().toString());
    }

    ZonedDateTime currentTime = ZonedDateTime.now();

    String token = Jwts.builder().setClaims(claims).setIssuer(settings.getTokenIssuer())
            .setIssuedAt(Date.from(currentTime.toInstant()))
            .setExpiration(Date.from(currentTime.plusSeconds(settings.getTokenExpirationTime()).toInstant()))
            .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey()).compact();

    return new AccessJwtToken(token, claims);
}