Example usage for org.joda.time Duration Duration

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

Introduction

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

Prototype

public Duration(Object duration) 

Source Link

Document

Creates a duration from the specified object using the org.joda.time.convert.ConverterManager ConverterManager .

Usage

From source file:com.chiorichan.tasks.Timings.java

License:Open Source License

/**
 * Converts the input value into a human readable string, e.g., 0 Day(s) 3 Hour(s) 13 Minutes(s) 42 Second(s).
 *
 * @param seconds The duration in seconds
 * @return Human readable duration string
 *//*w  ww. j  a va 2s .  c om*/
public static String readoutDuration(Number seconds) {
    Duration duration = new Duration(seconds);
    PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix(" Day(s) ").appendHours()
            .appendSuffix(" Hour(s) ").appendMinutes().appendSuffix(" Minute(s) ").appendSeconds()
            .appendSuffix(" Second(s)").toFormatter();
    return formatter.print(duration.toPeriod());
}

From source file:com.chiorichan.utils.UtilSystem.java

License:Open Source License

public static String uptime() {
    Duration duration = new Duration(System.currentTimeMillis() - AppLoader.startTime);
    PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix(" Day(s) ").appendHours()
            .appendSuffix(" Hour(s) ").appendMinutes().appendSuffix(" Minute(s) ").appendSeconds()
            .appendSuffix(" Second(s)").toFormatter();
    return formatter.print(duration.toPeriod());
}

From source file:com.claresco.tinman.sql.XapiResultSQLReader.java

License:Open Source License

protected XapiResult retrieveByID(int theID) throws SQLException {
    this.myIDRetrievalStatement.setInt(1, theID);

    myResult = this.myIDRetrievalStatement.executeQuery();

    if (isResulEmpty()) {
        return null;
    }//w w w  .j a v a 2 s  .co  m

    Double theScaled;
    Double theRaw;
    Double theMin;
    Double theMax;

    myResult.next();

    // Prim short for primitive type
    double thePrimScaled = myResult.getDouble("rsltscaled");
    if (myResult.wasNull()) {
        theScaled = null;
    } else {
        theScaled = new Double(thePrimScaled);
    }

    double thePrimRaw = myResult.getDouble("rsltrawscore");
    if (myResult.wasNull()) {
        theRaw = null;
    } else {
        theRaw = new Double(thePrimRaw);
    }

    double thePrimMin = myResult.getDouble("rsltminscore");
    if (myResult.wasNull()) {
        theMin = null;
    } else {
        theMin = new Double(thePrimMin);
    }

    double thePrimMax = myResult.getDouble("rsltmaxscore");
    if (myResult.wasNull()) {
        theMax = null;
    } else {
        theMax = new Double(thePrimMax);
    }

    XapiScore theScore = new XapiScore(theScaled, theRaw, theMin, theMax);
    if (theScore.isEmpty()) {
        theScore = null;
    }

    String theResponse = myResult.getString("rsltresponse");

    long msDuration = myResult.getLong("rsltduration");
    Duration theDuration = new Duration(msDuration);

    Boolean theSuccess;
    Boolean theComplete;
    boolean thePrimSuccess = myResult.getBoolean("rsltsuccess");
    if (myResult.wasNull()) {
        theSuccess = null;
    } else {
        theSuccess = new Boolean(thePrimSuccess);
    }

    boolean thePrimComplete = myResult.getBoolean("rsltcomplete");
    if (myResult.wasNull()) {
        theComplete = null;
    } else {
        theComplete = new Boolean(thePrimComplete);
    }

    return new XapiResult(theScore, theSuccess, theComplete, theResponse, theDuration);
}

From source file:com.daemon.database.SearchTerm.java

License:Open Source License

/**
 * Copy constructor./*from w w w.j  av  a2  s .c  o  m*/
 */
public SearchTerm(SearchTerm term) {
    _id = term._id;
    _term = term._term;
    _isActive = term._isActive;
    _current_start = new DateTime(term._current_start.getMillis());
    if (term._old_start != null)
        _old_start = new DateTime(term._old_start.getMillis());
    _interval_length = new Duration(term._interval_length.getMillis());
    _lastFetchedTweetId = term._lastFetchedTweetId;
    _priority = term._priority;
    if (term._timeLastFetched != null)
        _timeLastFetched = new DateTime(term._timeLastFetched.getMillis());
    _lastFetchedTweetCount = term._lastFetchedTweetCount;
    _whenCreated = new DateTime(term._whenCreated.getMillis());
}

From source file:com.daemon.database.SearchTerm.java

