Example usage for org.joda.time Period Period

List of usage examples for org.joda.time Period Period

Introduction

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

Prototype

private Period(int[] values, PeriodType type) 

Source Link

Document

Constructor used when we trust ourselves.

Usage

From source file:org.adempierelbr.util.AdempiereLBR.java

License:Open Source License

public static String executionTime(long start, long end) {

    Period period = new Period(start, end);
    String tempo = TextUtil.lPad(period.getHours(), 2) + ":" + TextUtil.lPad(period.getMinutes(), 2) + ":"
            + TextUtil.lPad(period.getSeconds(), 2);

    return tempo;
}

From source file:org.ash.gui.ASHrawdata.java

License:Open Source License

/**
 * Get period in mm, dd, hh, ss//from  w w w.  j av a  2  s.co  m
 * @param begind
 * @param endd
 * @return
 */
private String getPeriod(double begind, double endd) {
    String out = "";
    Double beginD = begind;
    Double endD = endd;
    DateTime start = new DateTime(beginD.longValue());
    DateTime end = new DateTime(endD.longValue());

    Period period = new Period(start, end);

    if (period.getMonths() > 0)
        out = period.getMonths() + " m. ";
    if (period.getDays() > 0)
        out = out + period.getDays() + " d. ";
    if (period.getHours() > 0)
        out = out + period.getHours() + " h. ";
    if (period.getMinutes() > 0)
        out = out + period.getMinutes() + " min. ";
    if (period.getSeconds() > 0)
        out = out + period.getSeconds() + " sec. ";

    return out;
}

From source file:org.ash.history.CalendarH.java

License:Open Source License

/**
 * Get period between start and end date from BDB
 * /*w  w  w  .ja v a2 s  . c  o  m*/
 * @return
 */
private String getPeriodBDB() {
    String out = "";
    DateTime start = new DateTime(getStartBDB());
    DateTime end = new DateTime(getEndBDB());

    Period period = new Period(start, end);

    if (period.getMonths() > 0)
        out = period.getMonths() + " month(s) ";
    if (period.getDays() > 0)
        out = out + period.getDays() + " day(s) ";
    if (period.getHours() > 0)
        out = out + period.getHours() + " hour(s) ";
    if (period.getMinutes() > 0)
        out = out + period.getMinutes() + " minute(s) ";

    return out;
}

From source file:org.ash.util.Utils.java

License:Open Source License

public static String getTimeFormatting(double intervalSec) {
    String out = "";

    // Exit when intervalSec == 0
    if (intervalSec == 0.0) {
        return out;
    }//w  w  w  .ja  v a2 s  .  c o m

    DateTime start = new DateTime(0);
    DateTime end = new DateTime((long) (intervalSec * 1000));
    Period period = new Period(start, end);

    String hours = "";
    String minutes = "";
    String secunds = "";

    if (period.getHours() < 10) {
        hours = "0" + period.getHours();
    } else {
        hours = "" + period.getHours();
    }
    if (period.getMinutes() < 10) {
        minutes = "0" + period.getMinutes();
    } else {
        minutes = "" + period.getMinutes();
    }
    if (period.getSeconds() < 10) {
        secunds = "0" + period.getSeconds();
    } else {
        secunds = "" + period.getSeconds();
    }

    out = hours + ":" + minutes + ":" + secunds;

    return out;
}

From source file:org.codeontology.CodeOntology.java

License:Open Source License

private void spoon() {
    checkInput();//from   w w w  .  j  a  v a  2s .  co  m
    try {
        long start = System.currentTimeMillis();
        spoon.addInputResource(getArguments().getInput());
        System.out.println("Building model...");
        spoon.buildModel();
        long end = System.currentTimeMillis();
        Period period = new Period(start, end);
        System.out.println("Model built successfully in " + formatter.print(period));

    } catch (ModelBuildingException e) {
        if (getArguments().removeTests() && tries < directories.length) {
            boolean result;
            do {
                result = removeDirectoriesByName(directories[tries]);
                tries++;
            } while (!result && tries < directories.length);

            if (result) {
                spoon = new Launcher();
                spoon();
                return;
            }
        }
        throw e;
    }
}

From source file:org.codeontology.CodeOntology.java

License:Open Source License

