Example usage for org.joda.time.format ISODateTimeFormat dateTime

List of usage examples for org.joda.time.format ISODateTimeFormat dateTime

Introduction

In this page you can find the example usage for org.joda.time.format ISODateTimeFormat dateTime.

Prototype

public static DateTimeFormatter dateTime() 

Source Link

Document

Returns a formatter that combines a full date and time, separated by a 'T' (yyyy-MM-dd'T'HH:mm:ss.SSSZZ).

Usage

From source file:org.jevis.commons.json.JsonFactory.java

License:Open Source License

public static JsonSample buildSample(JEVisSample sample) throws JEVisException {
    JsonSample json = new JsonSample();
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    json.setTs(fmt.print(sample.getTimestamp()));
    json.setValue(sample.getValue().toString());
    json.setNote(sample.getNote());//  ww  w .ja va  2 s  .  c om
    return json;
}

From source file:org.jongo.demo.Demo.java

License:Open Source License

private static void generateDemoDatabase(final DatabaseConfiguration dbcfg) {
    final String database = dbcfg.getDatabase();
    QueryRunner run = new QueryRunner(JDBCConnectionFactory.getDataSource(dbcfg));

    l.info("Generating Demo resources in database " + database);
    update(run, getCreateUserTable());//  w  ww  .  j a  va  2s .  c  om
    update(run, getCreateMakersTable());
    update(run, getCreateCarsTable());
    update(run, getCreateCommentsTable());
    update(run, getCreatePicturesTable());
    update(run, getCreateSalesStatsTable());
    update(run, getCreateSalesByMakerAndModelStatsTable());
    update(run, getCreateEmptyTable());

    l.info("Generating Demo Data in database " + database);

    final String insertUserQuery = "INSERT INTO users (name, age, birthday, credit) VALUES (?,?,?,?)";
    update(run, insertUserQuery, "foo", 30, "1982-12-13", 32.5);
    update(run, insertUserQuery, "bar", 33, "1992-01-15", 0);

    for (CarMaker maker : CarMaker.values()) {
        update(run, "INSERT INTO maker (name, realname) VALUES (?,?)", maker.name(), maker.getRealName());
    }

    final String insertCar = "INSERT INTO car (maker, model, year, fuel, transmission, currentMarketValue, newValue) VALUES (?,?,?,?,?,?,?)";
    update(run, insertCar, "CITROEN", "C2", 2008, "Gasoline", "Manual", 9000, 13000);
    update(run,
            "INSERT INTO car (maker, model, year, transmission, currentMarketValue, newValue) VALUES (?,?,?,?,?,?)",
            "FIAT", "500", 2010, "Manual", 19000, 23.000);
    update(run, insertCar, "BMW", "X5", 2011, "Diesel", "Automatic", 59000, 77000);

    final String insertComment = "INSERT INTO comments (car_id, car_comment) VALUES (?,?)";
    update(run, insertComment, 0, "The Citroen C2 is a small car with a great attitude");
    update(run, insertComment, 0, "I Love my C2");
    update(run, insertComment, 2,
            "BMW's X5 costs too much for what it's worth. Checkout http://www.youtube.com/watch?v=Bg1TB4dRobY");

    final String insertPicture = "INSERT INTO pictures (car_id, picture) VALUES (?,?)";
    update(run, insertPicture, 0, "http://www.babez.de/citroen/c2/picth01.jpg");
    update(run, insertPicture, 0, "http://www.babez.de/citroen/c2/pic02.jpg");
    update(run, insertPicture, 0, "http://www.babez.de/citroen/c2/picth03.jpg");

    update(run, insertPicture, 1, "http://www.dwsauto.com/wp-content/uploads/2008/07/fiat-500-photo.jpg");
    update(run, insertPicture, 1, "http://www.cochesadictos.com/coches/fiat-500/imagenes/index1.jpg");
    update(run, insertPicture, 1, "http://www.cochesadictos.com/coches/fiat-500/imagenes/index4.jpg");

    update(run, insertPicture, 2, "http://www.coches21.com/fotos/100/bmw_x5_457.jpg");
    update(run, insertPicture, 2, "http://www.coches21.com/fotos/100/bmw_x5_460.jpg");
    update(run, insertPicture, 2, "http://www.coches21.com/modelos/250/bmw_x5_65.jpg");

    // generate some random data for the stats page
    DateTimeFormatter isofmt = ISODateTimeFormat.dateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSSS");
    DateTime dt;// = isofmt.parseDateTime("2012-01-16T13:34:00.000Z");
    for (int year = 2000; year < 2012; year++) {
        for (int month = 1; month <= 12; month++) {
            int val = 1910 + new Random().nextInt(100);
            dt = isofmt.parseDateTime(year + "-" + month + "-01T01:00:00.000Z");
            update(run, "INSERT INTO sales_stats (year, month, sales, last_update) VALUES (?,?,?,?)", year,
                    month, val, fmt.print(dt));
            for (CarMaker maker : CarMaker.values()) {
                val = new Random().nextInt(100);
                update(run,
                        "INSERT INTO maker_stats (year, month, sales, maker, last_update) VALUES (?,?,?,?,?)",
                        year, month, val, maker.name(), fmt.print(dt));
            }
        }
    }

    update(run, "SET TABLE maker READONLY TRUE");

    //load the sp
    update(run, "CREATE FUNCTION simpleStoredProcedure () RETURNS TINYINT RETURN 1");
    update(run,
            "CREATE PROCEDURE insert_comment (IN car_id INTEGER, IN car_comment VARCHAR(255)) MODIFIES SQL DATA INSERT INTO comments VALUES (DEFAULT, car_id, car_comment)");
    update(run,
            "CREATE PROCEDURE get_year_sales (IN in_year INTEGER, OUT out_total INTEGER) READS SQL DATA SELECT COUNT(sales) INTO out_total FROM sales_stats WHERE year = in_year");
    update(run, getCreateView());

}

