Example usage for java.util.concurrent TimeUnit DAYS

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

Introduction

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

Prototype

TimeUnit DAYS

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

Click Source Link

Document

Time unit representing twenty four hours.

Usage

From source file:com.linkedin.pinot.query.aggregation.AggregationGroupByWithDictionaryAndTrieTreeOperatorTest.java

private void setupSegmentList(int numberOfSegments) throws Exception {
    final String filePath = TestUtils
            .getFileFromResourceUrl(getClass().getClassLoader().getResource(AVRO_DATA));
    _indexSegmentList.clear();//from   w w  w. j av  a 2s. co  m
    if (INDEXES_DIR.exists()) {
        FileUtils.deleteQuietly(INDEXES_DIR);
    }
    INDEXES_DIR.mkdir();

    for (int i = 0; i < numberOfSegments; ++i) {
        final File segmentDir = new File(INDEXES_DIR, "segment_" + i);

        final SegmentGeneratorConfig config = SegmentTestUtils.getSegmentGenSpecWithSchemAndProjectedColumns(
                new File(filePath), segmentDir, "time_day", TimeUnit.DAYS, "test");

        config.setSegmentNamePostfix(String.valueOf(i));

        final SegmentIndexCreationDriver driver = SegmentCreationDriverFactory.get(null);
        driver.init(config);
        driver.build();

        LOGGER.debug("built at : {}", segmentDir.getAbsolutePath());
        final File indexSegmentDir = new File(segmentDir, driver.getSegmentName());
        _indexSegmentList
                .add(new OfflineSegmentDataManager(ColumnarSegmentLoader.load(indexSegmentDir, ReadMode.heap)));
    }
}

From source file:io.spring.initializr.web.project.MainController.java

private ResponseEntity<String> serviceCapabilitiesFor(InitializrMetadataVersion version,
        MediaType contentType) {//from w w  w.  java  2  s.c  o m
    String appUrl = generateAppUrl();
    String content = getJsonMapper(version).write(this.metadataProvider.get(), appUrl);
    return ResponseEntity.ok().contentType(contentType).eTag(createUniqueId(content))
            .cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS)).body(content);
}

From source file:com.linkedin.pinot.query.aggregation.AggregationGroupByOperatorTest.java

private void setupSegmentList(int numberOfSegments) throws Exception {
    final String filePath = TestUtils
            .getFileFromResourceUrl(getClass().getClassLoader().getResource(AVRO_DATA));
    _indexSegmentList.clear();//from   ww w. j  a v  a 2s.  c  om
    if (INDEXES_DIR.exists()) {
        FileUtils.deleteQuietly(INDEXES_DIR);
    }
    INDEXES_DIR.mkdir();

    for (int i = 0; i < numberOfSegments; ++i) {
        final File segmentDir = new File(INDEXES_DIR, "segment_" + i);

        final SegmentGeneratorConfig config = SegmentTestUtils.getSegmentGenSpecWithSchemAndProjectedColumns(
                new File(filePath), segmentDir, "time_day", TimeUnit.DAYS, "test");

        final SegmentIndexCreationDriver driver = SegmentCreationDriverFactory.get(null);
        driver.init(config);
        driver.build();

        LOGGER.debug("built at : {}", segmentDir.getAbsolutePath());
        _indexSegmentList.add(new OfflineSegmentDataManager(
                ColumnarSegmentLoader.load(new File(segmentDir, driver.getSegmentName()), ReadMode.heap)));
    }
}

From source file:pt.ua.tm.neji.web.server.Server.java

@Override
public void lifeCycleStopping(LifeCycle event) {

    executor.shutdown();//  w w  w .j  ava  2  s .com
    try {
        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
    } catch (InterruptedException ex) {
        String m = "There was a problem terminating the server executor.";
        logger.error(m, ex);
    }

    try {
        logger.info("Terminating context...");
        context.terminate();

    } catch (NejiException ex) {
        ex.printStackTrace();
        System.exit(2);
    }
}