private void loadDependencies() {
    long start = System.currentTimeMillis();
    loader = project.getLoader();//  w  ww.j  a v  a  2  s .  c o  m
    loader.loadDependencies();

    String classpath = getArguments().getClasspath();

    if (classpath != null) {
        loader.loadClasspath(classpath);
    }
    long end = System.currentTimeMillis();
    System.out.println("Dependencies loaded in " + formatter.print(new Period(start, end)) + ".");
}

From source file:org.codeontology.CodeOntology.java

License:Open Source License

private void extractAllTriples() {
    long start = System.currentTimeMillis();

    System.out.println("Extracting triples...");
    spoon.addProcessor(new SourceProcessor());
    spoon.process();/*  ww  w  .ja  v a 2  s .co m*/
    RDFLogger.getInstance().writeRDF();

    long end = System.currentTimeMillis();

    Period period = new Period(start, end);
    System.out.println("Triples extracted successfully in " + formatter.print(period) + ".");
    spoon = new Launcher();
}

From source file:org.codeontology.CodeOntology.java

License:Open Source License

private void processJars() {
    long start = System.currentTimeMillis();
    String path = getArguments().getJarInput();
    if (path != null) {
        JarProcessor processor = new JarProcessor(path);
        processor.process();//from w  w w.jav a 2  s . c o  m
    }

    if (getArguments().exploreJars() && loader != null) {
        Set<File> jars = loader.getJarsLoaded();
        for (File jar : jars) {
            new JarProcessor(jar).process();
        }

        long end = System.currentTimeMillis();
        Period period = new Period(start, end);
        System.out.println("Jar files processed successfully in " + formatter.print(period) + ".");
    }
}

From source file:org.codice.ddf.commands.catalog.DumpCommand.java

License:Open Source License

