Example usage for java.util.concurrent TimeUnit HOURS

List of usage examples for java.util.concurrent TimeUnit HOURS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit HOURS.

Prototype

TimeUnit HOURS

To view the source code for java.util.concurrent TimeUnit HOURS.

Click Source Link

Document

Time unit representing sixty minutes.

Usage

From source file:org.dcache.util.histograms.TimeseriesHistogramTest.java

@Test
public void updateOnTimeseriesHistogramShouldReplaceLastValue() throws Exception {
    givenTimeseriesHistogram();//from  w  w  w .j  a  va  2s .c  om
    givenQueueCountValuesFor(48);
    givenBinUnitOf((double) TimeUnit.HOURS.toMillis(1));
    givenBinCountOf(48);
    givenBinLabelOf(TimeUnit.HOURS.name());
    givenDataLabelOf("COUNT");
    givenHistogramTypeOf("Queued Movers");
    givenHighestBinOf(getHoursInThePastFromNow(0));
    whenConfigureIsCalled();
    assertThatUpdateReplacesLastValue();
}

From source file:org.wso2.carbon.bps.perf.rest.RestClientTestDep.java

public void execute() throws Exception {

    instanceCount = Integer.parseInt(config.getProperty("instances"));
    serverURL = config.getProperty("serverURL");
    numTreads = Integer.parseInt(config.getProperty("threads"));
    outPath = config.getProperty("results");
    File outFolder = new File(outPath);
    if (!outFolder.exists()) {
        log.info("Results folder " + outFolder.getAbsolutePath() + " does not exist. Creating a new folder...");
        outFolder.mkdirs();/*  w ww  . jav  a  2 s. c  o  m*/
    }
    File testReportFile = new File(outFolder, "summary.csv");
    StringBuffer summaryBuffer = new StringBuffer();
    summaryBuffer.append("Server URL," + serverURL + "\n");
    summaryBuffer.append("Number of process instances," + instanceCount + "\n");
    summaryBuffer.append("Number of threads," + numTreads + "\n\n\n");
    summaryBuffer.append("Process ID,Total time,TPS,Average execution time\n\n");
    FileUtils.write(testReportFile, summaryBuffer.toString());

    List<ProcessConfig> processConfigs = new ArrayList<>();
    boolean processFound = true;
    String processRef = "process";
    int processNum = 1;
    while (processFound) {
        String processProp = config.getProperty(processRef + processNum);
        if (processProp == null) {
            break;
        }
        ProcessConfig processConfig = new ProcessConfig(processProp, null);
        String[] processParts = processProp.split("\\|");
        processConfig.setKey(processParts[0].trim());
        if (processParts.length > 1) {
            String[] varParts = processParts[1].split(";");
            for (String varPart : varParts) {
                String name = varPart.split(",")[0];
                String value = varPart.split(",")[1];
                processConfig.addVariable(name, value);
            }
        }
        processConfigs.add(processConfig);
    }

    for (ProcessConfig processConfig : processConfigs) {
        ActivitiRestClient client = new ActivitiRestClient(serverURL, numTreads);

        List<RestProcessExecutor> processExecutors = new ArrayList<>(instanceCount);
        ExecutorService executorService = Executors.newFixedThreadPool(numTreads);

        long stime = System.currentTimeMillis();
        for (int i = 0; i < instanceCount; i++) {
            RestProcessExecutor processExecutor = new RestProcessExecutor(null, processConfig.getId(),
                    processConfig.getStartupVariables(), client, i);
            processExecutors.add(processExecutor);
            executorService.execute(processExecutor);
        }

        executorService.shutdown();
        try {
            executorService.awaitTermination(1, TimeUnit.HOURS);
        } catch (InterruptedException e) {
            String msg = "Error occurred while waiting for executors to terminate.";
            log.error(msg, e);
        }

        long etime = System.currentTimeMillis();

        StringBuffer buf = new StringBuffer();
        double externalTPS = (double) instanceCount * 1000 / (double) (etime - stime);
        double totalDuration = 0;
        buf.append("Instance durations\n");
        for (RestProcessExecutor processExecutor : processExecutors) {
            buf.append(processExecutor.getExternalDuration() + "\n");
            totalDuration += processExecutor.getExternalDuration();
        }
        double avgExeTimeEngine = totalDuration / instanceCount;

        log.info("Process " + processConfig.getId() + " completed with duration: " + (etime - stime)
                + " ms | TPS: " + externalTPS + " | Average execution time: " + avgExeTimeEngine);
        String processRecord = processConfig.getId() + "," + (etime - stime) + "," + externalTPS + ","
                + avgExeTimeEngine + "\n";
        FileWriter fileWriter = new FileWriter(testReportFile, true);
        fileWriter.write(processRecord);
        fileWriter.close();

        buf.append("\n\nTPS," + externalTPS + "\n\n");

        File processReportFile = new File(outFolder, processConfig.getId() + ".csv");
        FileUtils.write(processReportFile, buf.toString());
        client.close();
    }

    //        Map<String, Object> vars = new HashMap<String, Object>();
    //        vars.put("testCount", new Long(1));
    //
    //        List<RestProcessExecutor> processExecutors = new ArrayList<>(instanceCount);
    //        ExecutorService executorService = Executors.newFixedThreadPool(numTreads);
    //
    //        long stime = System.currentTimeMillis();
    //        for (int i = 0; i < instanceCount; i++) {
    //            RestProcessExecutor processExecutor = new RestProcessExecutor(processKey, processId, vars, client, i);
    //            processExecutors.add(processExecutor);
    //            executorService.execute(processExecutor);
    //        }
    //
    //        executorService.shutdown();
    //        try {
    //            executorService.awaitTermination(1, TimeUnit.HOURS);
    //        } catch (InterruptedException e) {
    //            String msg = "Error occurred while waiting for executors to terminate.";
    //            log.error(msg, e);
    //        }
    //
    //        long etime = System.currentTimeMillis();
    //
    //        List<Long> startTimes = new ArrayList<Long>();
    //        List<Long> endTimes = new ArrayList<Long>();

    //        HistoryService h = engine.getHistoryService();
    //        for (HistoricProcessInstance hp : h.createHistoricProcessInstanceQuery().list()) {
    //            long startTime = hp.getStartTime().getTime();
    //            long endTime = hp.getStartTime().getTime();
    //            startTimes.add(startTime);
    //            endTimes.add(endTime);
    //            long duration = endTime - startTime;
    //            System.out.println("Duration: " + duration + " ms");
    //        }
    //        Collections.sort(startTimes);
    //        Collections.sort(endTimes);
    //
    //        long testStartTime = startTimes.get(0);
    //        long testEndTime = endTimes.get(endTimes.size() - 1);
    //        System.out.println("Test duration: " + (testEndTime - testStartTime));
    //        double throughput = (double) instanceCount * 1000 / (double) (testEndTime - testStartTime);
    //        System.out.println("TPS: " + throughput);

    //        StringBuffer buf = new StringBuffer();
    //        log.info("External duration: " + (etime - stime));
    //        double externalTPS = (double) instanceCount * 1000 / (double) (etime - stime);
    //        log.info("External TPS: " + externalTPS);
    //        buf.append("TPS," + externalTPS + "\n\n");
    //
    //        double totalDuration = 0;
    //
    //        buf.append("Instance duration\n");
    //        for (RestProcessExecutor processExecutor : processExecutors) {
    //            buf.append(processExecutor.getExternalDuration() + "\n");
    //            totalDuration += processExecutor.getExternalDuration();
    //        }
    //        log.info("Total duration: " + totalDuration);
    //        double avgExeTimeEngine = totalDuration / instanceCount;
    //        log.info("Average execution time (External): " + avgExeTimeEngine);
    //
    //        FileUtils.write(new File(outPath), buf.toString());
    //        client.close();

}