From source file:org.jspringbot.keyword.date.DateHelper.java

License:Open Source License

public String isoParseDateTime(String dateStr) {
    LOG.keywordAppender().appendProperty("Date String", dateStr);

    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    current = fmt.parseDateTime(dateStr);

    // show the log for print
    return formatDateTime();
}

From source file:org.lilyproject.tools.import_.json.RecordReader.java

License:Apache License

private MetadataBuilder readMetadata(JsonNode metadata, QName recordField) throws JsonFormatException {
    if (!metadata.isObject()) {
        throw new JsonFormatException("The value for the metadata should be an object, field: " + recordField);
    }//w  w  w.  j ava2s. com

    ObjectNode object = (ObjectNode) metadata;
    MetadataBuilder builder = new MetadataBuilder();

    Iterator<Map.Entry<String, JsonNode>> it = object.getFields();
    while (it.hasNext()) {
        Map.Entry<String, JsonNode> entry = it.next();
        String name = entry.getKey();
        JsonNode value = entry.getValue();

        if (value.isTextual()) {
            builder.value(name, value.getTextValue());
        } else if (value.isInt()) {
            builder.value(name, value.getIntValue());
        } else if (value.isLong()) {
            builder.value(name, value.getLongValue());
        } else if (value.isBoolean()) {
            builder.value(name, value.getBooleanValue());
        } else if (value.isFloatingPointNumber()) {
            // In the JSON format, for simplicity, we don't make distinction between float & double, so you
            // can't control which of the two is created.
            builder.value(name, value.getDoubleValue());
        } else if (value.isObject()) {
            String type = JsonUtil.getString(value, "type", null);
            if (type == null) {
                throw new JsonFormatException("Missing required 'type' property on object in metadata field '"
                        + name + "' of record field " + recordField);
            }

            if (type.equals("binary")) {
                JsonNode binaryValue = value.get("value");
                if (!binaryValue.isTextual()) {
                    throw new JsonFormatException("Invalid binary value for metadata field '" + name
                            + "' of record field " + recordField);
                }

                try {
                    builder.value(name, new ByteArray(binaryValue.getBinaryValue()));
                } catch (IOException e) {
                    throw new JsonFormatException("Invalid binary value for metadata field '" + name
                            + "' of record field " + recordField);
                }
            } else if (type.equals("datetime")) {
                JsonNode datetimeValue = value.get("value");
                if (!datetimeValue.isTextual()) {
                    throw new JsonFormatException("Invalid datetime value for metadata field '" + name
                            + "' of record field " + recordField);
                }

                try {
                    builder.value(name,
                            ISODateTimeFormat.dateTime().parseDateTime(datetimeValue.getTextValue()));
                } catch (Exception e) {
                    throw new JsonFormatException("Invalid datetime value for metadata field '" + name
                            + "' of record field " + recordField);
                }
            } else {
                throw new JsonFormatException("Unsupported type value '" + type + "' for metadata field '"
                        + name + "' of record field " + recordField);
            }
        } else {
            throw new JsonFormatException("Unsupported type of value for metadata field '" + name
                    + "' of record field " + recordField);
        }
    }

    return builder;
}