License:Open Source License

/**
 * Load a search term object identified by its Id from the database
 * and in a java search term object. Should only be used by the Tests.
 * Throws a SQLException if the id is not found in the Database
 * //  ww  w. ja v  a  2s.c  om
 * @param id The id identifying the search term object.
 * @return Returns the correct search term object or null, if there is
 * no such item identified by Id.
 */
public static SearchTerm load(int id) throws SQLException {
    String sqlSelect = "SELECT * FROM search_terms WHERE id = ?";

    Connection conn = null;
    PreparedStatement prepStatement = null;
    ResultSet resSet = null;

    SearchTerm searchTerm = null;
    FileInputStream fis = null;

    try {
        Properties props = new Properties();
        fis = new FileInputStream(DATABASE_PROPERTY_PATH);
        props.load(fis);
        Class.forName(props.getProperty("javabase.jdbc.driver"));

        String dbUrl = props.getProperty("javabase.jdbc.url") + props.getProperty("database.name") + "?user="
                + props.getProperty("javabase.jdbc.username") + "&password="
                + props.getProperty("javabase.jdbc.password") + "&useLegacyDatetimeCode=false"
                + "&serverTimezone=UTC";
        conn = DriverManager.getConnection(dbUrl);

        // Get the row
        prepStatement = conn.prepareStatement(sqlSelect);
        prepStatement.setInt(1, id);
        prepStatement.execute();
        resSet = prepStatement.getResultSet();
        resSet.first();

        // Fill the object

        // column - name
        // 2 - term, 4 - current_start
        searchTerm = new SearchTerm(resSet.getString(2),
                new DateTime(resSet.getTimestamp(4, Localization.UTC).getTime()));
        //1 id
        searchTerm._id = resSet.getInt(1);
        // 3 active
        searchTerm.setActive(resSet.getBoolean(3));
        // 5 old_start
        Timestamp oldStart = resSet.getTimestamp(5, Localization.UTC);
        if (!resSet.wasNull())
            searchTerm.setOldStart(new DateTime(oldStart.getTime()));
        // 6 interval_length

        // Dirty hack: Because we cannot get every time via getTimestamp, we have to get
        // the byte stream and convert it into a string time.
        byte[] arr = resSet.getBytes(6);
        String intervalLength = new String(arr);
        searchTerm.setIntervalLength(
                new Duration(Localization.DURATION_FORMATTER.parsePeriod(intervalLength).toStandardDuration()));

        // 7 priority
        searchTerm.setPriority(resSet.getInt(7));
        if (resSet.wasNull())
            searchTerm.setPriority(null);
        // 8 time_last_fetched
        Timestamp lastFetched = resSet.getTimestamp(8, Localization.UTC);
        if (!resSet.wasNull())
            searchTerm.setTimeLastFetched(new DateTime(lastFetched.getTime()));
        // 9 last_fetched_tweet_id
        Long lastFetchedTweetId = resSet.getLong(9);
        if (!resSet.wasNull())
            searchTerm.setLastFetchedTweetId(lastFetchedTweetId);
        // 10 last_fetched_tweet_count
        searchTerm.setLastFetchedTweetCount(resSet.getInt(10));
        if (resSet.wasNull())
            searchTerm.setLastFetchedTweetCount(null);
        //11 when_created
        Timestamp when_created = resSet.getTimestamp(11, Localization.UTC);
        searchTerm.setWhenCreated(new DateTime(when_created.getTime()));

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException sqlEx) {
        sqlEx.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (resSet != null)
            resSet.close();

        if (prepStatement != null)
            prepStatement.close();

        if (conn != null)
            conn.close();
    }

    return searchTerm;
}

From source file:com.daemon.database.SearchTerm.java

License:Open Source License

/**
 * Load a search term object identified by its Id from the database
 * and in a java search term object. Should only be used by the Tests.
 * Throws a SQLException if the id is not found in the Database
 * /*w ww. ja va 2s .c  o  m*/
 * @param term The name identifying the search term object.
 * @return Returns the correct search term object or null, if there is
 * no such item identified by term.
 */
