Example usage for javax.xml.bind DatatypeConverter parseDateTime

List of usage examples for javax.xml.bind DatatypeConverter parseDateTime

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter parseDateTime.

Prototype

public static java.util.Calendar parseDateTime(String lexicalXSDDateTime) 

Source Link

Document

Converts the string argument into a Calendar value.

Usage

From source file:org.gatein.api.management.Utils.java

public static Date getDate(ModelObject model, String... names) {
    String string = get(model, ModelString.class, names).getValue();
    if (string != null) {
        try {//from   ww  w  . java2  s . co  m
            return DatatypeConverter.parseDateTime(string).getTime();
        } catch (IllegalArgumentException e) {
            throw invalidValue(string, names);
        }
    }

    return null;
}

From source file:org.metaservice.frontend.rest.cache.FileSystemCacheResourceService.java

@Override
public InputStream getResource(String resource, Calendar date, String mimetype) {
    boolean latest = date == null;
    if (date == null) {
        date = DatatypeConverter.parseDateTime("2025-01-01T00:00:00Z");
    }/*www  .j av a 2  s  .  c  o m*/
    try {
        if (latest) {
            File cacheFile = getCacheFile(resource, mimetype);
            if (cacheFile.exists()) {
                return new FileInputStream(cacheFile);
            }
            return cacheResource(resourceService.getResource(resource, date, mimetype), resource, mimetype);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return resourceService.getResource(resource, date, mimetype);
}

From source file:org.moqui.impl.context.L10nFacadeImpl.java

@Override
public Timestamp parseTimestamp(String input, String format) {
    if (input == null || input.isEmpty())
        return null;
    Locale curLocale = getLocale();
    TimeZone curTz = getTimeZone();
    Calendar cal = null;/*  w  ww  . ja va  2s  .  c  o m*/
    if (format != null && !format.isEmpty())
        cal = calendarValidator.validate(input, format, curLocale, curTz);

    // long values are pretty common, so if there are no special characters try that first (fast to check)
    if (cal == null) {
        int nonDigits = StupidUtilities.countChars(input, false, true, true);
        if (nonDigits == 0) {
            try {
                Long lng = Long.valueOf(input);
                return new Timestamp(lng);
            } catch (NumberFormatException e) {
                if (logger.isTraceEnabled())
                    logger.trace("Ignoring NumberFormatException for Timestamp parse: " + e.toString());
            }
        }
    }

    // try a bunch of other format strings
    if (cal == null) {
        int timestampFormatsSize = timestampFormats.size();
        for (int i = 0; cal == null && i < timestampFormatsSize; i++) {
            String tf = timestampFormats.get(i);
            cal = calendarValidator.validate(input, tf, curLocale, curTz);
        }
    }

    // logger.warn("=========== input=${input}, cal=${cal}, long=${cal?.getTimeInMillis()}, locale=${curLocale}, timeZone=${curTz}, System=${System.currentTimeMillis()}")
    if (cal != null)
        return new Timestamp(cal.getTimeInMillis());

    try {
        // NOTE: do this AFTER the long parse because long numbers are interpreted really weird by this
        // ISO 8601 parsing using JAXB DatatypeConverter.parseDateTime(); on Java 7 can use "X" instead of "Z" in format string, but not in Java 6
        cal = DatatypeConverter.parseDateTime(input);
        if (cal != null)
            return new Timestamp(cal.getTimeInMillis());
    } catch (Exception e) {
        if (logger.isTraceEnabled())
            logger.trace("Ignoring Exception for DatatypeConverter Timestamp parse: " + e.toString());
    }

    return null;
}

From source file:org.neo4art.importer.wikipedia.transformer.WikipediaElementTransformer.java

public static WikipediaElement toWikipediaElement(WikiArticle article) {

    WikipediaElement wikipediaElement = null;

    WikiPatternMatcher articleTextParser = null;

    try {/* w w w  . j a v a  2  s  . co m*/

        if (StringUtils.isNotEmpty(article.getText())) {
            articleTextParser = new WikiPatternMatcher(article.getText());
        }

        if ((wikipediaElement = from(article, articleTextParser)) != null) {

            wikipediaElement.setId(Long.parseLong(article.getId()));
            wikipediaElement.setTitle(article.getTitle());
            wikipediaElement.setRevision(Long.parseLong(article.getRevisionId()));
            wikipediaElement
                    .setTimestamp(DatatypeConverter.parseDateTime(article.getTimeStamp()).getTimeInMillis());

            if (articleTextParser != null) {

                // ----- LINKS -----
                List<String> links = articleTextParser.getLinks();
                if (CollectionUtils.isNotEmpty(links)) {
                    for (String link : links) {
                        WikipediaPage page = new WikipediaPage();
                        page.setTitle(link);
                        wikipediaElement.addLink(page);
                    }
                }

                // ----- CATEGORIES -----
                List<String> categorieNames = articleTextParser.getCategories();
                if (CollectionUtils.isNotEmpty(categorieNames)) {
                    for (String categoryName : categorieNames) {
                        WikipediaCategory category = new WikipediaCategory();
                        category.setTitle(categoryName);
                        wikipediaElement.addCategory(category);
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(
                "Error parsing article " + article.getTitle() + " : " + ExceptionUtils.getRootCauseMessage(e));
    }

    return wikipediaElement;
}

From source file:org.ojbc.adapters.analyticaldatastore.processor.IncidentReportProcessor.java

@Transactional
public void processReport(Document incidentReport) throws Exception {
    Incident incident = new Incident();

    String rootElemntName = incidentReport.getDocumentElement().getLocalName();
    if (INCIDENT_REPORT_ROOT_ELEMENT_NAME.equals(rootElemntName)) {
        incident.setRecordType('N');
    } else if (INCIDENT_REPORT_UPDATE_ROOT_ELEMENT_NAME.equals(rootElemntName)) {
        incident.setRecordType('U');
    }/*from   www .  j av  a  2s .  c  om*/

    String reportingAgencyName = XmlUtils.xPathStringSearch(incidentReport, PATH_TO_LEXS_DIGEST
            + "/lexsdigest:EntityOrganization/nc:Organization[@s:id= " + PATH_TO_LEXS_DIGEST
            + " /lexsdigest:Associations/nc:ActivityReportingOrganizationAssociation[nc:ActivityReference/@s:ref="
            + PATH_TO_LEXS_DIGEST
            + "/lexsdigest:EntityActivity/nc:Activity[nc:ActivityCategoryText='Incident']/@s:id]/nc:OrganizationReference/@s:ref]/nc:OrganizationName");
    log.debug("Agency Name: " + reportingAgencyName);

    String reportingAgencyORI = XmlUtils.xPathStringSearch(incidentReport, PATH_TO_LEXS_DATA_ITEM_PACKAGE
            + "/lexs:PackageMetadata/lexs:DataOwnerMetadata/lexs:DataOwnerIdentifier/lexs:ORI");
    log.debug("Agency ORI: " + reportingAgencyORI);

    Integer reportingAgencyId = null;

    if (StringUtils.isNotBlank(reportingAgencyORI)) {
        reportingAgencyId = analyticalDatastoreDAO.searchForAgenyIDbyAgencyORI(reportingAgencyORI);

        if (reportingAgencyId == null) {
            throw new Exception("Valid Agency ORI required for incident.  Agency Name is: "
                    + reportingAgencyName + ", Agency ORI is: " + reportingAgencyORI);
        }

        incident.setReportingAgencyID(reportingAgencyId);
    } else {
        throw new Exception("Valid Agency ORI required for incident.  Agency Name is: "
                + StringUtils.trimToEmpty(reportingAgencyName) + ", Agency ORI is: "
                + StringUtils.trimToEmpty(reportingAgencyORI));
    }

    String incidentCaseNumber = XmlUtils.xPathStringSearch(incidentReport,
            PATH_TO_LEXS_DATA_ITEM_PACKAGE + "/lexs:PackageMetadata/lexs:DataItemID");
    log.debug("Incident Case Number: " + incidentCaseNumber);

    if (StringUtils.isNotBlank(incidentCaseNumber)) {
        incident.setIncidentCaseNumber(incidentCaseNumber);
    }

    //Check to see if incident(s) already exists
    List<Incident> incidents = analyticalDatastoreDAO
            .searchForIncidentsByIncidentNumberAndReportingAgencyID(incidentCaseNumber, reportingAgencyId);

    //if incidents exist, delete them prior to inserting a new one
    if (incidents.size() > 1) {
        throw new IllegalStateException(
                "Error condition. Duplicate records with same incident number and agency ID exists in database");
    }

    Integer incidentIDToReplace = null;

    if (incidents.size() == 1) {
        incidentIDToReplace = incidents.get(0).getIncidentID();
        incident.setIncidentID(incidentIDToReplace);
        log.debug("Incident ID to replace: " + incidentIDToReplace);

        analyticalDatastoreDAO.deleteIncident(incidents.get(0).getIncidentID());
    }

    String reportingSystem = XmlUtils.xPathStringSearch(incidentReport, PATH_TO_LEXS_DATA_ITEM_PACKAGE
            + "/lexs:PackageMetadata/lexs:DataOwnerMetadata/lexs:DataOwnerIdentifier/lexs:SystemID");
    incident.setReportingSystem(reportingSystem);

    //Look for either incident date/time or incident date field
    String incidentDateTimeAsString = XmlUtils.xPathStringSearch(incidentReport, PATH_TO_LEXS_DIGEST
            + "/lexsdigest:EntityActivity/nc:Activity/nc:ActivityDateRange/nc:StartDate/nc:DateTime");
    log.debug("Incident Date/Time: " + incidentDateTimeAsString);

    if (StringUtils.isNotEmpty(incidentDateTimeAsString)) {
        Calendar incidentDateTimeCal = DatatypeConverter.parseDateTime(incidentDateTimeAsString);
        Date incidentDateTime = incidentDateTimeCal.getTime();

        if (incidentDateTime != null) {
            incident.setIncidentDate(incidentDateTime);
        }

        Time incidentTime = new Time(incidentDateTime.getTime());
        log.debug("Incident Time: " + incidentTime.toString());

        if (incidentTime != null) {
            incident.setIncidentTime(incidentTime);
        }
    } else {
        String incidentDateAsString = XmlUtils.xPathStringSearch(incidentReport,
                PATH_TO_LEXS_DIGEST + "/lexsdigest:EntityActivity/nc:Activity/nc:ActivityDate/nc:Date");
        log.debug("Incident Date: " + incidentDateAsString);

        Calendar incidentDateCal = DatatypeConverter.parseDate(incidentDateAsString);
        Date incidentDate = incidentDateCal.getTime();

        if (incidentDate != null) {
            incident.setIncidentDate(incidentDate);
        }

    }

    String mapHorizontalCoordinateText = XmlUtils.xPathStringSearch(incidentReport,
            PATH_TO_LEXS_DATA_ITEM_PACKAGE
                    + "/lexs:StructuredPayload/inc-ext:IncidentReport/inc-ext:Location/nc:LocationMapLocation/nc:MapHorizontalCoordinateText");

    if (StringUtils.isNotBlank(mapHorizontalCoordinateText)) {
        //TODO: put this into a strategy
        try {
            mapHorizontalCoordinateText = updatedCoordinate(mapHorizontalCoordinateText);
            log.debug("Map horizontal coordinate text: " + mapHorizontalCoordinateText);

            BigDecimal longitude = new BigDecimal(mapHorizontalCoordinateText);
            incident.setIncidentLocationLongitude(longitude);
        } catch (Exception ex) {
            log.warn("Unable to set map horizontal text coordinate");
        }
    }

    String mapVerticalCoordinateText = XmlUtils.xPathStringSearch(incidentReport, PATH_TO_LEXS_DATA_ITEM_PACKAGE
            + "/lexs:StructuredPayload/inc-ext:IncidentReport/inc-ext:Location/nc:LocationMapLocation/nc:MapVerticalCoordinateText");

    if (StringUtils.isNotBlank(mapVerticalCoordinateText)) {
        //TODO: put this into a strategy
        try {
            mapVerticalCoordinateText = updatedCoordinate(mapVerticalCoordinateText);
            log.debug("Map vertical coordinate text: " + mapVerticalCoordinateText);

            BigDecimal latitude = new BigDecimal(mapVerticalCoordinateText);
            incident.setIncidentLocationLatitude(latitude);
        } catch (Exception ex) {
            log.warn("Unable to set map vertical text coordinate");
        }
    }

    String incidentLocationReference = XmlUtils.xPathStringSearch(incidentReport, PATH_TO_LEXS_DIGEST
            + "/lexsdigest:Associations/lexsdigest:IncidentLocationAssociation/nc:LocationReference/@s:ref");

    if (StringUtils.isNotEmpty(incidentLocationReference)) {
        Node locationNode = XmlUtils.xPathNodeSearch(incidentReport, PATH_TO_LEXS_DIGEST
                + "/lexsdigest:EntityLocation/nc:Location[@s:id='" + incidentLocationReference + "']");

        String streetFullText = XmlUtils.xPathStringSearch(locationNode,
                "nc:LocationAddress/nc:StructuredAddress/nc:LocationStreet/nc:StreetFullText");
        log.debug("Street Full Text: " + streetFullText);

        if (StringUtils.isNotBlank(streetFullText)) {
            incident.setIncidentLocationStreetAddress(streetFullText);
        } else {
            String streetNumberText = XmlUtils.xPathStringSearch(locationNode,
                    "nc:LocationAddress/nc:StructuredAddress/nc:LocationStreet/nc:StreetNumberText");
            log.debug("Street Number Text: " + streetNumberText);

            String streetName = XmlUtils.xPathStringSearch(locationNode,
                    "nc:LocationAddress/nc:StructuredAddress/nc:LocationStreet/nc:StreetName");
            log.debug("Street Name Text: " + streetName);

            String streetCategoryText = XmlUtils.xPathStringSearch(locationNode,
                    "nc:LocationAddress/nc:StructuredAddress/nc:LocationStreet/nc:StreetCategoryText");
            log.debug("Street Category Text: " + streetCategoryText);

            streetFullText = streetNumberText + streetName + streetFullText;
            log.debug("Street Full Text built from number, name and category: " + streetFullText);

            if (StringUtils.isNotBlank(streetFullText)) {
                incident.setIncidentLocationStreetAddress(streetFullText);
            }

        }

        String cityTown = XmlUtils.xPathStringSearch(locationNode,
                "nc:LocationAddress/nc:StructuredAddress/nc:LocationCityName");
        log.debug("City/Town: " + cityTown);

        if (StringUtils.isNotBlank(cityTown)) {
            incident.setIncidentLocationTown(cityTown);
        }

    }

    Integer incidentPk = analyticalDatastoreDAO.saveIncident(incident);

    //Add Incident Description Text
    processIncidentType(incidentReport, incidentPk);

    //Save circumstance codes
    processCircumstanceCodes(incidentReport, incidentPk);

    processArrests(incidentReport, incidentPk, reportingSystem);

}

From source file:org.ojbc.adapters.analyticaldatastore.processor.IncidentReportProcessor.java

protected Date returnArrestDate(Document incidentReport, Node arrestSubjectAssocationNode) throws Exception {
    String arrestActivityReference = XmlUtils.xPathStringSearch(arrestSubjectAssocationNode,
            "nc:ActivityReference/@s:ref");
    log.debug("Arrest Activity Reference: " + arrestActivityReference);

    Node arrestNode = XmlUtils.xPathNodeSearch(incidentReport, PATH_TO_LEXS_DIGEST
            + "/lexsdigest:EntityActivity/nc:Activity[@s:id='" + arrestActivityReference + "']");

    String arrestDateTimeAsString = XmlUtils.xPathStringSearch(arrestNode, "nc:ActivityDate/nc:DateTime");

    Calendar arrestDateTimeCal = DatatypeConverter.parseDateTime(arrestDateTimeAsString);
    Date arrestDateTime = arrestDateTimeCal.getTime();
    return arrestDateTime;
}

From source file:org.openestate.io.core.XmlUtils.java

private static Calendar parseDateTime(String value, boolean tryDateOnError) {
    value = StringUtils.trimToNull(value);
    if (value == null)
        return null;
    try {/*from   w ww  . j ava 2  s .c o  m*/
        return DatatypeConverter.parseDateTime(value);
    } catch (IllegalArgumentException ex) {
        //LOGGER.warn( "Can't parse value '" + value + "' as datetime!" );
        //LOGGER.warn( "> " + ex.getLocalizedMessage(), ex );
    }
    try {
        Date date = DateUtils.parseDateStrictly(value, new String[] { "yyyy-MM-dd'T'HH:mm:ss",
                "yyyy-MM-dd'T'HH:mm", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm" });
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal;
    } catch (ParseException ex) {
        //LOGGER.warn( "Can't parse value '" + value + "' as datetime!" );
        //LOGGER.warn( "> " + ex.getLocalizedMessage(), ex );
    }

    // try to parse the value as xsd:date instead
    if (tryDateOnError) {
        try {
            return XmlUtils.parseDate(value, false);
        } catch (IllegalArgumentException ex) {
            //LOGGER.warn( "Can't parse value '" + value + "' as datetime!" );
            //LOGGER.warn( "> " + ex.getLocalizedMessage(), ex );
        }
    }

    throw new IllegalArgumentException("Can't parse date-time value '" + value + "'!");
}

From source file:org.openestate.io.immobiliare_it.ImmobiliareItUtils.java

public static boolean isValidDateUpdatedType(Calendar value) {
    final Calendar min = DatatypeConverter.parseDateTime("2000-12-31T00:00:00");
    return value != null && !value.before(min);
}

From source file:org.openmainframe.ade.ext.output.ExtJaxbAnalyzedIntervalV2XmlStorer.java

/**
 * @param scoreSet/*w  w w  .  ja  va  2s . com*/
 * @param stats
 * @throws AdeInternalException
 * @throws AdeExtUsageException
 */
private void processStatisticsChart(IntervalMessageType jaxbMessageType, StatisticsChart stats)
        throws AdeException {

    Double intCont = stats.getDoubleStatOrThrow(LogProb);
    jaxbMessageType.setIntCont(intCont);

    double normIntCont = stats.getDoubleStatOrThrow(LogProb);
    jaxbMessageType.setNormIntCont(normIntCont);

    double anomaly = stats.getDoubleStatOrThrow(Anomaly);
    if (anomaly < 0) {
        anomaly = 0;
    }
    jaxbMessageType.setAnomaly(anomaly);

    String clusterStatus = stats.getStringStatOrThrow(ClusteringContextScore_status);
    jaxbMessageType.setClusterStatus(clusterStatus);

    double criticalWords = stats.getDoubleStatOrThrow(CriticalWordCountReporter_main);
    jaxbMessageType.setCriticalWords(criticalWords);

    /* Poisson complext type */
    Poisson poisson = new Poisson();
    jaxbMessageType.setPoisson(poisson);

    double poissonScore = stats.getDoubleStatOrThrow(LogNormalScore_main);
    poisson.setValue(poissonScore);

    double poissonMean = stats.getDoubleStatOrThrow(LogNormalScore_mean);
    poisson.setMean(poissonMean);

    /* Bernoulli complex type */
    Bernoulli bernoulli = new Bernoulli();
    jaxbMessageType.setBernoulli(bernoulli);

    double bernoulliScore = getScaledBernoulliScore(stats, clusterStatus,
            FullBernoulliClusterAwareScore_rawAnomaly);
    bernoulli.setValue(bernoulliScore);

    double bernoulliFrequency = stats.getDoubleStatOrThrow(FullBernoulliClusterAwareScore_frequency);
    if (bernoulliFrequency == 0) {
        bernoulliFrequency = 0;
    } else {
        bernoulliFrequency = m_xmlMetaData.getNumberOfIntervalsInADay() / bernoulliFrequency;
    }
    bernoulli.setFrequency(bernoulliFrequency);

    int clusterId = (int) stats.getDoubleStatOrThrow(ClusteringContextScore_clusterId);
    jaxbMessageType.setClusterId(clusterId);

    /* Periodicity complex type */
    Periodicity periodicity = new Periodicity();
    jaxbMessageType.setPeriodicity(periodicity);

    Double periodicityScore = stats.getDoubleStat(LastSeenScorer_LogProbGivenLast);
    if (periodicityScore != null) {
        periodicity.setScore(periodicityScore);
    }

    PeriodicityStatus periodicityStatus;
    String lastSeenLoggingScorerContinuous = stats.getStringStatOrThrow(LastSeenLoggingScorerContinuous_Main);
    if (periodicityScore != null) {
        if (periodicityScore > 0.7) {
            periodicityStatus = PeriodicityStatus.IN_SYNC;
        } else {
            periodicityStatus = PeriodicityStatus.NOT_IN_SYNC;
        }
    } else if (lastSeenLoggingScorerContinuous.equalsIgnoreCase("New")
            || lastSeenLoggingScorerContinuous.equalsIgnoreCase("neverSeenBefore")) {
        periodicityStatus = PeriodicityStatus.NEW;
    } else {
        periodicityStatus = PeriodicityStatus.NON_PERIODIC;
    }
    periodicity.setStatus(periodicityStatus.toString());

    String periodicityLastIssueString = stats.getStringStat(LastSeenLoggingScorerContinuous_LastTime);
    if (periodicityLastIssueString != null) {
        Calendar periodicityLastIssueCalendar = DatatypeConverter.parseDateTime(periodicityLastIssueString);
        m_gc.setTimeInMillis(periodicityLastIssueCalendar.getTimeInMillis());
        XMLGregorianCalendar periodicityLastIssue = s_dataTypeFactory.newXMLGregorianCalendar(m_gc);
        periodicity.setLastIssued(periodicityLastIssue);
    }

}

From source file:org.paxml.el.UtilFunctions.java

/**
 * Parse the standard xml date time./*from   w w w  . j  a va 2s .  c  o  m*/
 * 
 * @param str
 *            the date/time string
 * @return the calendar obj
 */
public static Calendar parseXmlDateTime(String str) {
    return DatatypeConverter.parseDateTime(str);

}