From source file:org.mifos.application.admin.system.SystemInfo.java

License:Open Source License

public String getDateTimeStringIso8601() {
    DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
    return formatter.print(getDateTime().getMillis());
}

From source file:org.mrgeo.geometry.splitter.TimeSpanGeometrySplitter.java

License:Apache License

@Override
public void initialize(Map<String, String> splitterProperties, final boolean uuidOutputNames,
        final String[] outputNames) {
    String timeFormat = splitterProperties.get(TIME_FORMAT_PROPERTY);
    if (timeFormat == null || timeFormat.isEmpty()) {
        dtf = ISODateTimeFormat.dateTime();
    } else {//from www  . j  av a  2s  .  com
        dtf = DateTimeFormat.forPattern(timeFormat);
    }
    DateTime startTime = getTimeProperty(splitterProperties, START_TIME_PROPERTY, dtf);
    DateTime endTime = getTimeProperty(splitterProperties, END_TIME_PROPERTY, dtf);
    String strInterval = splitterProperties.get(INTERVAL_PROPERTY);
    if (strInterval == null || strInterval.isEmpty()) {
        throw new IllegalArgumentException("Missing interval property for time span geometry splitter");
    }
    int seconds = -1;
    try {
        seconds = Integer.parseInt(strInterval);
    } catch (NumberFormatException nfe) {
        throw new IllegalArgumentException(
                "Invalid value for interval property for time span geometry splitter");
    }
    Period interval = Period.seconds(seconds);
    startField = splitterProperties.get(START_FIELD_PROPERTY);
    if (startField == null || startField.isEmpty()) {
        throw new IllegalArgumentException("Missing startField property for time span geometry splitter");
    }
    endField = splitterProperties.get(END_FIELD_PROPERTY);
    if (endField == null || endField.isEmpty()) {
        throw new IllegalArgumentException("Missing endField property for time span geometry splitter");
    }
    compareType = TimeSpanGeometrySplitter.CompareType.END_TIME;
    String strCompareType = splitterProperties.get(COMPARE_TYPE_PROPERTY);
    if (strCompareType != null && !strCompareType.isEmpty()) {
        compareType = compareTypeFromString(strCompareType);
    }

    List<DateTime> breakpointsList = new ArrayList<DateTime>();
    DateTime currBreakpoint = startTime;
    while (currBreakpoint.compareTo(endTime) <= 0) {
        breakpointsList.add(currBreakpoint);
        currBreakpoint = currBreakpoint.plus(interval);
    }
    // If the endTime is greater than the last breakpoint, then
    // include one more breakpoint.
    if (endTime.compareTo(currBreakpoint.minus(interval)) > 0) {
        breakpointsList.add(currBreakpoint);
    }
    if ((outputNames != null) && (breakpointsList.size() != outputNames.length)) {
        throw new IllegalArgumentException(
                "Invalid set of output names specified for the time span" + " geometry splitter. There are "
                        + breakpointsList.size() + " breakpoints, and " + outputNames.length + " output names");
    }
    breakpoints = new DateTime[breakpointsList.size()];
    breakpointsList.toArray(breakpoints);
    outputs = new String[breakpoints.length];
    for (int i = 0; i < breakpoints.length; i++) {
        String output;
        if (outputNames != null) {
            output = outputNames[i];
        } else {
            if (uuidOutputNames) {
                output = UUID.randomUUID().toString();
            } else {
                output = breakpoints[i].toString(dtf);
                // DirectoryMultipleOutputs only allows alphanumeric characters
                output = output.replaceAll("[^\\p{Alnum}]", "");
            }
        }
        outputs[i] = output;
    }
}

