Example usage for org.joda.time Seconds secondsBetween

List of usage examples for org.joda.time Seconds secondsBetween

Introduction

In this page you can find the example usage for org.joda.time Seconds secondsBetween.

Prototype

public static Seconds secondsBetween(ReadablePartial start, ReadablePartial end) 

Source Link

Document

Creates a Seconds representing the number of whole seconds between the two specified partial datetimes.

Usage

From source file:ManageBean.PostController.java

public void CaculateTime() {
    obj2 = new ArrayList<>();
    DateTime datenow = new DateTime();
    for (int i = 0; i < list.size(); i++) {

        DateTime datepost = new DateTime(list.get(i).getPostDate());

        Dates Date = new Dates();
        //Date.setDate(Days.daysBetween(datepost, datenow).getDays());
        if (Days.daysBetween(datepost, datenow).getDays() > 0) {
            Date.setTime("cch y " + Days.daysBetween(datepost, datenow).getDays() + " ngy");
        } else if ((Hours.hoursBetween(datepost, datenow).getHours() % 24) > 0) {
            Date.setTime("cch y " + Hours.hoursBetween(datepost, datenow).getHours() % 24 + "gi?");
        } else if ((Minutes.minutesBetween(datepost, datenow).getMinutes() % 60) > 0) {
            Date.setTime(/*from   w w  w . jav a  2s  . c o m*/
                    "cch y " + Minutes.minutesBetween(datepost, datenow).getMinutes() % 60 + " pht");
        } else {
            Date.setTime(
                    "cch y " + Seconds.secondsBetween(datepost, datenow).getSeconds() % 60 + " giy");
        }
        obj2.add(Date);

    }

}

From source file:net.technicpack.solder.cache.CachedSolderApi.java

License:Open Source License

@Override
public Collection<SolderPackInfo> internalGetPublicSolderPacks(String solderRoot, ISolderApi packFactory)
        throws RestfulAPIException {
    if (Seconds.secondsBetween(lastSolderPull, DateTime.now()).isLessThan(Seconds.seconds(cacheInSeconds))) {
        if (cachedPublicPacks != null)
            return cachedPublicPacks;
    }/*w w w . j  a  v  a2s  . co  m*/

    if (Seconds.secondsBetween(lastSolderPull, DateTime.now()).isLessThan(Seconds.seconds(cacheInSeconds / 10)))
        return new ArrayList<SolderPackInfo>(0);

    try {
        cachedPublicPacks = innerApi.internalGetPublicSolderPacks(solderRoot, this);
        return cachedPublicPacks;
    } finally {
        lastSolderPull = DateTime.now();
    }
}

From source file:net.technicpack.solder.cache.CachedSolderPackApi.java

License:Open Source License

@Override
public SolderPackInfo getPackInfo() throws RestfulAPIException {
    if (Seconds.secondsBetween(lastInfoAccess, DateTime.now()).isLessThan(Seconds.seconds(cacheInSeconds))) {
        if (rootInfoCache != null)
            return rootInfoCache;
    }/*from   w  w w  . j a v a  2 s  .c o  m*/

    if (Seconds.secondsBetween(lastInfoAccess, DateTime.now()).isLessThan(Seconds.seconds(cacheInSeconds / 10)))
        return rootInfoCache;

    try {
        return pullAndCache();
    } catch (RestfulAPIException ex) {
        ex.printStackTrace();

        return getPackInfoForBulk();
    }
}

From source file:org.apache.beam.runners.dataflow.util.PackageUtil.java

License:Apache License

/**
 * Transfers the classpath elements to the staging location.
 *
 * @param classpathElements The elements to stage.
 * @param stagingPath The base location to stage the elements to.
 * @return A list of cloud workflow packages, each representing a classpath element.
 *///from   w w w.  java 2 s  .  c  om