From source file:com.jdom.tvshowdownloader.integration.BlackBoxTest.java

@Test
public void downloadsEpisodesExpiredInDownloadQueue() {
    // Freeze time to three hours ago
    TimeUtilTest.freezeTime(TimeUtil.currentTimeMillis() - (new Duration(3, TimeUnit.HOURS).toMillis().value));
    alreadyDownloadingEpisodeSevenOfSimpsons();

    // Now it's three hours later, and the queue entry is expired
    TimeUtilTest.resumeTime();//  w w  w .  j  a  va  2  s  .  co m

    startMediaDownloader();

    File archivedTvDirectory = getArchivedTvDirectory();
    File simpsonsDir = new File(archivedTvDirectory, "The Simpsons");

    assertTrue("Expected the simpsons directory to exist!", simpsonsDir.isDirectory());

    File expectedFile = new File(simpsonsDir, "The_Simpsons_S24E07.nzb");

    assertTrue("An episode expired in the download queue should have been downloaded!!", expectedFile.isFile());
}

From source file:com.linkedin.pinot.common.metadata.SegmentZKMetadataTest.java

private ZNRecord getTestDoneRealtimeSegmentZNRecord() {
    String segmentName = "testTable_R_1000_2000_groupId0_part0";
    ZNRecord record = new ZNRecord(segmentName);
    record.setSimpleField(CommonConstants.Segment.SEGMENT_NAME, segmentName);
    record.setSimpleField(CommonConstants.Segment.TABLE_NAME, "testTable");
    record.setSimpleField(CommonConstants.Segment.INDEX_VERSION, "v1");
    record.setEnumField(CommonConstants.Segment.SEGMENT_TYPE, CommonConstants.Segment.SegmentType.REALTIME);
    record.setEnumField(CommonConstants.Segment.Realtime.STATUS, CommonConstants.Segment.Realtime.Status.DONE);
    record.setLongField(CommonConstants.Segment.START_TIME, 1000);
    record.setLongField(CommonConstants.Segment.END_TIME, 2000);
    record.setSimpleField(CommonConstants.Segment.TIME_UNIT, TimeUnit.HOURS.toString());
    record.setLongField(CommonConstants.Segment.TOTAL_DOCS, 10000);
    record.setLongField(CommonConstants.Segment.CRC, 1234);
    record.setLongField(CommonConstants.Segment.CREATION_TIME, 3000);
    record.setIntField(CommonConstants.Segment.FLUSH_THRESHOLD_SIZE, 1234);
    return record;
}