From source file:org.apache.carbondata.processing.loading.sort.unsafe.merger.UnsafeIntermediateMerger.java

public void finish() throws CarbonSortKeyAndGroupByException {
    try {/*from  ww w.  j a v  a2s.c  o  m*/
        executorService.shutdown();
        executorService.awaitTermination(2, TimeUnit.DAYS);
    } catch (InterruptedException e) {
        throw new CarbonSortKeyAndGroupByException("Problem while shutdown the server ", e);
    }
    checkForFailure();
}

From source file:contestWebsite.AdminPanel.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets");
    ve.init();//from  w w w .j a  v a  2s.  c o  m
    VelocityContext context = new VelocityContext();
    Pair<Entity, UserCookie> infoAndCookie = init(context, req);

    UserCookie userCookie = infoAndCookie.y;
    boolean loggedIn = (boolean) context.get("loggedIn");

    String updated = req.getParameter("updated");
    if (updated != null && updated.equals("1") && !loggedIn) {
        resp.sendRedirect("/adminPanel?updated=1");
    }
    context.put("updated", req.getParameter("updated"));

    if (loggedIn && userCookie.isAdmin()) {
        Entity contestInfo = infoAndCookie.x;
        context.put("contestInfo", contestInfo);

        String confPassError = req.getParameter("confPassError");
        context.put("confPassError",
                confPassError != null && confPassError.equals("1") ? "Those passwords didn't match, try again."
                        : null);
        String passError = req.getParameter("passError");
        context.put("passError",
                passError != null && passError.equals("1") ? "That password is incorrect, try again." : null);

        context.put("middleSubjects", Test.getTests(Level.MIDDLE));
        context.put("Level", Level.class);
        context.put("subjects", Subject.values());

        String[] defaultEmails = { "forgotPass", "question", "registration" };
        for (String defaultEmail : defaultEmails) {
            String email;
            if (contestInfo.hasProperty(defaultEmail + "Email")) {
                email = ((Text) contestInfo.getProperty(defaultEmail + "Email")).getValue();
            } else {
                InputStream emailStream = getServletContext()
                        .getResourceAsStream("/html/email/" + defaultEmail + ".html");
                email = CharStreams.toString(new InputStreamReader(emailStream, Charsets.UTF_8));
                emailStream.close();
            }
            context.put(defaultEmail + "Email", email);
        }

        try {
            context.put("awardCriteria", Retrieve.awardCriteria(contestInfo));
            context.put("qualifyingCriteria", Retrieve.qualifyingCriteria(contestInfo));
            context.put("clientId", contestInfo.getProperty("OAuth2ClientId"));
        } catch (Exception e) {
            System.err.println("Surpressing exception while loading admin panel");
            e.printStackTrace();
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+6"));

        try {
            Date endDate = dateFormat.parse((String) contestInfo.getProperty("editEndDate"));
            Date startDate = dateFormat.parse((String) contestInfo.getProperty("editStartDate"));
            if (new Date().after(endDate) || new Date().before(startDate)) {
                context.put("regEditClosed", true);
            }
        } catch (Exception e) {
            context.put("regEditClosed", true);
        }

        try {
            Date endDate = dateFormat.parse((String) contestInfo.getProperty("endDate"));
            Date startDate = dateFormat.parse((String) contestInfo.getProperty("startDate"));
            if (new Date().after(endDate) || new Date().before(startDate)) {
                context.put("regClosed", true);
            }
        } catch (Exception e) {
            context.put("regClosed", true);
        }

        MemcacheService memCache = MemcacheServiceFactory.getMemcacheService();
        memCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(java.util.logging.Level.INFO));
        byte[] tabulationTaskStatusBytes = (byte[]) memCache.get("tabulationTaskStatus");
        if (tabulationTaskStatusBytes != null) {
            String[] tabulationTaskStatus = new String(tabulationTaskStatusBytes).split("_");
            context.put("tabulationTaskStatus", tabulationTaskStatus[0]);
            List<String> tabulationTaskStatusTime = new ArrayList<String>();
            long timeAgo = new Date().getTime() - new Date(Long.parseLong(tabulationTaskStatus[1])).getTime();
            List<Pair<TimeUnit, String>> timeUnits = new ArrayList<Pair<TimeUnit, String>>() {
                {
                    add(new Pair<TimeUnit, String>(TimeUnit.DAYS, "day"));
                    add(new Pair<TimeUnit, String>(TimeUnit.HOURS, "hour"));
                    add(new Pair<TimeUnit, String>(TimeUnit.MINUTES, "minute"));
                    add(new Pair<TimeUnit, String>(TimeUnit.SECONDS, "second"));
                }
            };
            for (Pair<TimeUnit, String> entry : timeUnits) {
                if (entry.getX().convert(timeAgo, TimeUnit.MILLISECONDS) > 0) {
                    long numUnit = entry.getX().convert(timeAgo, TimeUnit.MILLISECONDS);
                    tabulationTaskStatusTime.add(numUnit + " " + entry.getY() + (numUnit == 1 ? "" : "s"));
                    timeAgo -= TimeUnit.MILLISECONDS.convert(numUnit, entry.getX());
                }
            }
            if (tabulationTaskStatusTime.size() >= 1) {
                context.put("tabulationTaskStatusTime", StringUtils.join(tabulationTaskStatusTime, ", "));
            } else {
                context.put("tabulationTaskStatusTime", timeAgo + " milliseconds");
            }
        }

        close(context, ve.getTemplate("adminPanel.html"), resp);
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Contest Administrator privileges required for that operation");
    }
}

