Example usage for org.joda.time.format DateTimeFormatter parseDateTime

List of usage examples for org.joda.time.format DateTimeFormatter parseDateTime

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter parseDateTime.

Prototype

public DateTime parseDateTime(String text) 

Source Link

Document

Parses a date-time from the given text, returning a new DateTime.

Usage

From source file:org.openiot.gsn.utils.Helpers.java

License:Open Source License

public static long convertTimeFromIsoToLong(String time, String format) throws Exception {
    DateTimeFormatter fmt = DateTimeFormat.forPattern(format);
    return fmt.parseDateTime(time).getMillis();
}

From source file:org.openiot.gsn.wrappers.general.CSVHandler.java

License:Open Source License

public static DateTime parseTimeStamp(String format, String value) throws IllegalArgumentException {
    DateTimeFormatter fmt = DateTimeFormat.forPattern(format);
    return fmt.parseDateTime(value);
}

From source file:org.openiot.gsn.wrappers.GridDataWrapper.java

License:Open Source License

private long strTime2Long(String s, String timeFormat) {

    long l = -1;//from w w  w  .  ja  v a 2 s  . c  o  m
    try {
        DateTimeFormatter fmt = DateTimeFormat.forPattern(timeFormat);
        l = fmt.parseDateTime(s).getMillis();
    } catch (java.lang.IllegalArgumentException e) {
        logger.warn(e.getMessage(), e);
    }
    return l;
}

From source file:org.openiot.gsn.wrappers.JDBCWrapper.java

License:Open Source License

public boolean initialize() {
    setName(getWrapperName() + "-" + (++threadCounter));
    AddressBean addressBean = getActiveAddressBean();

    table_name = addressBean.getPredicateValue("table-name");

    databaseURL = addressBean.getPredicateValue("jdbc-url");
    username = addressBean.getPredicateValue("username");
    password = addressBean.getPredicateValue("password");
    driver = addressBean.getPredicateValue("driver");

    if ((databaseURL != null) && (username != null) && (password != null) && (driver != null)) {
        useDefaultStorageManager = false;
        sm = StorageManagerFactory.getInstance(driver, username, password, databaseURL, 8);
        logger.warn("Using specified storage manager: " + databaseURL);
    } else {//from   w w  w . j  a  v  a  2 s .c  o  m
        sm = Main.getDefaultStorage();
        logger.warn("Using default storage manager");
    }

    if (table_name == null) {
        logger.warn("The > table-name < parameter is missing from the wrapper for VS "
                + this.getActiveAddressBean().getVirtualSensorName());
        return false;
    }

    //////////////////
    boolean usePreviousCheckPoint = true;
    String time = addressBean.getPredicateValue("start-time");
    if (time == null) {
        logger.warn("The > start-time < parameter is missing from the wrapper for VS "
                + this.getActiveAddressBean().getVirtualSensorName());
        return false;
    }

    if (time.equalsIgnoreCase("continue")) {
        latest_timed = getLatestProcessed();
        usePreviousCheckPoint = false;
        logger.warn("Mode: continue => " + latest_timed);
    } else if (isISOFormat(time)) {

        try {
            DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
            start_time = fmt.parseDateTime(time).getMillis();
            latest_timed = start_time;
            logger.warn("Mode: ISO => " + latest_timed);
        } catch (IllegalArgumentException e) {
            logger.warn("The > start-time < parameter is malformed (looks like ISO8601) for VS "
                    + this.getActiveAddressBean().getVirtualSensorName());
            return false;
        }
    } else if (isLong(time)) {
        try {
            latest_timed = Long.parseLong(time);
            logger.warn("Mode: epoch => " + latest_timed);
        } catch (NumberFormatException e) {
            logger.warn("The > start-time < parameter is malformed (looks like epoch) for VS "
                    + this.getActiveAddressBean().getVirtualSensorName());
            return false;
        }
    } else {
        logger.warn(
                "Incorrectly formatted > start-time < accepted values are: 'continue' (from latest element in destination table), iso-date (e.g. 2009-11-02T00:00:00.000+00:00), or epoch (e.g. 1257946505000)");
        return false;
    }

    //////////////////

    checkPointDir = addressBean.getPredicateValueWithDefault("check-point-directory", "jdbc-check-points");
    checkPointFile = checkPointDir + "/" + table_name + "-"
            + this.getActiveAddressBean().getVirtualSensorName();
    new File(checkPointDir).mkdirs();

    if (usePreviousCheckPoint) {
        logger.warn("trying to read latest timestamp from chekpoint file ... " + checkPointFile);
        try {
            if (getLatestTimeStampFromCheckPoint() != 0) {
                latest_timed = getLatestTimeStampFromCheckPoint();
                logger.warn("latest ts => " + latest_timed);
            } else
                logger.warn("wrong value for latest ts (" + getLatestTimeStampFromCheckPoint() + "), ignored");
        } catch (IOException e) {
            logger.warn("Checkpoints couldn't be used due to IO exception.");
            logger.warn(e.getMessage(), e);
        }
    }

    //////////////////

    Connection connection = null;
    try {
        logger.info("Initializing the structure of JDBCWrapper with : " + table_name);
        connection = sm.getConnection();

        outputFormat = sm.tableToStructureByString(table_name, connection);
    } catch (SQLException e) {
        logger.error(e.getMessage(), e);
        return false;
    } finally {
        sm.close(connection);
    }

    dataFieldsLength = outputFormat.length;
    dataFieldNames = new String[dataFieldsLength];
    dataFieldTypes = new Byte[dataFieldsLength];

    for (int i = 0; i < outputFormat.length; i++) {
        dataFieldNames[i] = outputFormat[i].getName();
        dataFieldTypes[i] = outputFormat[i].getDataTypeID();
    }

    return true;
}