public static SearchTerm load(String term) throws SQLException {
    String sqlSelect = "SELECT * FROM search_terms WHERE term = ?";

    Connection conn = null;
    PreparedStatement prepStatement = null;
    ResultSet resSet = null;

    SearchTerm searchTerm = null;
    FileInputStream fis = null;

    try {
        Properties props = new Properties();
        fis = new FileInputStream(DATABASE_PROPERTY_PATH);
        props.load(fis);
        Class.forName(props.getProperty("javabase.jdbc.driver"));

        String dbUrl = props.getProperty("javabase.jdbc.url") + props.getProperty("database.name") + "?user="
                + props.getProperty("javabase.jdbc.username") + "&password="
                + props.getProperty("javabase.jdbc.password") + "&useLegacyDatetimeCode=false"
                + "&serverTimezone=UTC";
        conn = DriverManager.getConnection(dbUrl);

        // Get the row
        prepStatement = conn.prepareStatement(sqlSelect);
        prepStatement.setString(1, term);
        prepStatement.execute();
        resSet = prepStatement.getResultSet();
        resSet.first();

        // Fill the object

        // column - name
        // 2 - term, 4 - current_start
        searchTerm = new SearchTerm(resSet.getString(2),
                new DateTime(resSet.getTimestamp(4, Localization.UTC).getTime()));
        //1 id
        searchTerm._id = resSet.getInt(1);
        // 3 active
        searchTerm.setActive(resSet.getBoolean(3));
        // 5 old_start
        Timestamp oldStart = resSet.getTimestamp(5, Localization.UTC);
        if (!resSet.wasNull())
            searchTerm.setOldStart(new DateTime(oldStart.getTime()));

        // 6 interval length

        // Dirty hack: Because we cannot get every time via getTimestamp, we have to get the byte stream
        // and convert them into a string time.
        byte[] arr = resSet.getBytes(6);
        String intervalLength = new String(arr);
        searchTerm.setIntervalLength(
                new Duration(Localization.DURATION_FORMATTER.parsePeriod(intervalLength).toStandardDuration()));

        // 7 priority
        searchTerm.setPriority(resSet.getInt(7));
        if (resSet.wasNull())
            searchTerm.setPriority(null);
        // 8 time_last_fetched
        Timestamp lastFetched = resSet.getTimestamp(8, Localization.UTC);
        if (!resSet.wasNull())
            searchTerm.setTimeLastFetched(new DateTime(lastFetched.getTime()));
        // 9 last_fetched_tweet_id
        Long lastFetchedTweetId = resSet.getLong(9);
        if (!resSet.wasNull())
            searchTerm.setLastFetchedTweetId(lastFetchedTweetId);
        // 10 last_fetched_tweet_count
        searchTerm.setLastFetchedTweetCount(resSet.getInt(10));
        if (resSet.wasNull())
            searchTerm.setLastFetchedTweetCount(null);
        //  11 when_created
        Timestamp when_created = resSet.getTimestamp(11, Localization.UTC);
        searchTerm.setWhenCreated(new DateTime(when_created.getTime()));
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException sqlEx) {
        sqlEx.printStackTrace();
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (resSet != null)
            resSet.close();

        if (prepStatement != null)
            prepStatement.close();

        if (conn != null)
            conn.close();
    }

    return searchTerm;
}

From source file:com.daemon.Minion.java

License:Open Source License

/**
 * Calculates the interval length for the given search term (and its meta data).
 * @param metaData The meta data with search term for which the new interval length
 * should be calculated.//  www .ja  v a  2s . c  o m
 * @param logger The log file that is used by the daemon.
 * @param props The properties file that is used by the daemon.
 * @param name The name of the Twitter profile that is used.
 * @return Returns the interval length for the meta data object.
 */
public static Duration calculateIntervalLength(SearchTermMetaData metaData, Logger logger,
        DaemonProperties props, String name) {
    SearchTerm term = metaData.getSearchTerm();
    int count = metaData.getTweetCount();

    double priorityFactor = props.priorityFactors[props.defaultPriorityIndex];

    // Try setting the priority factor
    try {
        priorityFactor = (int) mapPriority(term.getPriority(), props);
    } catch (IllegalArgumentException ex) {
        try {
            if (logger != null) {
                logger.log("Cannot read priority from search term " + term.getTerm() + "(id " + term.getId()
                        + "). Using default value.", name);
            }
        } catch (Exception _) {
        }
    }

    // Time difference between newest tweet and oldest acceptable tweet in minutes
    double timeDiff = 0;

    // If we have no new tweets, this field is empty
    if (metaData.getNewestTweetDate() != null) {
        timeDiff = metaData.getNewestTweetDate().minus(metaData.getOldestTweetDate().getMillis()).getMillis()
                / 60000d;
    }

    long intervalLengthInMin = 0;
    if (timeDiff != 0) {
        // Tweets per minute
        double tpm = ((double) count) / timeDiff;

        // The formula for the interval length in minutes
        intervalLengthInMin = (int) (priorityFactor * (1 / tpm) * props.throttleFactor * 100);
    } else if (count <= 1) {
        // Here: timeDiff == 0
        // This may be a statistical outlier, so we increase the interval length
        // manually and not by formula
        intervalLengthInMin = term.getIntervalLength().getMillis() / 60000 * props.outlierFactor;
    }

    // if timeDiff == 0, but count > 1, we have A LOT of tweets, so interval length
    // should be as low as possible (so it is set to 0).

    // Make sure the interval length does not fall below the given default value
    Duration intervalLength = new Duration(intervalLengthInMin * 60000L);
    if (intervalLength.minus(props.defaultIntervalLength.getMillis()).getMillis() < 0)
        intervalLength = props.defaultIntervalLength;
    else if (intervalLength.minus(props.maxIntervalLength.getMillis()).getMillis() > 0)
        intervalLength = props.maxIntervalLength;

    return intervalLength;
}

