Example usage for java.time.temporal ChronoUnit SECONDS

List of usage examples for java.time.temporal ChronoUnit SECONDS

Introduction

In this page you can find the example usage for java.time.temporal ChronoUnit SECONDS.

Prototype

ChronoUnit SECONDS

To view the source code for java.time.temporal ChronoUnit SECONDS.

Click Source Link

Document

Unit that represents the concept of a second.

Usage

From source file:me.ryanhamshire.griefprevention.command.CommandHelper.java

public static Consumer<CommandSource> createBankTransactionsConsumer(CommandSource src, GPClaim claim,
        boolean checkTown, boolean returnToClaimInfo) {
    return settings -> {
        final String name = "Bank Transactions";
        List<String> bankTransactions = new ArrayList<>(
                claim.getData().getEconomyData().getBankTransactionLog());
        Collections.reverse(bankTransactions);
        List<Text> textList = new ArrayList<>();
        textList.add(/*  w w  w .  jav a  2 s .c om*/
                Text.builder().append(Text.of(TextColors.WHITE, "\n[", TextColors.AQUA, "Return to bank info",
                        TextColors.WHITE, "]\n")).onClick(TextActions.executeCallback(consumer -> {
                            displayClaimBankInfo(src, claim, checkTown, returnToClaimInfo);
                        })).build());
        Gson gson = new Gson();
        for (String transaction : bankTransactions) {
            GPBankTransaction bankTransaction = gson.fromJson(transaction, GPBankTransaction.class);
            final Duration duration = Duration.between(bankTransaction.timestamp,
                    Instant.now().truncatedTo(ChronoUnit.SECONDS));
            final long s = duration.getSeconds();
            final User user = GriefPreventionPlugin.getOrCreateUser(bankTransaction.source);
            final String timeLeft = String.format("%dh %02dm %02ds", s / 3600, (s % 3600) / 60, (s % 60))
                    + " ago";
            textList.add(Text.of(getTransactionColor(bankTransaction.type), bankTransaction.type.name(),
                    TextColors.BLUE, " | ", TextColors.WHITE, bankTransaction.amount, TextColors.BLUE, " | ",
                    TextColors.GRAY, timeLeft, user == null ? ""
                            : Text.of(TextColors.BLUE, " | ", TextColors.LIGHT_PURPLE, user.getName())));
        }
        textList.add(Text.builder()
                .append(Text.of(TextColors.WHITE, "\n[", TextColors.AQUA, "Return to bank info",
                        TextColors.WHITE, "]\n"))
                .onClick(TextActions.executeCallback(CommandHelper.createCommandConsumer(src, "claimbank", "")))
                .build());
        PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
        PaginationList.Builder paginationBuilder = paginationService.builder()
                .title(Text.of(TextColors.AQUA, name)).padding(Text.of(TextStyles.STRIKETHROUGH, "-"))
                .contents(textList);
        paginationBuilder.sendTo(src);
    };
}

From source file:org.apache.archiva.repository.maven2.MavenRepositoryProvider.java