From source file:org.mule.modules.quickbooks.utils.QBDateAdapter.java

License:Open Source License

public QBDateAdapter() {
    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
    DateTimeParser[] parsers = { ISODateTimeFormat.dateTimeNoMillis().getParser(),
            ISODateTimeFormat.dateTime().getParser(),
            DateTimeFormat.forPattern("yyyy-MM-ddZ").withZone(DateTimeZone.getDefault()).getParser() };
    builder.append(ISODateTimeFormat.dateTimeNoMillis().getPrinter(), parsers);
    dateTimeFormatter = builder.toFormatter();
}

From source file:org.n52.ses.wsn.dissemination.updateinterval.NoNewMessagesMessage.java

License:Open Source License

private Element createContent() {
    Element content = XmlUtils.createElement(UpdateIntervalDisseminationMethod.NO_NEW_MESSAGES_NAME);
    Attr time = content.getOwnerDocument().createAttribute("currentTime");
    time.setValue(new DateTime().toString(ISODateTimeFormat.dateTime()));
    content.setAttributeNode(time);/*  w  ww .  jav  a2 s  .c om*/
    return content;
}

From source file:org.n52.sos.feeder.baw.connector.SESConnector.java

License:Open Source License

private String[] splitObservations(String inputObservation) throws Exception {

    try {/*from   www .j  a va 2 s .  com*/
        // Determining how many observations are contained in the observation collection
        Pattern countPattern = Pattern.compile("<swe:value>(.*?)</swe:value>");
        Matcher countMatcher = countPattern.matcher(inputObservation);
        String countString = null;
        if (countMatcher.find()) {
            countString = countMatcher.group(1).trim();
        }
        int observationCount = Integer.parseInt(countString);

        // This array will contain one observation string for each observation of the observation
        // collection
        String[] outputStrings;

        // If the observation collection contains only one value it can be directly returned
        if (observationCount == 1) {
            outputStrings = new String[] { inputObservation };
        }

        // If the observation collection contains more than one value it must be split
        else {

            // Extracting the values that are contained in the observation collection and creating a
            // StringTokenizer that allows to access the values
            Pattern valuesPattern = Pattern.compile("<swe:values>(.*?)</swe:values>");
            Matcher valuesMatcher = valuesPattern.matcher(inputObservation);
            String valuesString = null;
            if (valuesMatcher.find()) {
                valuesString = valuesMatcher.group(1).trim();
            }

            // Read the id of the observation collection
            Pattern idPattern = Pattern
                    .compile("ObservationCollection gml:id=\"(.*?)\"(.*?)xsi:schemaLocation=");
            Matcher idMatcher = idPattern.matcher(inputObservation);
            String idString = "";
            if (idMatcher.find()) {
                idString = idMatcher.group(1).trim();
            }

            StringTokenizer valuesTokenizer = new StringTokenizer(valuesString, ";");
            // If only the latest observation is wished, find youngest
            // observation.
            if (Configuration.getInstance().isOnlyYoungestName()) {
                DateTime youngest = new DateTime(0);
                String youngestValues = "";
                DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                while (valuesTokenizer.hasMoreElements()) {
                    String valueString = (String) valuesTokenizer.nextElement();
                    DateTime time = fmt.parseDateTime(valueString.split(",")[0]);
                    if (time.isAfter(youngest.getMillis())) {
                        youngest = time;
                        youngestValues = valueString;
                    }
                }
                outputStrings = new String[] {
                        createSingleObservationString(inputObservation, youngestValues) };
            } else {
                outputStrings = new String[observationCount];

                for (int i = 0; i < observationCount; i++) {

                    // Add the extracted observation to an array containing
                    // all extracted observations
                    outputStrings[i] = createSingleObservationString(inputObservation,
                            valuesTokenizer.nextToken());
                }
            }

        }
        // Returning the extracted observations
        return outputStrings;
    }

    catch (Exception e) {
        throw e;
    }
}