From source file:com.esofthead.mycollab.vaadin.web.ui.field.DateTimeOptionField.java

License:Open Source License

private Date getDateValue() {
    Date selectDate = popupDateField.getValue();
    if (selectDate == null) {
        return null;
    }/*from   w ww  .j  a  v a 2  s .c om*/

    DateTime jodaSelectDate = new DateTime(selectDate)
            .toDateTime(DateTimeZone.forTimeZone(AppContext.getUserTimeZone()));
    Date baseDate = new LocalDate(jodaSelectDate).toDate();
    if (hideTimeOption) {
        return new LocalDateTime(baseDate).toDateTime(DateTimeZone.forTimeZone(AppContext.getUserTimeZone()))
                .toDate();
    } else {
        Integer hour = (hourPickerComboBox.getValue() != null)
                ? Integer.parseInt((String) hourPickerComboBox.getValue())
                : 0;
        Integer minus = (minutePickerComboBox.getValue() != null)
                ? Integer.parseInt((String) minutePickerComboBox.getValue())
                : 0;
        String timeFormat = (timeFormatComboBox.getValue() != null) ? (String) timeFormatComboBox.getValue()
                : "AM";
        long milliseconds = calculateMilliSeconds(hour, minus, timeFormat);
        DateTime jodaTime = new DateTime(baseDate).plus(new Duration(milliseconds));
        return new LocalDateTime(jodaTime.getMillis())
                .toDateTime(DateTimeZone.forTimeZone(AppContext.getUserTimeZone())).toDate();
    }
}

From source file:com.evolveum.polygon.connector.googleapps.cache.ConnectorObjectsCache.java

private void configure(GoogleAppsConfiguration configuration) {
    final boolean oldAllowCache = allowCache;
    final Duration oldMaxCacheTTL = maxCacheTTL;
    final Duration oldIgnoreCacheAfterUpdateTTL = ignoreCacheAfterUpdateTTL;

    maxCacheTTL = new Duration(configuration.getMaxCacheTTL());
    ignoreCacheAfterUpdateTTL = new Duration(configuration.getIgnoreCacheAfterUpdateTTL());
    allowCache = Boolean.TRUE.equals(configuration.getAllowCache());

    if (allowCache != oldAllowCache || !maxCacheTTL.equals(oldMaxCacheTTL)
            || !ignoreCacheAfterUpdateTTL.equals(oldIgnoreCacheAfterUpdateTTL)) {
        logger.ok("Cache() - configured with allowCache: " + allowCache + ", maxCacheTTL: "
                + maxCacheTTL.getStandardSeconds() + " s" + ", ignoreCacheAfterUpdateTTL: "
                + ignoreCacheAfterUpdateTTL.getStandardSeconds() + " s");
    }//from ww  w .  ja  va  2 s  .  c  o  m
}

From source file:com.example.geomesa.kafka.KafkaQuickStart.java

License:Open Source License