@Override
protected Object doExecute() throws Exception {
    final File dumpDir = new File(dirPath);

    if (!dumpDir.exists()) {
        printErrorMessage("Directory [" + dirPath + "] must exist.");
        console.println("If the directory does indeed exist, try putting the path in quotes.");
        return null;
    }/*from  ww w  .  j a v a 2  s.c o m*/

    if (!dumpDir.isDirectory()) {
        printErrorMessage("Path [" + dirPath + "] must be a directory.");
        return null;
    }

    if (!DEFAULT_TRANSFORMER_ID.matches(transformerId)) {
        transformers = getTransformers();
        if (transformers == null) {
            console.println(transformerId + " is an invalid metacard transformer.");
            return null;
        }
    }

    CatalogFacade catalog = getCatalog();
    FilterBuilder builder = getFilterBuilder();

    Filter createdFilter = null;
    if ((createdAfter != null) && (createdBefore != null)) {
        DateTime createStartDateTime = DateTime.parse(createdAfter);
        DateTime createEndDateTime = DateTime.parse(createdBefore);
        createdFilter = builder.attribute(Metacard.CREATED).is().during().dates(createStartDateTime.toDate(),
                createEndDateTime.toDate());
    } else if (createdAfter != null) {
        DateTime createStartDateTime = DateTime.parse(createdAfter);
        createdFilter = builder.attribute(Metacard.CREATED).is().after().date(createStartDateTime.toDate());
    } else if (createdBefore != null) {
        DateTime createEndDateTime = DateTime.parse(createdBefore);
        createdFilter = builder.attribute(Metacard.CREATED).is().before().date(createEndDateTime.toDate());
    }

    Filter modifiedFilter = null;
    if ((modifiedAfter != null) && (modifiedBefore != null)) {
        DateTime modifiedStartDateTime = DateTime.parse(modifiedAfter);
        DateTime modifiedEndDateTime = DateTime.parse(modifiedBefore);
        modifiedFilter = builder.attribute(Metacard.MODIFIED).is().during()
                .dates(modifiedStartDateTime.toDate(), modifiedEndDateTime.toDate());
    } else if (modifiedAfter != null) {
        DateTime modifiedStartDateTime = DateTime.parse(modifiedAfter);
        modifiedFilter = builder.attribute(Metacard.MODIFIED).is().after().date(modifiedStartDateTime.toDate());
    } else if (modifiedBefore != null) {
        DateTime modifiedEndDateTime = DateTime.parse(modifiedBefore);
        modifiedFilter = builder.attribute(Metacard.MODIFIED).is().before().date(modifiedEndDateTime.toDate());
    }

    Filter filter = null;
    if ((createdFilter != null) && (modifiedFilter != null)) {
        // Filter by both created and modified dates
        filter = builder.allOf(createdFilter, modifiedFilter);
    } else if (createdFilter != null) {
        // Only filter by created date
        filter = createdFilter;
    } else if (modifiedFilter != null) {
        // Only filter by modified date
        filter = modifiedFilter;
    } else {
        // Don't filter by date range
        filter = builder.attribute(Metacard.ID).is().like().text(WILDCARD);
    }

    if (cqlFilter != null) {
        filter = CQL.toFilter(cqlFilter);
    }

    QueryImpl query = new QueryImpl(filter);
    query.setRequestsTotalResultsCount(false);
    query.setPageSize(pageSize);

    Map<String, Serializable> props = new HashMap<String, Serializable>();
    // Avoid caching all results while dumping with native query mode
    props.put("mode", "native");

    final AtomicLong resultCount = new AtomicLong(0);
    long start = System.currentTimeMillis();

    SourceResponse response = catalog.query(new QueryRequestImpl(query, props));

    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(multithreaded);
    RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    final ExecutorService executorService = new ThreadPoolExecutor(multithreaded, multithreaded, 0L,
            TimeUnit.MILLISECONDS, blockingQueue, rejectedExecutionHandler);

    while (response.getResults().size() > 0) {
        response = catalog.query(new QueryRequestImpl(query, props));

        if (multithreaded > 1) {
            final List<Result> results = new ArrayList<Result>(response.getResults());
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    for (final Result result : results) {
                        Metacard metacard = result.getMetacard();
                        try {
                            exportMetacard(dumpDir, metacard);
                        } catch (IOException | CatalogTransformerException e) {
                            executorService.shutdownNow();
                        }
                        printStatus(resultCount.incrementAndGet());
                    }
                }
            });
        } else {
            for (final Result result : response.getResults()) {
                Metacard metacard = result.getMetacard();
                exportMetacard(dumpDir, metacard);
                printStatus(resultCount.incrementAndGet());
            }
        }

        if (response.getResults().size() < pageSize || pageSize == -1) {
            break;
        }

        if (pageSize > 0) {
            query.setStartIndex(query.getStartIndex() + pageSize);
        }
    }

    executorService.shutdown();

    while (!executorService.isTerminated()) {
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            // ignore
        }
    }

    long end = System.currentTimeMillis();
    String elapsedTime = timeFormatter.print(new Period(start, end).withMillis(0));
    console.printf(" %d file(s) dumped in %s\t%n", resultCount.get(), elapsedTime);
    LOGGER.info("{} file(s) dumped in {}", resultCount.get(), elapsedTime);
    console.println();

    return null;
}

From source file:org.codice.ddf.commands.catalog.IngestCommand.java

License:Open Source License