From source file:com.openkm.servlet.RepositoryStartupServlet.java

/**
 * Start OpenKM and possible repository and database initialization
 *///from   w  w  w  .j  av a 2s .c o m
public static synchronized void start() throws ServletException {
    SystemAuthentication systemAuth = new SystemAuthentication();

    if (running) {
        throw new IllegalStateException("OpenKM already started");
    }

    try {
        log.info("*** Repository initializing... ***");

        if (Config.REPOSITORY_NATIVE) {
            systemAuth.enable();
            DbRepositoryModule.initialize();
            systemAuth.disable();
        } else {
            JcrRepositoryModule.initialize();
        }

        log.info("*** Repository initialized ***");
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }

    log.info("*** User database initialized ***");

    if (!Config.REPOSITORY_NATIVE) {
        // Test for datastore
        SessionImpl si = (SessionImpl) JcrRepositoryModule.getSystemSession();

        if (((RepositoryImpl) si.getRepository()).getDataStore() == null) {
            hasConfiguredDataStore = false;
        } else {
            hasConfiguredDataStore = true;
        }
    }

    // Create timers
    uiTimer = new Timer("Update Info", true);
    cronTimer = new Timer("Crontab Manager", true);
    uinTimer = new Timer("User Interface Notification", true);

    // Workflow
    log.info("*** Initializing workflow engine... ***");
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    jbpmContext.setSessionFactory(HibernateUtil.getSessionFactory());
    jbpmContext.getGraphSession();
    jbpmContext.getJbpmConfiguration().getJobExecutor().start(); // startJobExecutor();
    jbpmContext.close();

    // Mime types
    log.info("*** Initializing MIME types... ***");
    MimeTypeConfig.loadMimeTypes();

    log.info("*** Activating update info ***");
    ui = new UpdateInfo();
    uiTimer.schedule(ui, TimeUnit.MINUTES.toMillis(5), TimeUnit.HOURS.toMillis(24)); // First in 5 min, next each 24 hours

    log.info("*** Activating cron ***");
    cron = new Cron();
    Calendar calCron = Calendar.getInstance();
    calCron.add(Calendar.MINUTE, 1);
    calCron.set(Calendar.SECOND, 0);
    calCron.set(Calendar.MILLISECOND, 0);

    // Round begin to next minute, 0 seconds, 0 miliseconds
    cronTimer.scheduleAtFixedRate(cron, calCron.getTime(), 60 * 1000); // First in 1 min, next each 1 min

    log.info("*** Activating UI Notification ***");
    uin = new UINotification();

    // First in 1 second next in x minutes
    uinTimer.scheduleAtFixedRate(uin, 1000, TimeUnit.MINUTES.toMillis(Config.SCHEDULE_UI_NOTIFICATION));

    try {
        // General maintenance works
        String dapContent = "com.openkm.dao.DashboardActivityDAO.purge();";
        CronTabUtils.createOrUpdate("Dashboard Activity Purge", "@daily", dapContent);

        String uisContent = "com.openkm.cache.UserItemsManager.serialize();";
        CronTabUtils.createOrUpdate("User Items Serialize", "@hourly", uisContent);

        String ruiContent = "com.openkm.cache.UserItemsManager.refreshDbUserItems();";
        CronTabUtils.createOrUpdate("Refresh User Items", "@weekly", ruiContent);

        String umiContent = "new com.openkm.core.UserMailImporter().run();";
        CronTabUtils.createOrUpdate("User Mail Importer", "*/30 * * * *", umiContent);

        String tewContent = "new com.openkm.extractor.TextExtractorWorker().run();";
        CronTabUtils.createOrUpdate("Text Extractor Worker", "*/5 * * * *", tewContent);

        String swdContent = "new com.openkm.core.Watchdog().run();";
        CronTabUtils.createOrUpdate("Session Watchdog", "*/5 * * * *", swdContent);

        String pptContent = "new com.openkm.util.pendtask.PendingTaskExecutor().run();";
        CronTabUtils.createOrUpdate("Process Pending Tasks", "*/5 * * * *", pptContent);

        // Datastore garbage collection
        if (!Config.REPOSITORY_NATIVE && hasConfiguredDataStore) {
            String dgcContent = "new com.openkm.module.jcr.stuff.DataStoreGarbageCollector().run();";
            CronTabUtils.createOrUpdate("Datastore Garbage Collector", "@daily", dgcContent);
        }
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
    }

    try {
        log.info("*** Activating thesaurus repository ***");
        RDFREpository.getInstance();
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
    }

    try {
        if (Config.REMOTE_CONVERSION_SERVER.equals("")) {
            if (!Config.SYSTEM_OPENOFFICE_PATH.equals("")) {
                log.info("*** Start OpenOffice manager ***");
                DocConverter.getInstance().start();
            } else if (!Config.SYSTEM_OPENOFFICE_SERVER.equals("")) {
                log.info("*** Using OpenOffice conversion server ***");
            } else {
                log.warn("*** No OpenOffice manager nor server configured ***");
            }
        } else {
            log.info("*** Remote conversion configured ***");
        }
    } catch (Throwable e) {
        log.warn(e.getMessage(), e);
    }

    // Initialize plugin framework
    ExtensionManager.getInstance();

    try {
        log.info("*** Execute start script ***");
        File script = new File(Config.HOME_DIR + File.separatorChar + Config.START_SCRIPT);
        ExecutionUtils.runScript(script);
        File jar = new File(Config.HOME_DIR + File.separatorChar + Config.START_JAR);
        ExecutionUtils.getInstance().runJar(jar);
    } catch (Throwable e) {
        log.warn(e.getMessage(), e);
    }

    try {
        log.info("*** Execute start SQL ***");
        File sql = new File(Config.HOME_DIR + File.separatorChar + Config.START_SQL);

        if (sql.exists() && sql.canRead()) {
            FileReader fr = new FileReader(sql);
            HibernateUtil.executeSentences(fr);
            IOUtils.closeQuietly(fr);
        } else {
            log.warn("Unable to read sql: {}", sql.getPath());
        }
    } catch (Throwable e) {
        log.warn(e.getMessage(), e);
    }

    // OpenKM is started
    running = true;
}