From source file:org.openiot.gsn.wrappers.TetraedreFluoWrapper.java

License:Open Source License

public boolean initialize() {
    setName(getWrapperName() + "-" + (++threadCounter));
    AddressBean addressBean = getActiveAddressBean();

    table_name = addressBean.getPredicateValue("table-name");
    physical_input = addressBean.getPredicateValue("physical-input");
    databaseURL = addressBean.getPredicateValue("jdbc-url");
    username = addressBean.getPredicateValue("username");
    password = addressBean.getPredicateValue("password");
    driver = addressBean.getPredicateValue("driver");

    if ((databaseURL != null) && (username != null) && (password != null) && (driver != null)) {
        useDefaultStorageManager = false;
        sm = StorageManagerFactory.getInstance(driver, username, password, databaseURL, 8);
        logger.warn("Using specified storage manager: " + databaseURL);
    } else {/*ww w .ja  v  a 2s . c o m*/
        sm = Main.getDefaultStorage();
        logger.warn("Using default storage manager");
    }

    if (table_name == null) {
        logger.warn("The > table-name < parameter is missing from the wrapper for VS "
                + this.getActiveAddressBean().getVirtualSensorName());
        return false;
    }

    //////////////////
    boolean usePreviousCheckPoint = true;
    String time = addressBean.getPredicateValue("start-time");
    if (time == null) {
        logger.warn("The > start-time < parameter is missing from the wrapper for VS "
                + this.getActiveAddressBean().getVirtualSensorName());
        return false;
    }

    if (time.equalsIgnoreCase("continue")) {
        latest_timed = getLatestProcessed();
        usePreviousCheckPoint = false;
        logger.warn("Mode: continue => " + latest_timed);
    } else if (isISOFormat(time)) {

        try {
            DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
            start_time = fmt.parseDateTime(time).getMillis();
            latest_timed = start_time;
            logger.warn("Mode: ISO => " + latest_timed);
        } catch (IllegalArgumentException e) {
            logger.warn("The > start-time < parameter is malformed (looks like ISO8601) for VS "
                    + this.getActiveAddressBean().getVirtualSensorName());
            return false;
        }
    } else if (isLong(time)) {
        try {
            latest_timed = Long.parseLong(time);
            logger.warn("Mode: epoch => " + latest_timed);
        } catch (NumberFormatException e) {
            logger.warn("The > start-time < parameter is malformed (looks like epoch) for VS "
                    + this.getActiveAddressBean().getVirtualSensorName());
            return false;
        }
    } else {
        logger.warn(
                "Incorrectly formatted > start-time < accepted values are: 'continue' (from latest element in destination table), iso-date (e.g. 2009-11-02T00:00:00.000+00:00), or epoch (e.g. 1257946505000)");
        return false;
    }

    //////////////////

    checkPointDir = addressBean.getPredicateValueWithDefault("check-point-directory", "jdbc-check-points");
    checkPointFile = checkPointDir + "/" + table_name + "-"
            + this.getActiveAddressBean().getVirtualSensorName();
    new File(checkPointDir).mkdirs();

    if (usePreviousCheckPoint) {
        logger.warn("trying to read latest timestamp from chekpoint file ... " + checkPointFile);
        try {
            if (getLatestTimeStampFromCheckPoint() != 0) {
                latest_timed = getLatestTimeStampFromCheckPoint();
                logger.warn("latest ts => " + latest_timed);
            } else
                logger.warn("wrong value for latest ts (" + getLatestTimeStampFromCheckPoint() + "), ignored");
        } catch (IOException e) {
            logger.warn("Checkpoints couldn't be used due to IO exception.");
            logger.warn(e.getMessage(), e);
        }
    }

    //////////////////

    Connection connection = null;
    try {
        logger.info("Initializing the structure of JDBCWrapper with : " + table_name);
        connection = sm.getConnection();

        outputFormat = sm.tableToStructureByString(table_name, connection);
    } catch (SQLException e) {
        logger.error(e.getMessage(), e);
        return false;
    } finally {
        sm.close(connection);
    }

    dataFieldsLength = outputFormat.length;
    dataFieldNames = new String[dataFieldsLength];
    dataFieldTypes = new Byte[dataFieldsLength];

    for (int i = 0; i < outputFormat.length; i++) {
        dataFieldNames[i] = outputFormat[i].getName();
        dataFieldTypes[i] = outputFormat[i].getDataTypeID();
    }

    return true;
}