From source file:org.hawkular.metrics.generator.DataGenerator.java

private long convertDurationToMillis(long value, String units) {
    switch (units) {
    case "s":
        return TimeUnit.MILLISECONDS.convert(value, TimeUnit.SECONDS);
    case "m":
        return TimeUnit.MILLISECONDS.convert(value, TimeUnit.MINUTES);
    case "h":
        return TimeUnit.MILLISECONDS.convert(value, TimeUnit.HOURS);
    case "d":
        return TimeUnit.MILLISECONDS.convert(value, TimeUnit.DAYS);
    default:/*from  w w w.ja  v a  2  s. co m*/
        throw new IllegalArgumentException(units + " is an invalid time unit");
    }
}

From source file:com.stratio.ingestion.sink.elasticsearch.TestElasticSearchSink.java

@Ignore
@Test/*from   ww w.j a v  a  2s  .c  o  m*/
public void shouldParseConfiguration() {
    parameters.put(HOSTNAMES, "10.5.5.27");
    parameters.put(CLUSTER_NAME, "testing-cluster-name");
    parameters.put(INDEX_NAME, "testing-index-name");
    parameters.put(INDEX_TYPE, "testing-index-type");
    parameters.put(TTL, "10");

    fixture = new ElasticSearchSink();
    fixture.configure(new Context(parameters));

    String[] expected = { "10.5.5.27" };

    assertEquals("testing-cluster-name", fixture.getClusterName());
    assertEquals("testing-index-name", fixture.getIndexName());
    assertEquals("testing-index-type", fixture.getIndexType());
    assertEquals(TimeUnit.DAYS.toMillis(10), fixture.getTTLMs());
    assertArrayEquals(expected, fixture.getServerAddresses());
}

From source file:com.epam.ta.reportportal.core.jasper.GetJasperReportHandler.java

/**
 * Format launch duration from long to human readable format.
 *
 * @param duration/* w w  w.java2  s.co m*/
 *            - input duration as long value
 * @return String - formatted output
 */
private static String millisToShortDHMS(long duration) {
    String res;
    long days = TimeUnit.MILLISECONDS.toDays(duration);
    long hours = TimeUnit.MILLISECONDS.toHours(duration)
            - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));
    long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)
            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));
    long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)
            - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));
    if (days == 0) {
        res = String.format("%02d:%02d:%02d", hours, minutes, seconds);
    } else {
        res = String.format("%dd%02d:%02d:%02d", days, hours, minutes, seconds);
    }
    return res;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.quota.QuotaService.java