@Override
public RemoteRepositoryConfiguration getRemoteConfiguration(RemoteRepository remoteRepository)
        throws RepositoryException {
    if (!(remoteRepository instanceof MavenRemoteRepository)) {
        log.error("Wrong remote repository type " + remoteRepository.getClass().getName());
        throw new RepositoryException("The given repository type cannot be handled by the maven provider: "
                + remoteRepository.getClass().getName());
    }/*from   w  ww  .  ja va 2  s.c  om*/
    RemoteRepositoryConfiguration cfg = new RemoteRepositoryConfiguration();
    cfg.setType(remoteRepository.getType().toString());
    cfg.setId(remoteRepository.getId());
    cfg.setName(remoteRepository.getName());
    cfg.setDescription(remoteRepository.getDescription());
    cfg.setUrl(remoteRepository.getLocation().toString());
    cfg.setTimeout((int) remoteRepository.getTimeout().toMillis() / 1000);
    cfg.setCheckPath(remoteRepository.getCheckPath());
    RepositoryCredentials creds = remoteRepository.getLoginCredentials();
    if (creds != null) {
        if (creds instanceof PasswordCredentials) {
            PasswordCredentials pCreds = (PasswordCredentials) creds;
            cfg.setPassword(new String(pCreds.getPassword()));
            cfg.setUsername(pCreds.getUsername());
        }
    }
    cfg.setLayout(remoteRepository.getLayout());
    cfg.setExtraParameters(remoteRepository.getExtraParameters());
    cfg.setExtraHeaders(remoteRepository.getExtraHeaders());
    cfg.setRefreshCronExpression(remoteRepository.getSchedulingDefinition());

    IndexCreationFeature indexCreationFeature = remoteRepository.getFeature(IndexCreationFeature.class).get();
    cfg.setIndexDir(convertUriToPath(indexCreationFeature.getIndexPath()));
    cfg.setPackedIndexDir(convertUriToPath(indexCreationFeature.getPackedIndexPath()));

    RemoteIndexFeature remoteIndexFeature = remoteRepository.getFeature(RemoteIndexFeature.class).get();
    cfg.setRemoteIndexUrl(remoteIndexFeature.getIndexUri().toString());
    cfg.setRemoteDownloadTimeout((int) remoteIndexFeature.getDownloadTimeout().get(ChronoUnit.SECONDS));
    cfg.setDownloadRemoteIndexOnStartup(remoteIndexFeature.isDownloadRemoteIndexOnStartup());
    cfg.setDownloadRemoteIndex(remoteIndexFeature.isDownloadRemoteIndex());
    cfg.setRemoteDownloadNetworkProxyId(remoteIndexFeature.getProxyId());

    return cfg;

}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.JWTSecurityHandler.java