public static void main(String[] args) throws Exception {
    // read command line args for a connection to Kafka
    CommandLineParser parser = new BasicParser();
    Options options = getCommonRequiredOptions();
    CommandLine cmd = parser.parse(options, args);

    // create the producer and consumer KafkaDataStore objects
    Map<String, String> dsConf = getKafkaDataStoreConf(cmd);
    dsConf.put("isProducer", "true");
    DataStore producerDS = DataStoreFinder.getDataStore(dsConf);
    dsConf.put("isProducer", "false");
    DataStore consumerDS = DataStoreFinder.getDataStore(dsConf);

    // verify that we got back our KafkaDataStore objects properly
    if (producerDS == null) {
        throw new Exception("Null producer KafkaDataStore");
    }/*from  ww w .  j  a v a 2 s.  co m*/
    if (consumerDS == null) {
        throw new Exception("Null consumer KafkaDataStore");
    }

    // create the schema which creates a topic in Kafka
    // (only needs to be done once)
    final String sftName = "KafkaQuickStart";
    final String sftSchema = "name:String,age:Int,dtg:Date,*geom:Point:srid=4326";
    SimpleFeatureType sft = SimpleFeatureTypes.createType(sftName, sftSchema);
    // set zkPath to default if not specified
    String zkPath = (dsConf.get(ZK_PATH) == null) ? "/geomesa/ds/kafka" : dsConf.get(ZK_PATH);
    SimpleFeatureType preppedOutputSft = KafkaDataStoreHelper.createStreamingSFT(sft, zkPath);
    // only create the schema if it hasn't been created already
    if (!Arrays.asList(producerDS.getTypeNames()).contains(sftName))
        producerDS.createSchema(preppedOutputSft);

    System.out.println("Register KafkaDataStore in GeoServer (Press enter to continue)");
    System.in.read();

    // the live consumer must be created before the producer writes features
    // in order to read streaming data.
    // i.e. the live consumer will only read data written after its instantiation
    SimpleFeatureSource consumerFS = consumerDS.getFeatureSource(sftName);
    SimpleFeatureStore producerFS = (SimpleFeatureStore) producerDS.getFeatureSource(sftName);

    // creates and adds SimpleFeatures to the producer every 1/5th of a second
    System.out.println("Writing features to Kafka... refresh GeoServer layer preview to see changes");
    Instant replayStart = new Instant();
    addSimpleFeatures(sft, producerFS);
    Instant replayEnd = new Instant();

    // read from Kafka after writing all the features.
    // LIVE CONSUMER - will obtain the current state of SimpleFeatures
    System.out.println("\nConsuming with the live consumer...");
    SimpleFeatureCollection featureCollection = consumerFS.getFeatures();
    System.out.println(featureCollection.size() + " features were written to Kafka");

    addDeleteNewFeature(sft, producerFS);

    // read from Kafka after writing all the features.
    // LIVE CONSUMER - will obtain the current state of SimpleFeatures
    System.out.println("\nConsuming with the live consumer...");
    featureCollection = consumerFS.getFeatures();
    System.out.println(featureCollection.size() + " features were written to Kafka");

    // the state of the two SimpleFeatures is real time here
    System.out.println("Here are the two SimpleFeatures that were obtained with the live consumer:");
    SimpleFeatureIterator featureIterator = featureCollection.features();
    SimpleFeature feature1 = featureIterator.next();
    SimpleFeature feature2 = featureIterator.next();
    featureIterator.close();
    printFeature(feature1);
    printFeature(feature2);

    // REPLAY CONSUMER - will obtain the state of SimpleFeatures at any specified time
    // Replay consumer requires a ReplayConfig which takes a time range and a
    // duration of time to process
    System.out.println("\nConsuming with the replay consumer...");
    Duration readBehind = new Duration(1000); // 1 second readBehind
    ReplayConfig rc = new ReplayConfig(replayStart, replayEnd, readBehind);
    SimpleFeatureType replaySFT = KafkaDataStoreHelper.createReplaySFT(preppedOutputSft, rc);
    producerDS.createSchema(replaySFT);
    SimpleFeatureSource replayConsumerFS = consumerDS.getFeatureSource(replaySFT.getName());

    // querying for the state of SimpleFeatures approximately 5 seconds before the replayEnd.
    // the ReplayKafkaConsumerFeatureSource will build the state of SimpleFeatures
    // by processing all of the messages that were sent in between queryTime-readBehind and queryTime.
    // only the messages in between replayStart and replayEnd are cached.
    Instant queryTime = replayEnd.minus(5000);
    featureCollection = replayConsumerFS.getFeatures(ReplayTimeHelper.toFilter(queryTime));
    System.out.println(featureCollection.size() + " features were written to Kafka");

    System.out.println("Here are the two SimpleFeatures that were obtained with the replay consumer:");
    featureIterator = featureCollection.features();
    feature1 = featureIterator.next();
    feature2 = featureIterator.next();
    featureIterator.close();
    printFeature(feature1);
    printFeature(feature2);

    if (System.getProperty("clear") != null) {
        // Run Java command with -Dclear=true
        // This will cause a 'clear'
        producerFS.removeFeatures(Filter.INCLUDE);
    }

    System.exit(0);
}