private void computeAndApplyChargeInt(final Collection<ContainerLog> ContainersLogs, final boolean isRecover)
        throws StorageException {
    //Get Data  ** ProjectQuota **
    ProjectQuotaDataAccess pqDA = (ProjectQuotaDataAccess) RMStorageFactory
            .getDataAccess(ProjectQuotaDataAccess.class);
    Map<String, ProjectQuota> projectsQuotaMap = pqDA.getAll();
    final long curentDay = TimeUnit.DAYS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    Map<String, ProjectQuota> chargedProjects = new HashMap<>();
    Map<ProjectDailyId, ProjectDailyCost> chargedProjectsDailyCost = new HashMap<>();

    List<ContainerLog> toBeRemovedContainersLogs = new ArrayList<>();
    List<ContainerCheckPoint> toBePercistedContainerCheckPoint = new ArrayList<>();
    List<ContainerCheckPoint> toBeRemovedContainerCheckPoint = new ArrayList<>();

    // Calculate the quota
    for (ContainerLog containerLog : ContainersLogs) {
        if (!isRecover && recovered.remove(containerLog.getContainerid())) {
            //we have already charged this project when recovering we should
            //not charge it two times
            continue;
        }/*from w  w w . java2  s  .  co m*/
        if (isRecover) {
            recovered.add(containerLog.getContainerid());
        }
        // Get ApplicationId from ContainerId
        ContainerId containerId = ConverterUtils.toContainerId(containerLog.getContainerid());
        ApplicationId appId = containerId.getApplicationAttemptId().getApplicationId();

        //Get ProjectId from ApplicationId in ** ApplicationState Table ** 
        String appOwner = applicationOwnerCache.get(appId.toString());
        if (appOwner == null) {
            ApplicationState appState = (ApplicationState) appStatDS.findByApplicationId(appId.toString());
            if (appState == null) {
                LOG.error("Application not found: " + appId.toString() + " for container "
                        + containerLog.getContainerid());
                continue;
            } else {
                if (applicationOwnerCache.size() > 100000) {
                    //if the cahs is too big empty it and it will be refilled with
                    //the active applications
                    //TODO make a proper chash
                    applicationOwnerCache = new HashMap<>();
                }
                appOwner = appState.getUser();
                applicationOwnerCache.put(appId.toString(), appOwner);
            }
        }

        String projectName = HopsWorksHelper.getProjectName(appOwner);
        String user = HopsWorksHelper.getUserName(appOwner);

        //comput used ticks
        Long checkpoint = containerLog.getStart();
        float currentMultiplicator = containerLog.getMultiplicator();
        ContainerCheckPoint lastCheckPoint = containersCheckPoints.get(containerLog.getContainerid());
        if (lastCheckPoint != null) {
            checkpoint = lastCheckPoint.getCheckPoint();
            currentMultiplicator = lastCheckPoint.getMultiplicator();
        }
        long nbRunningTicks = containerLog.getStop() - checkpoint;

        // Decide what to do with the ticks
        if (nbRunningTicks > 0) {
            if (containerLog.getExitstatus() == ContainerExitStatus.CONTAINER_RUNNING_STATE) {
                //The container as been running for more than one checkpoint duration
                ContainerCheckPoint newCheckpoint = new ContainerCheckPoint(containerLog.getContainerid(),
                        containerLog.getStop(), currentMultiplicator);
                containersCheckPoints.put(containerLog.getContainerid(), newCheckpoint);
                toBePercistedContainerCheckPoint.add(newCheckpoint);

                LOG.debug("charging project still running " + projectName + " for container "
                        + containerLog.getContainerid() + " current ticks " + nbRunningTicks + "("
                        + containerLog.getStart() + ", " + containerLog.getStop() + ", " + checkpoint
                        + ") current multiplicator " + currentMultiplicator);

                float charge = computeCharge(nbRunningTicks, currentMultiplicator, containerLog.getNbVcores(),
                        containerLog.getMemoryUsed(), containerLog.getGpuUsed());
                chargeProjectQuota(chargedProjects, projectsQuotaMap, projectName, user,
                        containerLog.getContainerid(), charge);
                //** ProjectDailyCost charging**
                chargeProjectDailyCost(chargedProjectsDailyCost, projectName, user, curentDay, charge,
                        containerId.getApplicationAttemptId().getApplicationId());

            } else {
                //The container has finished running
                toBeRemovedContainersLogs.add((ContainerLog) containerLog);
                if (containersCheckPoints.remove(containerLog.getContainerid()) != null) {
                    toBeRemovedContainerCheckPoint.add(new ContainerCheckPoint(containerLog.getContainerid()));
                }

                //** ProjectQuota charging**
                LOG.debug("charging project finished " + projectName + " for container "
                        + containerLog.getContainerid() + " current ticks " + nbRunningTicks
                        + " current multiplicator " + currentMultiplicator);
                float charge = computeCharge(nbRunningTicks, currentMultiplicator, containerLog.getNbVcores(),
                        containerLog.getMemoryUsed(), containerLog.getGpuUsed());
                chargeProjectQuota(chargedProjects, projectsQuotaMap, projectName, user,
                        containerLog.getContainerid(), charge);

                //** ProjectDailyCost charging**
                chargeProjectDailyCost(chargedProjectsDailyCost, projectName, user, curentDay, charge,
                        containerId.getApplicationAttemptId().getApplicationId());
            }
        } else {
            if (checkpoint == containerLog.getStart()
                    && containerLog.getExitstatus() == ContainerExitStatus.CONTAINER_RUNNING_STATE) {
                //create a checkPoint at start to store multiplicator.
                ContainerCheckPoint newCheckpoint = new ContainerCheckPoint(containerLog.getContainerid(),
                        containerLog.getStart(), currentMultiplicator);
                containersCheckPoints.put(containerLog.getContainerid(), newCheckpoint);
                toBePercistedContainerCheckPoint.add(newCheckpoint);
            } else if (containerLog.getExitstatus() != ContainerExitStatus.CONTAINER_RUNNING_STATE) {
                //the container is not running remove it from db
                toBeRemovedContainersLogs.add((ContainerLog) containerLog);
                if (containersCheckPoints.remove(containerLog.getContainerid()) != null) {
                    toBeRemovedContainerCheckPoint.add(new ContainerCheckPoint(containerLog.getContainerid()));
                }
            }
        }
    }
    // Delet the finished ContainersLogs
    ContainersLogsDataAccess csDA = (ContainersLogsDataAccess) RMStorageFactory
            .getDataAccess(ContainersLogsDataAccess.class);
    csDA.removeAll(toBeRemovedContainersLogs);

    //Add and remove Containers checkpoints
    ContainersCheckPointsDataAccess ccpDA = (ContainersCheckPointsDataAccess) RMStorageFactory
            .getDataAccess(ContainersCheckPointsDataAccess.class);
    ccpDA.addAll(toBePercistedContainerCheckPoint);
    ccpDA.removeAll(toBeRemovedContainerCheckPoint);

    if (LOG.isDebugEnabled()) {
        // Show all charged project
        for (ProjectQuota _cpq : chargedProjects.values()) {
            LOG.debug("RIZ:: Charged projects: " + _cpq.toString() + " charge amount:"
                    + _cpq.getTotalUsedQuota());
        }
    }

    // Add all the changed project quota to NDB
    pqDA.addAll(chargedProjects.values());
    ProjectsDailyCostDataAccess pdcDA = (ProjectsDailyCostDataAccess) RMStorageFactory
            .getDataAccess(ProjectsDailyCostDataAccess.class);
    pdcDA.addAll(chargedProjectsDailyCost.values());
}