From source file:org.openiot.gsn.wrappers.TetraedreNMCWrapper.java

License:Open Source License

public boolean initialize() {
    setName(getWrapperName() + "-" + (++threadCounter));
    AddressBean addressBean = getActiveAddressBean();

    table_name = addressBean.getPredicateValue("table-name");
    databaseURL = addressBean.getPredicateValue("jdbc-url");
    username = addressBean.getPredicateValue("username");
    password = addressBean.getPredicateValue("password");
    driver = addressBean.getPredicateValue("driver");

    if ((databaseURL != null) && (username != null) && (password != null) && (driver != null)) {
        useDefaultStorageManager = false;
        sm = StorageManagerFactory.getInstance(driver, username, password, databaseURL, 8);
        logger.warn("Using specified storage manager: " + databaseURL);
    } else {/*from   w  w  w.  ja v a2 s.c o  m*/
        sm = Main.getDefaultStorage();
        logger.warn("Using default storage manager");
    }

    if (table_name == null) {
        logger.warn("The > table-name < parameter is missing from the wrapper for VS "
                + this.getActiveAddressBean().getVirtualSensorName());
        return false;
    }

    //////////////////
    boolean usePreviousCheckPoint = true;
    String time = addressBean.getPredicateValue("start-time");
    if (time == null) {
        logger.warn("The > start-time < parameter is missing from the wrapper for VS "
                + this.getActiveAddressBean().getVirtualSensorName());
        return false;
    }

    if (time.equalsIgnoreCase("continue")) {
        latest_timed = getLatestProcessed();
        usePreviousCheckPoint = false;
        logger.warn("Mode: continue => " + latest_timed);
    } else if (isISOFormat(time)) {

        try {
            DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
            start_time = fmt.parseDateTime(time).getMillis();
            latest_timed = start_time;
            logger.warn("Mode: ISO => " + latest_timed);
        } catch (IllegalArgumentException e) {
            logger.warn("The > start-time < parameter is malformed (looks like ISO8601) for VS "
                    + this.getActiveAddressBean().getVirtualSensorName());
            return false;
        }
    } else if (isLong(time)) {
        try {
            latest_timed = Long.parseLong(time);
            logger.warn("Mode: epoch => " + latest_timed);
        } catch (NumberFormatException e) {
            logger.warn("The > start-time < parameter is malformed (looks like epoch) for VS "
                    + this.getActiveAddressBean().getVirtualSensorName());
            return false;
        }
    } else {
        logger.warn(
                "Incorrectly formatted > start-time < accepted values are: 'continue' (from latest element in destination table), iso-date (e.g. 2009-11-02T00:00:00.000+00:00), or epoch (e.g. 1257946505000)");
        return false;
    }

    //////////////////

    checkPointDir = addressBean.getPredicateValueWithDefault("check-point-directory", "jdbc-check-points");
    checkPointFile = checkPointDir + "/" + table_name + "-"
            + this.getActiveAddressBean().getVirtualSensorName();
    new File(checkPointDir).mkdirs();

    if (usePreviousCheckPoint) {
        logger.warn("trying to read latest timestamp from chekpoint file ... " + checkPointFile);
        try {
            if (getLatestTimeStampFromCheckPoint() != 0) {
                latest_timed = getLatestTimeStampFromCheckPoint();
                logger.warn("latest ts => " + latest_timed);
            } else
                logger.warn("wrong value for latest ts (" + getLatestTimeStampFromCheckPoint() + "), ignored");
        } catch (IOException e) {
            logger.warn("Checkpoints couldn't be used due to IO exception.");
            logger.warn(e.getMessage(), e);
        }
    }

    //////////////////

    Connection connection = null;
    try {
        logger.info("Initializing the structure of JDBCWrapper with : " + table_name);
        connection = sm.getConnection();

        outputFormat = sm.tableToStructureByString(table_name, connection);
    } catch (SQLException e) {
        logger.error(e.getMessage(), e);
        return false;
    } finally {
        sm.close(connection);
    }

    dataFieldsLength = outputFormat.length;
    dataFieldNames = new String[dataFieldsLength];
    dataFieldTypes = new Byte[dataFieldsLength];

    for (int i = 0; i < outputFormat.length; i++) {
        dataFieldNames[i] = outputFormat[i].getName();
        dataFieldTypes[i] = outputFormat[i].getDataTypeID();
    }

    return true;
}

