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.n52.ses.io.parser.SASParser.java

License:Open Source License

/**
 * Parses an SAS alert/*w  w w . j  a  va  2 s.  c  o m*/
 * 
 * @param xmlObj the SAS alert as DOM node
 * 
 * @return A list of {@link MapEvent}s containing the alert as first entity.
 */
public List<MapEvent> parseXML(XmlObject xmlObj) {
    //parse string based
    this.parseAlertDocumentText(xmlObj.toString());

    //parse time stamp text
    DateTimeFormatter dtf = this.buildDTFormatter();
    DateTime dt = dtf.parseDateTime(this.timestamp);
    long timeStamp = dt.getMillis();

    //parse alert data
    this.parseAlertData(this.alertdata);

    //build result list
    List<MapEvent> result = new ArrayList<MapEvent>();

    //build MapEvent
    MapEvent event = new MapEvent(timeStamp, timeStamp);

    //set value
    event.put(MapEvent.VALUE_KEY, this.value);

    //set geometry
    event.put(MapEvent.GEOMETRY_KEY, this.geometry);

    //set sensor ID
    event.put(MapEvent.SENSORID_KEY, this.sensorID);

    //set original message
    event.put(MapEvent.ORIGNIAL_MESSAGE_KEY, xmlObj.toString());

    //add event to result
    result.add(event);

    SASParser.logger.info("SAS alert parsed");
    return result;
}

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

License:Open Source License

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

    try {//from w  ww  .  j a va 2s . c  om
        // 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 w w  .  ja  va  2 s .  c o  m
 * 
 * @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;
}

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

License:Open Source License

/**
 * Gets the last update time.//from w ww .ja  va 2s.  co  m
 * 
 * @param samplingTime
 *            the sampling time
 * @return the last update time
 */
private Calendar getLastUpdateTime(TimeObjectPropertyType samplingTime) {
    AbstractTimeObjectType timeObject = samplingTime.getTimeObject();
    TimePeriodType timePeriod = (TimePeriodType) timeObject;
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    Date date = null;
    try {
        DateTime dateTime = fmt.parseDateTime(timePeriod.getEndPosition().getStringValue());
        date = dateTime.toDate();
    } catch (Exception e) {
        log.error("Error when parsing Date: " + e.getMessage(), e);
    }
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    return cal;
}

From source file:org.numenta.nupic.RunLayer.java

License:Open Source License