From source file:com.px100systems.data.plugin.persistence.DiskPersistence.java

/**
 * Resumes the stopped server/*  w  w  w  . j  a v a 2  s  .c  o  m*/
 */
public void resume() {
    if (scheduler != null)
        scheduler.shutdown();
    scheduler = new ScheduledThreadPoolExecutor(1); // One thread should be fine. Write-behind nature is single-threaded

    persist();

    scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            persist();
        }
    }, writeBehindSeconds, writeBehindSeconds, TimeUnit.SECONDS);

    scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            cleanup();
        }
    }, cleanupHours, cleanupHours, TimeUnit.HOURS);

    scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            compact();
        }
    }, compactHours, compactHours, TimeUnit.HOURS);

    log.info("Started in-memory data storage persistence");
}

From source file:org.mitre.openid.connect.web.DynamicClientRegistrationEndpoint.java

/**
 * Create a new Client, issue a client ID, and create a registration access token.
 * @param jsonString/*w  w  w . j ava  2 s .c  om*/
 * @param m
 * @param p
 * @return
 */
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String registerNewClient(@RequestBody String jsonString, Model m) {

    ClientDetailsEntity newClient = null;
    try {
        newClient = ClientDetailsEntityJsonProcessor.parse(jsonString);
    } catch (JsonSyntaxException e) {
        // bad parse
        // didn't parse, this is a bad request
        logger.error("registerNewClient failed; submitted JSON is malformed");
        m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400
        return HttpCodeView.VIEWNAME;
    }

    if (newClient != null) {
        // it parsed!

        //
        // Now do some post-processing consistency checks on it
        //

        // clear out any spurious id/secret (clients don't get to pick)
        newClient.setClientId(null);
        newClient.setClientSecret(null);

        // do validation on the fields
        try {
            newClient = validateScopes(newClient);
            newClient = validateResponseTypes(newClient);
            newClient = validateGrantTypes(newClient);
            newClient = validateRedirectUris(newClient);
            newClient = validateAuth(newClient);
        } catch (ValidationException ve) {
            // validation failed, return an error
            m.addAttribute(JsonErrorView.ERROR, ve.getError());
            m.addAttribute(JsonErrorView.ERROR_MESSAGE, ve.getErrorDescription());
            m.addAttribute(HttpCodeView.CODE, ve.getStatus());
            return JsonErrorView.VIEWNAME;
        }

        if (newClient.getTokenEndpointAuthMethod() == null) {
            newClient.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC);
        }

        if (newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_BASIC
                || newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_JWT
                || newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_POST) {

            // we need to generate a secret
            newClient = clientService.generateClientSecret(newClient);
        }

        // set some defaults for token timeouts
        if (config.isHeartMode()) {
            // heart mode has different defaults depending on primary grant type
            if (newClient.getGrantTypes().contains("authorization_code")) {
                newClient.setAccessTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(1)); // access tokens good for 1hr
                newClient.setIdTokenValiditySeconds((int) TimeUnit.MINUTES.toSeconds(5)); // id tokens good for 5min
                newClient.setRefreshTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(24)); // refresh tokens good for 24hr
            } else if (newClient.getGrantTypes().contains("implicit")) {
                newClient.setAccessTokenValiditySeconds((int) TimeUnit.MINUTES.toSeconds(15)); // access tokens good for 15min
                newClient.setIdTokenValiditySeconds((int) TimeUnit.MINUTES.toSeconds(5)); // id tokens good for 5min
                newClient.setRefreshTokenValiditySeconds(0); // no refresh tokens
            } else if (newClient.getGrantTypes().contains("client_credentials")) {
                newClient.setAccessTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(6)); // access tokens good for 6hr
                newClient.setIdTokenValiditySeconds(0); // no id tokens
                newClient.setRefreshTokenValiditySeconds(0); // no refresh tokens
            }
        } else {
            newClient.setAccessTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(1)); // access tokens good for 1hr
            newClient.setIdTokenValiditySeconds((int) TimeUnit.MINUTES.toSeconds(10)); // id tokens good for 10min
            newClient.setRefreshTokenValiditySeconds(null); // refresh tokens good until revoked
        }

        // this client has been dynamically registered (obviously)
        newClient.setDynamicallyRegistered(true);

        // this client can't do token introspection
        newClient.setAllowIntrospection(false);

        // now save it
        try {
            ClientDetailsEntity savedClient = clientService.saveNewClient(newClient);

            // generate the registration access token
            OAuth2AccessTokenEntity token = connectTokenService.createRegistrationAccessToken(savedClient);
            token = tokenService.saveAccessToken(token);

            // send it all out to the view

            RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer()
                    + "register/" + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8"));
            m.addAttribute("client", registered);
            m.addAttribute(HttpCodeView.CODE, HttpStatus.CREATED); // http 201

            return ClientInformationResponseView.VIEWNAME;
        } catch (UnsupportedEncodingException e) {
            logger.error("Unsupported encoding", e);
            m.addAttribute(HttpCodeView.CODE, HttpStatus.INTERNAL_SERVER_ERROR);
            return HttpCodeView.VIEWNAME;
        } catch (IllegalArgumentException e) {
            logger.error("Couldn't save client", e);

            m.addAttribute(JsonErrorView.ERROR, "invalid_client_metadata");
            m.addAttribute(JsonErrorView.ERROR_MESSAGE,
                    "Unable to save client due to invalid or inconsistent metadata.");
            m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400

            return JsonErrorView.VIEWNAME;
        }
    } else {
        // didn't parse, this is a bad request
        logger.error("registerNewClient failed; submitted JSON is malformed");
        m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400

        return HttpCodeView.VIEWNAME;
    }

}