@Override
protected Object doExecute() throws Exception {

    final CatalogFacade catalog = getCatalog();
    final File inputFile = new File(filePath);

    if (!inputFile.exists()) {
        printErrorMessage("File or directory [" + filePath + "] must exist.");
        console.println("If the file does indeed exist, try putting the path in quotes.");
        return null;
    }/*from  w w  w .  java  2 s.c  o  m*/

    if (deprecatedBatchSize != DEFAULT_BATCH_SIZE) {
        // user specified the old style batch size, so use that
        printErrorMessage(
                "Batch size positional argument is DEPRECATED, please use --batchsize option instead.");
        batchSize = deprecatedBatchSize;
    }

    if (batchSize <= 0) {
        printErrorMessage(
                "A batch size of [" + batchSize + "] was supplied. Batch size must be greater than 0.");
        return null;
    }

    if (!StringUtils.isEmpty(failedDir)) {
        failedIngestDirectory = new File(failedDir);
        if (!verifyFailedIngestDirectory()) {
            return null;
        }

        /**
         * Batch size is always set to 1, when using an Ingest Failure Directory.  If a batch size is specified by the user, issue
         * a warning stating that a batch size of 1 will be used.
         */
        if (batchSize != DEFAULT_BATCH_SIZE) {
            console.println("WARNING: An ingest failure directory was supplied in addition to a batch size of "
                    + batchSize
                    + ". When using an ingest failure directory, the batch size must be 1. Setting batch size to 1.");
        }

        batchSize = 1;
    }

    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(multithreaded);
    RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    ExecutorService executorService = new ThreadPoolExecutor(multithreaded, multithreaded, 0L,
            TimeUnit.MILLISECONDS, blockingQueue, rejectedExecutionHandler);

    if (inputFile.isDirectory()) {
        final long start = System.currentTimeMillis();

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                fileCount.getAndSet(getFileCount(inputFile));
            }
        });

        printProgressAndFlush(start, fileCount.get(), ingestCount.get());

        IngestVisitor visitor = new IngestVisitor(start, catalog, executorService);
        try {
            Files.walkFileTree(Paths.get(filePath), visitor);
            visitor.done();
        } finally {
            executorService.shutdown();
        }

        while (!executorService.isTerminated()) {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                // ignore
            }
        }

        printProgressAndFlush(start, fileCount.get(), ingestCount.get());

        long end = System.currentTimeMillis();

        console.println();
        String elapsedTime = timeFormatter.print(new Period(start, end).withMillis(0));
        console.printf(" %d file(s) ingested in %s", ingestCount.get(), elapsedTime);
        LOGGER.info("{} file(s) ingested in {} [{} records/sec]", ingestCount.get(), elapsedTime,
                calculateRecordsPerSecond(ingestCount.get(), start, end));
        INGEST_LOGGER.info("{} file(s) ingested in {} [{} records/sec]", ingestCount.get(), elapsedTime,
                calculateRecordsPerSecond(ingestCount.get(), start, end));
        if (INGEST_LOGGER.isWarnEnabled() && fileCount.get() != ingestCount.get()) {
            console.println();
            String failedAmount = Integer.toString(fileCount.get() - ingestCount.get());
            printErrorMessage(
                    failedAmount + " file(s) failed to be ingested.  See the ingest log for more details.");
            INGEST_LOGGER.warn("{} files(s) failed to be ingested.", failedAmount);
        }

        return null;
    } else if (inputFile.isFile()) {
        executorService.shutdown();

        ArrayList<Metacard> metacards = new ArrayList<Metacard>(batchSize);
        Metacard result = null;
        try {
            result = readMetacard(inputFile);
        } catch (IngestException e) {
            result = null;
            printErrorMessage("Failed to ingest file [" + inputFile.getAbsolutePath()
                    + "].  See the ingest log for more details.");
            logIngestException(e, inputFile);
            if (failedIngestDirectory != null) {
                moveToFailedIngestDirectory(inputFile);
            }
        }

        if (result != null) {
            metacards.add(result);
        }

        if (metacards.size() > 0) {
            CreateResponse createResponse = null;
            try {
                createResponse = createMetacards(catalog, metacards);
            } catch (IngestException e) {
                createResponse = null;
                printErrorMessage(inputFile.getAbsolutePath() + " failed ingest.");
                if (INGEST_LOGGER.isWarnEnabled()) {
                    INGEST_LOGGER.warn("{} failed ingest", inputFile.getAbsolutePath(), e);
                }
                if (failedIngestDirectory != null) {
                    moveToFailedIngestDirectory(inputFile);
                }
            } catch (SourceUnavailableException e) {
                createResponse = null;
                printErrorMessage(inputFile.getAbsolutePath() + " failed ingest.");
                if (INGEST_LOGGER.isWarnEnabled()) {
                    INGEST_LOGGER.warn("{} failed ingest", inputFile.getAbsolutePath(), e);
                }
                if (failedIngestDirectory != null) {
                    moveToFailedIngestDirectory(inputFile);
                }
            }

            if (createResponse != null) {
                List<Metacard> recordsCreated = createResponse.getCreatedMetacards();
                console.println(recordsCreated.size() + " file(s) created.");
                for (Metacard record : recordsCreated) {
                    console.println("ID: " + record.getId() + " created.");
                }
                if (INGEST_LOGGER.isDebugEnabled()) {
                    INGEST_LOGGER.debug("{} file(s) created. {}", metacards.size(), buildIngestLog(metacards));
                }
            }
        }
        return null;
    }

    executorService.shutdown();
    console.println("Could not execute command.");
    return null;
}