@SuppressWarnings("unused")
public static void main(String[] args) {
    long start = System.currentTimeMillis();

    RunLayer.MakeshiftLayer layer = RunLayer.createLayer();

    System.out.println("\n===================================\n");

    loadSPOutputFile();/*  w  w w. j a  v a 2  s  . c  o  m*/
    loadRawInputFile();
    if (NETWORK) {
        for (int i = 0; i < MakeshiftLayer.input.size(); i++) {
            int[] sparseSPOutput = MakeshiftLayer.input.get(i);
            layer.networkStep(sparseSPOutput, LEARN);
        }
    } else if (TM_ONLY) {
        for (int i = 0; i < MakeshiftLayer.input.size(); i++) {
            layer.printHeader();
            int[] sparseSPOutput = MakeshiftLayer.input.get(i);
            Tuple tmTuple = layer.tmStep(sparseSPOutput, LEARN, IS_VERBOSE);
            double score = layer.anomalyStep(sparseSPOutput, (int[]) tmTuple.get(1), true);
            layer.incRecordNum();

            // Store the current prediction as previous
            layer.storeCyclePrediction((int[]) tmTuple.get(2));
        }
    } else if (SP_ONLY) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        try (Stream<String> stream = Files.lines(Paths.get(MakeshiftLayer.INPUT_PATH))) {
            stream.skip(1).forEach(l -> {
                String[] line = l.split("[\\s]*\\,[\\s]*");

                DateTime timestamp = formatter.parseDateTime(line[0].trim());
                double value = Double.parseDouble(line[1].trim());
                layer.printHeader();
                Tuple encTuple = layer.encodingStep(timestamp, value, IS_VERBOSE);
                Tuple spTuple = layer.spStep((int[]) encTuple.get(0), LEARN, IS_VERBOSE);

                layer.incRecordNum();
                if (layer.recordNum == 200) {
                    System.exit(0);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        try (Stream<String> stream = Files.lines(Paths.get(MakeshiftLayer.INPUT_PATH))) {
            stream.skip(1).forEach(l -> {
                String[] line = l.split("[\\s]*\\,[\\s]*");
                DateTime timestamp = formatter.parseDateTime(line[0].trim());
                double value = Double.parseDouble(line[1].trim());
                layer.printHeader();
                Tuple encTuple = layer.encodingStep(timestamp, value, IS_VERBOSE);
                Tuple spTuple = layer.spStep((int[]) encTuple.get(0), LEARN, IS_VERBOSE);
                int[] spOutput = (int[]) spTuple.get(1);
                Tuple tmTuple = layer.tmStep((int[]) spTuple.get(1), LEARN, IS_VERBOSE);
                //Classification<Double> cla = layer.classificationStep((int[])tmTuple.get(0), (int)encTuple.get(1), value, LEARN, IS_VERBOSE);
                double score = layer.anomalyStep(spOutput, layer.prevPredictedCols, IS_VERBOSE);

                layer.incRecordNum();

                // Store the current prediction as previous
                layer.storeCyclePrediction((int[]) tmTuple.get(2));
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    System.out.println("--- " + ((System.currentTimeMillis() - start) / 1000d) + " seconds ---");
}

From source file:org.nuxeo.ecm.platform.oauth2.openid.auth.facebook.FacebookUserInfo.java

License:Apache License

@Override
public Date getUpdatedTime() {
    Date date;//  w w w  .j a v  a2 s .com
    try {
        DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
        DateTime dateTime = parser.parseDateTime(updatedTime);
        date = dateTime.toDate();
    } catch (IllegalArgumentException e) {
        return null;
    }
    return date;
}

From source file:org.nuxeo.elasticsearch.aggregate.DateHistogramAggregate.java

License:Open Source License

private long convertStringToDate(String date) {
    Map<String, String> props = getProperties();
    DateTimeFormatter fmt;
    if (props.containsKey(AGG_FORMAT_PROP)) {
        fmt = DateTimeFormat.forPattern(props.get(AGG_FORMAT_PROP));
    } else {/*from  w w  w . j  a  v a2 s. c  om*/
        throw new IllegalArgumentException("format property must be defined for " + toString());
    }
    // TODO should take in account all the locale zone stuff ...
    return fmt.parseDateTime(date).getMillis();
}

From source file:org.ojbc.bundles.adapters.staticmock.StaticMockQuery.java

License:RPL License

List<IdentifiableDocumentWrapper> incidentSearchDocumentsAsList(Document incidentSearchRequestMessage,
        DateTime baseDate) throws Exception {

    Element rootElement = incidentSearchRequestMessage.getDocumentElement();
    String rootNamespaceURI = rootElement.getNamespaceURI();
    String rootLocalName = rootElement.getLocalName();
    if (!(OjbcNamespaceContext.NS_INCIDENT_SEARCH_REQUEST_DOC.equals(rootNamespaceURI)
            && "IncidentSearchRequest".equals(rootLocalName))) {
        throw new IllegalArgumentException("Invalid message, must have {"
                + OjbcNamespaceContext.NS_INCIDENT_SEARCH_REQUEST_DOC + "}IncidentSearchRequest as the root "
                + "instead of {" + rootNamespaceURI + "}" + rootLocalName);
    }/*from  w ww  . j a v a2 s. c o m*/

    NodeList systemElements = XmlUtils.xPathNodeListSearch(rootElement, "isr:SourceSystemNameText");
    if (systemElements == null || systemElements.getLength() == 0) {
        throw new IllegalArgumentException(
                "Invalid query request message:  must specify at least one system to query.");
    }

    List<IdentifiableDocumentWrapper> ret = new ArrayList<IdentifiableDocumentWrapper>();

    String searchXPath = buildIncidentSearchXPathFromIncidentSearchMessage(incidentSearchRequestMessage);

    String dateLowerString = XmlUtils.xPathStringSearch(incidentSearchRequestMessage,
            "/isr-doc:IncidentSearchRequest/isr:Incident/nc:ActivityDateRange/nc:StartDate/nc:DateTime");
    String dateUpperString = XmlUtils.xPathStringSearch(incidentSearchRequestMessage,
            "/isr-doc:IncidentSearchRequest/isr:Incident/nc:ActivityDateRange/nc:EndDate/nc:DateTime");

    LOG.debug("dateLowerString=" + dateLowerString);
    LOG.debug("dateUpperString=" + dateUpperString);

    if (searchXPath == null && isMissing(dateLowerString) && isMissing(dateUpperString)) {
        return ret;
    }

    DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeParser();

    for (IdentifiableDocumentWrapper dw : incidentDataSource.getDocuments()) {

        Document d = dw.getDocument();
        LOG.debug("Searching document " + dw.getId());

        boolean match = (searchXPath == null || XmlUtils.xPathNodeSearch(d, searchXPath) != null);
        LOG.debug("Match=" + match + " based on xpath eval");

        if (match && (!(isMissing(dateLowerString) && isMissing(dateUpperString)))) {

            LOG.debug("In date evaluation");

            String incidentStartDateString = XmlUtils.xPathStringSearch(d,
                    "/ir:IncidentReport/lexspd:doPublish/lexs:PublishMessageContainer/lexs:PublishMessage/lexs:DataItemPackage/lexs:Digest/lexsdigest:EntityActivity/nc:Activity[nc:ActivityCategoryText='Incident']/nc:ActivityDateRange/nc:StartDate/nc:DateTime");
            String incidentEndDateString = XmlUtils.xPathStringSearch(d,
                    "/ir:IncidentReport/lexspd:doPublish/lexs:PublishMessageContainer/lexs:PublishMessage/lexs:DataItemPackage/lexs:Digest/lexsdigest:EntityActivity/nc:Activity[nc:ActivityCategoryText='Incident']/nc:ActivityDateRange/nc:EndDate/nc:DateTime");

            if (isMissing(incidentStartDateString) && isMissing(incidentEndDateString)) {
                match = false;
            } else {
                DateTime incidentStartDateTime = null;
                DateTime incidentEndDateTime = null;
                try {
                    incidentStartDateTime = dateTimeFormatter.parseDateTime(incidentStartDateString);
                    incidentEndDateTime = dateTimeFormatter.parseDateTime(incidentEndDateString);
                } catch (Exception e) {
                    e.printStackTrace();
                    LOG.warn("Unable to parse date (either " + incidentStartDateString + " or "
                            + incidentEndDateString
                            + "). Note that null dates are ok...just means it's not part of the incident");
                }
                LOG.debug("incidentStartDateTime=" + incidentStartDateTime);
                LOG.debug("incidentEndDateTime=" + incidentEndDateTime);
                if (incidentStartDateTime == null && incidentEndDateTime == null) {
                    match = false;
                } else {
                    if (!isMissing(dateLowerString)) {
                        DateTime lowerDateTime = dateTimeFormatter.parseDateTime(dateLowerString);
                        if (incidentEndDateTime != null && incidentEndDateTime.isBefore(lowerDateTime)) {
                            match = false;
                        } else if (incidentEndDateTime == null
                                && incidentStartDateTime.isBefore(lowerDateTime)) {
                            match = false;
                        }
                    }
                    if (!isMissing(dateUpperString)) {
                        DateTime upperDateTime = dateTimeFormatter.parseDateTime(dateUpperString);
                        if (incidentStartDateTime != null && incidentStartDateTime.isAfter(upperDateTime)) {
                            match = false;
                        } else if (incidentStartDateTime == null
                                && incidentEndDateTime.isBefore(upperDateTime)) {
                            match = false;
                        }
                    }
                }
            }

        }

        if (match) {
            ret.add(dw);
        }

    }

    return ret;

}

From source file:org.ojbc.web.portal.controllers.PortalController.java

License:RPL License

UserLogonInfo getUserLogonInfo(Element assertionElement) {

    UserLogonInfo userLogonInfo = new UserLogonInfo();

    if (assertionElement == null) {
        log.warn("assertionElement was null, returning empty UserLogonInfo");
        return userLogonInfo;
    }/*  w w w.  jav a 2s. c om*/

    try {

        debugPrintAssertion(assertionElement);

        String instantString = (String) xPath.evaluate("/saml2:Assertion/saml2:AuthnStatement/@AuthnInstant",
                assertionElement, XPathConstants.STRING);
        DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
        DateTime authnInstant = fmt.parseDateTime(instantString);
        int minutesOnline = Minutes.minutesBetween(authnInstant, new DateTime()).getMinutes();
        int hoursOnline = (int) minutesOnline / 60;
        minutesOnline = minutesOnline % 60;
        userLogonInfo.timeOnlineString = String.valueOf(hoursOnline) + ":" + (minutesOnline < 10 ? "0" : "")
                + String.valueOf(minutesOnline);

        String userLastName = (String) xPath.evaluate(
                "/saml2:Assertion/saml2:AttributeStatement[1]/saml2:Attribute[@Name='gfipm:2.0:user:SurName']/saml2:AttributeValue/text()",
                assertionElement, XPathConstants.STRING);
        String userFirstName = (String) xPath.evaluate(
                "/saml2:Assertion/saml2:AttributeStatement[1]/saml2:Attribute[@Name='gfipm:2.0:user:GivenName']/saml2:AttributeValue/text()",
                assertionElement, XPathConstants.STRING);
        String userAgency = (String) xPath.evaluate(
                "/saml2:Assertion/saml2:AttributeStatement[1]/saml2:Attribute[@Name='gfipm:2.0:user:EmployerName']/saml2:AttributeValue/text()",
                assertionElement, XPathConstants.STRING);

        String sEmail = (String) xPath.evaluate(
                "/saml2:Assertion/saml2:AttributeStatement[1]/saml2:Attribute[@Name='gfipm:2.0:user:EmailAddressText']/saml2:AttributeValue/text()",
                assertionElement, XPathConstants.STRING);

        userLogonInfo.userNameString = (userFirstName == null ? "" : userFirstName) + " "
                + (userLastName == null ? "" : userLastName) + " / " + (userAgency == null ? "" : userAgency);
        userLogonInfo.emailAddress = sEmail;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return userLogonInfo;
}

From source file:org.onebusaway.admin.json.JodaDateTimeAdapter.java

License:Apache License

@Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    DateTimeFormatter fmt = OneBusAwayDateFormats.DATETIMEPATTERN_JSON_DATE_TIME;
    DateTime result = fmt.parseDateTime(json.getAsJsonPrimitive().getAsString());

    return result;
}