From source file:org.n52.sos.feeder.baw.task.FeedObservationThread.java

License:Open Source License

/**
 * Gets the update interval.//from w  ww.j  a va  2 s  .c om
 * 
 * @param observation
 *            the observation
 * @param newestUpdate
 *            the newest update
 * @return the update interval
 */
private long getUpdateInterval(ObservationType observation, Calendar newestUpdate) {
    long updateInterval = 0;
    try {

        updateInterval = Configuration.getInstance().getUpdateInterval();
        XmlCursor cResult = observation.getResult().newCursor();
        cResult.toChild(new QName(Strings.getString("Schema.Namespace.Swe101"),
                Strings.getString("Schema.Type.DataArray")));
        DataArrayDocument dataArrayDoc = null;
        try {
            dataArrayDoc = DataArrayDocument.Factory.parse(cResult.getDomNode());
        } catch (XmlException e) {
            log.error("Error when parsing DataArray: " + e.getMessage());
        }
        // get Seperators
        TextBlock textBlock = dataArrayDoc.getDataArray1().getEncoding().getTextBlock();
        String tokenSeparator = textBlock.getTokenSeparator();
        String blockSeparator = textBlock.getBlockSeparator();

        // get values
        String values = dataArrayDoc.getDataArray1().getValues().getDomNode().getFirstChild().getNodeValue();

        // get updateInterval
        String[] blockArray = values.split(blockSeparator);
        DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
        Date latest = newestUpdate.getTime();
        for (String value : blockArray) {
            String[] valueArray = value.split(tokenSeparator);
            try {
                DateTime dateTime = fmt.parseDateTime(valueArray[0]);
                Date temp = dateTime.toDate();
                long interval = (temp.getTime() - latest.getTime());
                if (interval < updateInterval) {
                    updateInterval = (int) interval;
                }
                latest = temp;
            } catch (Exception e) {
                log.error("Error when parsing Date: " + e.getMessage(), e);
            }
        }

        if (blockArray.length >= 2) {
            String[] valueArrayFirst = blockArray[blockArray.length - 2].split(tokenSeparator);
            String[] valueArrayLast = blockArray[blockArray.length - 1].split(tokenSeparator);
            DateTime dateTimeFirst = fmt.parseDateTime(valueArrayFirst[0]);
            DateTime dateTimeLast = fmt.parseDateTime(valueArrayLast[0]);
            updateInterval = dateTimeLast.getMillis() - dateTimeFirst.getMillis();
        }

        if (updateInterval <= Configuration.getInstance().getUpdateInterval()) {
            return Configuration.getInstance().getUpdateInterval();
        }
    } catch (IllegalStateException e) {
        log.debug("Configuration is not available (anymore).", e);
    }

    return updateInterval;
}