List<DataflowPackage> stageClasspathElements(Collection<String> classpathElements, final String stagingPath,
        final Sleeper retrySleeper, final CreateOptions createOptions) {
    LOG.info("Uploading {} files from PipelineOptions.filesToStage to staging location to "
            + "prepare for execution.", classpathElements.size());
    Instant start = Instant.now();

    if (classpathElements.size() > SANE_CLASSPATH_SIZE) {
        LOG.warn(
                "Your classpath contains {} elements, which Google Cloud Dataflow automatically "
                        + "copies to all workers. Having this many entries on your classpath may be indicative "
                        + "of an issue in your pipeline. You may want to consider trimming the classpath to "
                        + "necessary dependencies only, using --filesToStage pipeline option to override "
                        + "what files are being staged, or bundling several dependencies into one.",
                classpathElements.size());
    }

    checkArgument(stagingPath != null,
            "Can't stage classpath elements because no staging location has been provided");

    final AtomicInteger numUploaded = new AtomicInteger(0);
    final AtomicInteger numCached = new AtomicInteger(0);
    List<CompletionStage<DataflowPackage>> destinationPackages = new ArrayList<>();

    for (String classpathElement : classpathElements) {
        DataflowPackage sourcePackage = new DataflowPackage();
        if (classpathElement.contains("=")) {
            String[] components = classpathElement.split("=", 2);
            sourcePackage.setName(components[0]);
            sourcePackage.setLocation(components[1]);
        } else {
            sourcePackage.setName(null);
            sourcePackage.setLocation(classpathElement);
        }

        File sourceFile = new File(sourcePackage.getLocation());
        if (!sourceFile.exists()) {
            LOG.warn("Skipping non-existent file to stage {}.", sourceFile);
            continue;
        }

        CompletionStage<StagingResult> stagingResult = computePackageAttributes(sourcePackage, stagingPath)
                .thenComposeAsync(
                        packageAttributes -> stagePackage(packageAttributes, retrySleeper, createOptions));

        CompletionStage<DataflowPackage> stagedPackage = stagingResult.thenApply(stagingResult1 -> {
            if (stagingResult1.alreadyStaged()) {
                numCached.incrementAndGet();
            } else {
                numUploaded.incrementAndGet();
            }
            return stagingResult1.getPackageAttributes().getDestination();
        });

        destinationPackages.add(stagedPackage);
    }

    try {
        CompletionStage<List<DataflowPackage>> stagingFutures = MoreFutures.allAsList(destinationPackages);
        boolean finished = false;
        do {
            try {
                MoreFutures.get(stagingFutures, 3L, TimeUnit.MINUTES);
                finished = true;
            } catch (TimeoutException e) {
                // finished will still be false
                LOG.info("Still staging {} files", classpathElements.size());
            }
        } while (!finished);
        List<DataflowPackage> stagedPackages = MoreFutures.get(stagingFutures);
        Instant done = Instant.now();
        LOG.info("Staging files complete: {} files cached, {} files newly uploaded in {} seconds",
                numCached.get(), numUploaded.get(), Seconds.secondsBetween(start, done).getSeconds());
        return stagedPackages;
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException("Interrupted while staging packages", e);
    } catch (ExecutionException e) {
        throw new RuntimeException("Error while staging packages", e.getCause());
    }
}

From source file:org.apache.falcon.plugin.GraphiteNotificationPlugin.java

License:Apache License

@Override
public void monitor(ResourceMessage message) {
    MetricNotificationService metricNotificationService = Services.get()
            .getService(MetricNotificationService.SERVICE_NAME);
    try {//from   w  w w  .  java 2s  .c om
        String entityType = StringUtils.isNotBlank(message.getDimensions().get("entityType"))
                ? message.getDimensions().get("entityType")
                : message.getDimensions().get("entity-type");
        String entityName = StringUtils.isNotBlank(message.getDimensions().get("entityName"))
                ? message.getDimensions().get("entityName")
                : message.getDimensions().get("entity-name");
        String prefix = StartupProperties.get().getProperty("falcon.graphite.prefix");
        LOG.debug("message:" + message.getAction());
        if (entityType.equalsIgnoreCase(EntityType.PROCESS.name())
                && ConfigurationStore.get().get(EntityType.PROCESS, entityName) != null) {
            Entity entity = ConfigurationStore.get().get(EntityType.PROCESS, entityName);
            Process process = (Process) entity;
            String pipeline = StringUtils.isNotBlank(process.getPipelines()) ? process.getPipelines()
                    : "default";
            pipeline = pipeline.replaceAll(" ", "-");

            if ((message.getAction().equals("wf-instance-succeeded"))) {
                Long timeTaken = message.getExecutionTime() / 1000000000;
                StringBuilder processingMetric = new StringBuilder(prefix).append(".")
                        .append(message.getDimensions().get("cluster")).append(".").append(pipeline)
                        .append(".GENERATE.").append(entityName).append(".processing_time");
                metricNotificationService.publish(processingMetric.toString(), timeTaken);

                DateTime nominalTime = new DateTime(message.getDimensions().get("nominal-time"));
                DateTime startTime = new DateTime(message.getDimensions().get("start-time"));
                StringBuilder startTimeMetric = new StringBuilder(prefix).append(".")
                        .append(message.getDimensions().get("cluster")).append(".").append(pipeline)
                        .append(".GENERATE.").append(entityName).append(".start_delay");
                metricNotificationService.publish(startTimeMetric.toString(),
                        (long) Seconds.secondsBetween(nominalTime, startTime).getSeconds());
            }

            if (message.getAction().equals("wf-instance-failed")) {
                StringBuilder metricName = new StringBuilder(prefix).append(".")
                        .append(message.getDimensions().get("cluster")).append(".").append(pipeline)
                        .append(".GENERATE.").append(entityName).append(".failure")
                        .append(message.getDimensions().get("error-message"));
                metricNotificationService.publish(metricName.toString(), (long) 1);
            }
        }
    } catch (Exception e) {
        LOG.error("Exception in sending metrics to Graphite:", e);
    }
}