From source file:net.voidfunction.rm.master.AdminServlet.java

private static String getDuration(long millis) {
    long days = TimeUnit.MILLISECONDS.toDays(millis);
    millis -= TimeUnit.DAYS.toMillis(days);
    long hours = TimeUnit.MILLISECONDS.toHours(millis);
    millis -= TimeUnit.HOURS.toMillis(hours);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
    millis -= TimeUnit.MINUTES.toMillis(minutes);
    long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);

    StringBuilder sb = new StringBuilder();
    sb.append(days);/*from   ww  w .  j av  a  2s  . c om*/
    sb.append(" days, ");
    sb.append(hours);
    sb.append(" hours, ");
    sb.append(minutes);
    sb.append(" minutes, ");
    sb.append(seconds);
    sb.append(" seconds");

    return (sb.toString());
}

From source file:org.apache.nifi.registry.web.security.authentication.jwt.JwtService.java

private static long validateTokenExpiration(long proposedTokenExpiration, String identity) {
    final long maxExpiration = TimeUnit.MILLISECONDS.convert(12, TimeUnit.HOURS);
    final long minExpiration = TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES);

    if (proposedTokenExpiration > maxExpiration) {
        logger.warn(String.format("Max token expiration exceeded. Setting expiration to %s from %s for %s",
                maxExpiration, proposedTokenExpiration, identity));
        proposedTokenExpiration = maxExpiration;
    } else if (proposedTokenExpiration < minExpiration) {
        logger.warn(String.format("Min token expiration not met. Setting expiration to %s from %s for %s",
                minExpiration, proposedTokenExpiration, identity));
        proposedTokenExpiration = minExpiration;
    }//from w w w. j a  v a 2  s . c  om

    return proposedTokenExpiration;
}