@Override
public void init(Configuration config) throws Exception {
    LOG.info("Initializing JWT Security Handler");
    this.config = config;
    jwtEnabled = config.getBoolean(YarnConfiguration.RM_JWT_ENABLED, YarnConfiguration.DEFAULT_RM_JWT_ENABLED);
    jwtAudience = config.getTrimmedStrings(YarnConfiguration.RM_JWT_AUDIENCE,
            YarnConfiguration.DEFAULT_RM_JWT_AUDIENCE);
    renewalExecutorService = rmAppSecurityManager.getRenewalExecutorService();
    String validity = config.get(YarnConfiguration.RM_JWT_VALIDITY_PERIOD,
            YarnConfiguration.DEFAULT_RM_JWT_VALIDITY_PERIOD);
    validityPeriod = rmAppSecurityManager.parseInterval(validity, YarnConfiguration.RM_JWT_VALIDITY_PERIOD);
    String expirationLeewayConf = config.get(YarnConfiguration.RM_JWT_EXPIRATION_LEEWAY,
            YarnConfiguration.DEFAULT_RM_JWT_EXPIRATION_LEEWAY);
    Pair<Long, TemporalUnit> expirationLeeway = rmAppSecurityManager.parseInterval(expirationLeewayConf,
            YarnConfiguration.RM_JWT_EXPIRATION_LEEWAY);
    if (((ChronoUnit) expirationLeeway.getSecond()).compareTo(ChronoUnit.SECONDS) < 0) {
        throw new IllegalArgumentException(
                "Value of " + YarnConfiguration.RM_JWT_EXPIRATION_LEEWAY + " should be at least seconds");
    }/* w  w w .  j a va  2  s  .c o m*/
    leeway = Duration.of(expirationLeeway.getFirst(), expirationLeeway.getSecond()).getSeconds();
    if (jwtEnabled) {
        rmAppSecurityActions = rmAppSecurityManager.getRmAppCertificateActions();
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java

@Test
public void testRenewJWT() throws Exception {
    ApplicationId appId = ApplicationId.newInstance(System.currentTimeMillis(), 1);
    JWTSecurityHandler.JWTMaterialParameter jwtParam0 = createJWTParameter(appId, 2, ChronoUnit.SECONDS);
    RMAppSecurityActions actor = RMAppSecurityActionsFactory.getInstance().getActor(conf);
    String jwt0 = actor.generateJWT(jwtParam0);

    TimeUnit.SECONDS.sleep(2);/*  w  w w.  j a v  a  2  s  .  com*/

    JWTSecurityHandler.JWTMaterialParameter jwtParam1 = createJWTParameter(appId);
    jwtParam1.setToken(jwt0);
    String jwt1 = actor.renewJWT(jwtParam1);
    Assert.assertNotNull(jwt1);
    Assert.assertNotEquals(jwt0, jwt1);
    LOG.info(jwt0);
    LOG.info(jwt1);
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestX509SecurityHandler.java

@Test
public void testCertificateRenewal() throws Exception {
    conf.set(YarnConfiguration.HOPS_RM_SECURITY_ACTOR_KEY,
            "org.apache.hadoop.yarn.server.resourcemanager.security.TestingRMAppSecurityActions");
    RMAppSecurityManager rmAppSecurityManager = new RMAppSecurityManager(rmContext);
    MockX509SecurityHandler x509SecurityHandler = new MockX509SecurityHandler(rmContext, rmAppSecurityManager,
            false);/*from  w  w  w.j ava 2s  .  c  o m*/
    rmAppSecurityManager.registerRMAppSecurityHandler(x509SecurityHandler);
    rmAppSecurityManager.init(conf);
    rmAppSecurityManager.start();

    LocalDateTime now = DateUtils.getNow();
    LocalDateTime expiration = now.plus(10, ChronoUnit.SECONDS);
    ApplicationId appId = ApplicationId.newInstance(DateUtils.localDateTime2UnixEpoch(now), 1);
    x509SecurityHandler.setOldCertificateExpiration(DateUtils.localDateTime2UnixEpoch(expiration));

    X509SecurityHandler.X509MaterialParameter x509Param = new X509SecurityHandler.X509MaterialParameter(appId,
            "Dolores", 1);
    x509Param.setExpiration(DateUtils.localDateTime2UnixEpoch(expiration));
    x509SecurityHandler.registerRenewer(x509Param);
    Map<ApplicationId, ScheduledFuture> tasks = x509SecurityHandler.getRenewalTasks();
    ScheduledFuture renewalTask = tasks.get(appId);
    assertFalse(renewalTask.isCancelled());
    assertFalse(renewalTask.isDone());

    // Wait until the scheduled task is executed
    TimeUnit.SECONDS.sleep(10);
    assertTrue(renewalTask.isDone());
    assertFalse(x509SecurityHandler.getRenewalException());
    assertTrue(tasks.isEmpty());
    rmAppSecurityManager.stop();
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestX509SecurityHandler.java

@Test(timeout = 12000)
public void testFailedCertificateRenewal() throws Exception {
    conf.set(YarnConfiguration.HOPS_RM_SECURITY_ACTOR_KEY,
            "org.apache.hadoop.yarn.server.resourcemanager.security.TestingRMAppSecurityActions");
    RMAppSecurityManager securityManager = new RMAppSecurityManager(rmContext);
    MockX509SecurityHandler.MockFailingX509SecurityHandler x509Handler = new MockX509SecurityHandler.MockFailingX509SecurityHandler(
            rmContext, securityManager, Integer.MAX_VALUE);
    securityManager.registerRMAppSecurityHandlerWithType(x509Handler, X509SecurityHandler.class);
    securityManager.init(conf);//from   www. j  a  v a 2 s. co m
    securityManager.start();

    LocalDateTime now = DateUtils.getNow();
    LocalDateTime expiration = now.plus(10, ChronoUnit.SECONDS);
    ApplicationId appId = ApplicationId.newInstance(DateUtils.localDateTime2UnixEpoch(now), 1);
    X509SecurityHandler.X509MaterialParameter x509Param = new X509SecurityHandler.X509MaterialParameter(appId,
            "Dolores", 1);
    x509Param.setExpiration(DateUtils.localDateTime2UnixEpoch(expiration));
    x509Handler.registerRenewer(x509Param);

    Map<ApplicationId, ScheduledFuture> tasks = x509Handler.getRenewalTasks();
    // There should be a scheduled task
    ScheduledFuture task = tasks.get(appId);
    assertFalse(task.isCancelled());
    assertFalse(task.isDone());
    assertFalse(x509Handler.hasRenewalFailed());
    assertEquals(0, x509Handler.getNumberOfRenewalFailures());

    TimeUnit.SECONDS.sleep(10);
    assertTrue(tasks.isEmpty());
    assertEquals(4, x509Handler.getNumberOfRenewalFailures());
    assertTrue(x509Handler.hasRenewalFailed());
    securityManager.stop();
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestX509SecurityHandler.java

@Test(timeout = 12000)
public void testRetryCertificateRenewal() throws Exception {
    conf.set(YarnConfiguration.HOPS_RM_SECURITY_ACTOR_KEY,
            "org.apache.hadoop.yarn.server.resourcemanager.security.TestingRMAppSecurityActions");
    RMAppSecurityManager securityManager = new RMAppSecurityManager(rmContext);
    MockX509SecurityHandler.MockFailingX509SecurityHandler x509Handler = new MockX509SecurityHandler.MockFailingX509SecurityHandler(
            rmContext, securityManager, 2);
    securityManager.registerRMAppSecurityHandlerWithType(x509Handler, X509SecurityHandler.class);
    securityManager.init(conf);/*ww  w . ja  va2 s.c  om*/
    securityManager.start();

    LocalDateTime now = DateUtils.getNow();
    LocalDateTime expiration = now.plus(10, ChronoUnit.SECONDS);
    ApplicationId appId = ApplicationId.newInstance(DateUtils.localDateTime2UnixEpoch(now), 1);
    X509SecurityHandler.X509MaterialParameter x509Param = new X509SecurityHandler.X509MaterialParameter(appId,
            "Dolores", 1);
    x509Param.setExpiration(DateUtils.localDateTime2UnixEpoch(expiration));
    x509Handler.registerRenewer(x509Param);
    TimeUnit.SECONDS.sleep(10);
    assertEquals(2, x509Handler.getNumberOfRenewalFailures());
    assertFalse(x509Handler.hasRenewalFailed());
    assertTrue(x509Handler.getRenewalTasks().isEmpty());
    securityManager.stop();
}

From source file:org.darkware.wpman.util.TimeWindow.java

/**
 * Fetch a random moment falling somewhere inside this time window.
 *
 * @return A {@code DateTime} representing a random moment which is explicitly between the earliest
 * and latest moments in the window./*from  ww w .  j  ava 2  s .com*/
 */
public LocalDateTime getRandomMoment() {
    long durationSeconds = this.earliest.until(this.latest, ChronoUnit.SECONDS);
    return this.earliest.plus(RandomUtils.nextLong(0, durationSeconds), ChronoUnit.SECONDS);
}

From source file:org.eclipse.smarthome.ui.internal.items.ItemUIRegistryImpl.java

private boolean matchStateToValue(State state, String value, String matchCondition) {
    // Check if the value is equal to the supplied value
    boolean matched = false;

    // Remove quotes - this occurs in some instances where multiple types
    // are defined in the xtext definitions
    String unquotedValue = value;
    if (unquotedValue.startsWith("\"") && unquotedValue.endsWith("\"")) {
        unquotedValue = unquotedValue.substring(1, unquotedValue.length() - 1);
    }//from  w w  w.  ja  v  a 2 s  . c  o  m

    // Convert the condition string into enum
    Condition condition = Condition.EQUAL;
    if (matchCondition != null) {
        condition = Condition.fromString(matchCondition);
        if (condition == null) {
            logger.warn("matchStateToValue: unknown match condition '{}'", matchCondition);
            return matched;
        }
    }

    if (unquotedValue.equals(UnDefType.NULL.toString()) || unquotedValue.equals(UnDefType.UNDEF.toString())) {
        switch (condition) {
        case EQUAL:
            if (unquotedValue.equals(state.toString())) {
                matched = true;
            }
            break;
        case NOT:
        case NOTEQUAL:
            if (!unquotedValue.equals(state.toString())) {
                matched = true;
            }
            break;
        default:
            break;
        }
    } else {
        if (state instanceof DecimalType || state instanceof QuantityType<?>) {
            try {
                double compareDoubleValue = Double.parseDouble(unquotedValue);
                double stateDoubleValue;
                if (state instanceof DecimalType) {
                    stateDoubleValue = ((DecimalType) state).doubleValue();
                } else {
                    stateDoubleValue = ((QuantityType<?>) state).doubleValue();
                }
                switch (condition) {
                case EQUAL:
                    if (stateDoubleValue == compareDoubleValue) {
                        matched = true;
                    }
                    break;
                case LTE:
                    if (stateDoubleValue <= compareDoubleValue) {
                        matched = true;
                    }
                    break;
                case GTE:
                    if (stateDoubleValue >= compareDoubleValue) {
                        matched = true;
                    }
                    break;
                case GREATER:
                    if (stateDoubleValue > compareDoubleValue) {
                        matched = true;
                    }
                    break;
                case LESS:
                    if (stateDoubleValue < compareDoubleValue) {
                        matched = true;
                    }
                    break;
                case NOT:
                case NOTEQUAL:
                    if (stateDoubleValue != compareDoubleValue) {
                        matched = true;
                    }
                    break;
                }
            } catch (NumberFormatException e) {
                logger.debug("matchStateToValue: Decimal format exception: ", e);
            }
        } else if (state instanceof DateTimeType) {
            ZonedDateTime val = ((DateTimeType) state).getZonedDateTime();
            ZonedDateTime now = ZonedDateTime.now();
            long secsDif = ChronoUnit.SECONDS.between(val, now);

            try {
                switch (condition) {
                case EQUAL:
                    if (secsDif == Integer.parseInt(unquotedValue)) {
                        matched = true;
                    }
                    break;
                case LTE:
                    if (secsDif <= Integer.parseInt(unquotedValue)) {
                        matched = true;
                    }
                    break;
                case GTE:
                    if (secsDif >= Integer.parseInt(unquotedValue)) {
                        matched = true;
                    }
                    break;
                case GREATER:
                    if (secsDif > Integer.parseInt(unquotedValue)) {
                        matched = true;
                    }
                    break;
                case LESS:
                    if (secsDif < Integer.parseInt(unquotedValue)) {
                        matched = true;
                    }
                    break;
                case NOT:
                case NOTEQUAL:
                    if (secsDif != Integer.parseInt(unquotedValue)) {
                        matched = true;
                    }
                    break;
                }
            } catch (NumberFormatException e) {
                logger.debug("matchStateToValue: Decimal format exception: ", e);
            }
        } else {
            // Strings only allow = and !=
            switch (condition) {
            case NOT:
            case NOTEQUAL:
                if (!unquotedValue.equals(state.toString())) {
                    matched = true;
                }
                break;
            default:
                if (unquotedValue.equals(state.toString())) {
                    matched = true;
                }
                break;
            }
        }
    }

    return matched;
}

From source file:org.haiku.haikudepotserver.security.AuthenticationServiceImpl.java

/**
 * <p>This will return a JWT (java web token) that is signed by a secret that allows for the client to get
 * that token and for it to be used as a form of authentication for some period of time.</p>
 *///  www  .j a va  2s. c  om

@Override
public String generateToken(User user) {

    Preconditions.checkArgument(null != user, "the user must be provided");

    Instant instant = Instant.now();

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject(user.getNickname() + SUFFIX_JSONWEBTOKEN_SUBJECT)
            .issueTime(new java.util.Date(instant.toEpochMilli()))
            .expirationTime(new java.util.Date(
                    instant.plus(jsonWebTokenExpirySeconds, ChronoUnit.SECONDS).toEpochMilli()))
            .issuer(jsonWebTokenIssuer).build();

    SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);

    try {
        signedJWT.sign(jsonWebTokenSigner);
    } catch (JOSEException je) {
        throw new IllegalStateException("unable to sign a jwt", je);
    }

    return signedJWT.serialize();
}