From source file:org.apache.falcon.plugin.ProcessExecutionStatsPlugin.java

License:Apache License

@Override
public void monitor(ResourceMessage message) {
    try {// ww w  .j ava 2 s.  c  om
        String entityType = StringUtils.isNotBlank(message.getDimensions().get("entityType"))
                ? message.getDimensions().get("entityType")
                : message.getDimensions().get("entity-type");
        String entityName = StringUtils.isNotBlank(message.getDimensions().get("entityName"))
                ? message.getDimensions().get("entityName")
                : message.getDimensions().get("entity-name");
        LOG.debug("message:" + message.getAction());
        if (entityType.equalsIgnoreCase(EntityType.PROCESS.name())
                && ConfigurationStore.get().get(EntityType.PROCESS, entityName) != null) {
            Process process = ConfigurationStore.get().get(EntityType.PROCESS, entityName);
            String pipelines = StringUtils.isNotBlank(process.getPipelines()) ? process.getPipelines()
                    : "__untagged";
            String cluster = message.getDimensions().get("cluster");
            DateTime nominalTime = new DateTime(message.getDimensions().get("nominal-time"));
            DateTime startTime = new DateTime(message.getDimensions().get("start-time"));
            Long startDelay = (long) Seconds.secondsBetween(nominalTime, startTime).getSeconds();
            Long timeTaken = message.getExecutionTime() / 1000000000;

            String[] pipelineNames = pipelines.split(",");

            for (String name : pipelineNames) {

                if ((message.getAction().equals("wf-instance-succeeded"))) {
                    MONITORING_JDBC_STATE_STORE.putProcessInstance(entityName, cluster, nominalTime.getMillis(),
                            startDelay, timeTaken, name, "succeeded");
                }
                if (message.getAction().equals("wf-instance-failed")) {
                    MONITORING_JDBC_STATE_STORE.putProcessInstance(entityName, cluster, nominalTime.getMillis(),
                            startDelay, timeTaken, name, "failed");
                }
            }
        }
    } catch (Exception e) {
        LOG.error("Exception in sending metrics to FalconDB:", e);
    }
}

From source file:org.apache.pig.piggybank.evaluation.datetime.diff.ISOSecondsBetween.java

License:Apache License

@Override
public Long exec(Tuple input) throws IOException {
    if (input == null || input.size() < 2) {
        return null;
    }//ww  w  .ja  va 2s  . c o  m

    // Set the time to default or the output is in UTC
    DateTimeZone.setDefault(DateTimeZone.UTC);

    DateTime startDate = new DateTime(input.get(0).toString());
    DateTime endDate = new DateTime(input.get(1).toString());

    // Larger date first
    Seconds s = Seconds.secondsBetween(endDate, startDate);
    long seconds = s.getSeconds();

    return seconds;
}

From source file:org.apereo.portal.events.aggr.EventProcessingResult.java

License:Apache License

protected EventProcessingResult(int processed, DateTime start, DateTime end, boolean complete) {
    this.processed = processed;
    this.start = start;
    this.end = end;
    this.complete = complete;

    if (start == null || end == null) {
        creationRate = 0;//from  w  w w. j a va 2 s  .com
    } else {
        creationRate = (double) processed / Math.abs(Seconds.secondsBetween(start, end).getSeconds());
    }
}

From source file:org.codehaus.httpcache4j.cache.CacheItem.java

License:Open Source License

public int getAge(HTTPRequest request) {
    return Seconds.secondsBetween(cachedTime, request.getRequestTime()).getSeconds();
}

From source file:org.codehaus.httpcache4j.cache.CacheItem.java

License:Open Source License

public static int getTTL(HTTPResponse response, int defaultTTLinSeconds) {
    final CacheControl cc = response.getCacheControl();
    if (cc != null) {
        int maxAge = cc.getMaxAge();
        if (maxAge > 0) {
            return maxAge;
        }//from w ww .  j av  a  2s  . c  om
    }
    /**
     * HTTP/1.1 clients and caches MUST treat other invalid date formats, especially including the value "0", as in the past (i.e., "already expired").
     * To mark a response as "already expired," an origin server sends an Expires date that is equal to the Date header value.
     * (See the rules for expiration calculations in section 13.2.4.)
     * To mark a response as "never expires," an origin server sends an Expires date approximately one year from the time the response is sent.
     * HTTP/1.1 servers SHOULD NOT send Expires dates more than one year in the future.
     */
    if (response.getExpires() != null) {
        DateTime expiryDate = response.getExpires();
        if (expiryDate != null) {
            DateTime date = response.getDate();
            if (date != null && date.isBefore(expiryDate)) {
                return Seconds.secondsBetween(date, expiryDate).getSeconds();
            }
        }

    }

    return defaultTTLinSeconds;
}