From source file:org.eclipse.skalli.core.rest.admin.StatisticsQueryTest.java

@Test
public void testFromToIntervals() throws Exception {
    long now = System.currentTimeMillis();
    StatisticsQuery query = new StatisticsQuery(getParams("-1d", null, null), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getFrom());
    Assert.assertEquals(now, query.getTo());

    query = new StatisticsQuery(getParams(null, "-1d", null), now);
    Assert.assertEquals(0, query.getFrom());
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getTo());

    query = new StatisticsQuery(getParams("-2d", "-1d", null), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(2, TimeUnit.DAYS), query.getFrom());
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getTo());

    query = new StatisticsQuery(getParams("-1d", null, "1h"), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getFrom());
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)
            + TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS), query.getTo());

    query = new StatisticsQuery(getParams(null, "-1d", "1h"), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)
            - TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS), query.getFrom());
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getTo());

    // from + period > now => to = now
    query = new StatisticsQuery(getParams("-1d", null, "2d"), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getFrom());
    Assert.assertEquals(now, query.getTo());

    // period is ignored, if from and to are specified
    query = new StatisticsQuery(getParams("-2d", "-1d", "1h"), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(2, TimeUnit.DAYS), query.getFrom());
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getTo());

    // positive to interval is treated as not specified => to = now
    query = new StatisticsQuery(getParams("-1d", "4711d", null), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getFrom());
    Assert.assertEquals(now, query.getTo());

    // positive from interval is treated as not specified => from = 0
    query = new StatisticsQuery(getParams("4711d", "-1d", null), now);
    Assert.assertEquals(0, query.getFrom());
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getTo());

    // positive from interval are treated as not specified => show 1 day
    query = new StatisticsQuery(getParams("4711d", "4711d", null), now);
    Assert.assertEquals(now - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), query.getFrom());
    Assert.assertEquals(now, query.getTo());
}