From source file:org.openlmis.core.utils.DateUtil.java

License:Open Source License

public static DateTime cutTimeStamp(DateTime dateTime) {
    DateTimeFormatter format = DateTimeFormat.forPattern(DB_DATE_FORMAT);
    String formatDate = format.print(dateTime);
    return format.parseDateTime(formatDate);
}

From source file:org.openmainframe.ade.ext.main.Train.java

License:Open Source License

/**
 * Parse the AdeExt Argument.  This method is used to parse
 * the input argument in AdeCore.//from w ww . java  2 s.  com
 * 
 * @param args
 * @return 
 * @throws AdeException
 */
public final ArrayList<String> parseAdeExtArgs(String[] args) throws AdeException {
    ArrayList<String> adeArgs;
    adeArgs = new ArrayList<String>();

    if (args.length == 0) {
        usageError("Expecting at least one argument");
        return new ArrayList<String>(0);
    }
    if (args.length > 3) {
        usageError("Too many arguments");
    }

    /* Convert the Source argument to AnalysisGroup */
    if (args[0].equalsIgnoreCase("all")) {
        adeArgs.add("-a");
    } else {
        /* Add the source.  
         * Note that Ade expect analysisGroup instead of source. 
         *
         * In Upload and Analyze, the AnalysisGroup always use the same name as 
         * the sourceId.  Therefore, the sourceId input here can be used as 
         * AnalysisGroup name.
         */
        adeArgs.add("-s");
        adeArgs.add(args[0]);
    }

    //"MM/dd/yyyy HH:mm ZZZ"
    final DateTimeFormatter outFormatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm ZZZ").withOffsetParsed()
            .withZoneUTC();

    /* Handle the end date if exist */

    if (args.length > 2) {
        final DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy").withOffsetParsed()
                .withZoneUTC();
        m_endDateTime = formatter.parseDateTime(args[2]);

        /* Move the endDate's time to the end of date.  AdeCore requires the end date
         * to be the start day of the next day. 
         * 
         * For example, if the endDate specified is 10/10.  The endDate will be set to
         * 10/11 00:00:00.  This will include the entire 10/10 in the Model.  */
        adeArgs.add("-end-date");
        m_endDateTime = m_endDateTime.withDurationAdded(Duration.standardDays(1), 1);
        adeArgs.add(m_endDateTime.toString(outFormatter));
    } else {
        /* If endDate wasn't specified, don't specify it. */
        m_endDateTime = null;
    }

    /* Handle the start date if exist */
    if (args.length > 1) {
        final DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy").withOffsetParsed()
                .withZoneUTC();
        m_startDateTime = formatter.parseDateTime(args[1]);
        adeArgs.add("-start-date");
        adeArgs.add(m_startDateTime.toString(outFormatter));
    } else {
        m_startDateTime = null;
    }

    /* call the super class with the converted arguments */
    StringBuilder bldadeArgsString = new StringBuilder("");
    for (String arg : adeArgs) {
        bldadeArgsString.append(arg + " ");
    }
    logger.trace("Arguments used to call TrainLog: " + bldadeArgsString.toString());

    return adeArgs;
}

From source file:org.openmainframe.ade.ext.os.parser.LinuxSyslog3164ParserBase.java

License:Open Source License

/**
 * Retrieves the date parsed from the header of a log. Unless otherwise defined in the properties file,
 * we have to use some logic to figure out the year. After parsing the date, we need to correct the time-zone. 
 * Then we set the dateTime to the current year. Now we need to check the dateTime and see if it's after today.
 * The logic is as follows:/*from  w ww  .j av  a 2s .co m*/
 *      - If Log time-stamp < End of day of today 
 *          (comparing Month, Day, Hour, Minutes, Seconds, with year missing), 
 *          assume it's this year.
 *      - If Log time-stamp > End of day of today 
 *          (comparing Month, Day, Hour, Minutes, Seconds, with year missing), 
 *          assume it's previous year.
 * 
 * The following restrictions will be made to customer for BulkLoad:
 *      - Cannot upload logs older than 11 months.
 *      - Cannot upload logs that are continuous for more than 11 months.
 * 
 * Note: END OF TODAY is purposely chosen instead of START OF TODAY in case a user bulk loads logs that 
 * belongs to today.  It's not possible/likely that a user would bulk load logs from last year of the 
 * same day with the restriction we specified above.
 * @param source the source name string value.
 * @param s the date and time string value.
 * @return Date object with date/time-stamp of the Linux log.
 */
@Override
public final Date toDate(String source, String s) {
    DateTime dt = null;
    for (DateTimeFormatter fmt : dt_formatters) {
        try {
            dt = fmt.parseDateTime(s);
            dt = dt.withZoneRetainFields(INPUT_TIME_ZONE);
            dt = dt.withZone(OUTPUT_TIME_ZONE);

            /* Year must be set after all the time is normalized to the timezone */
            dt = dt.withYear(curYear);

            if (s_linuxAdeExtProperties.isYearDefined()) {
                yearSetter = LinuxSyslogYearSetter.getYearSetter(source);

                /* If years is defined, then, use the defined year as a starting year */
                final int yearToUse = yearSetter.getDesiredYear(dt);
                dt = dt.withYear(yearToUse);
            } else if (dt.isAfter(END_OF_TODAY)) {
                /* Set DateTime to previous year */
                dt = dt.withYear(curYear - 1);
            } else {
                dt = dt.withYear(curYear);
            }

            /* AdeCore will take the Java Date object, and convert 
             * it to the output time-zone, then extract the hour. */
            return dt.toDate();
        } catch (IllegalArgumentException e) {
            /* This exception can occur normally when iterating
             * through the DateTimeFormatter objects. It is only 
             * an error worth noting when the dt object is not null.
             */
            if (dt != null) {
                s_logger.error("Invalid argument encountered.", e);
            }
        }
    }
    throw new IllegalArgumentException("Failed to parse date " + s);
}

From source file:org.openmrs.mobile.utilities.DateUtils.java

License:Open Source License

public static DateTime convertTimeString(String dateAsString) {
    DateTime date = null;/*from   www. java  2  s.c  o m*/
    if (StringUtils.notNull(dateAsString)) {
        try {

            DateTimeFormatter originalFormat = DateTimeFormat.forPattern(OPEN_MRS_REQUEST_FORMAT);
            date = originalFormat.parseDateTime(dateAsString);

        } catch (Exception ex) {
            DateTimeFormatter originalFormat = DateTimeFormat.forPattern(OPEN_MRS_REQUEST_PATIENT_FORMAT);
            date = originalFormat.parseDateTime(dateAsString);
        }
    }

    return date;
}