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.codice.ddf.spatial.ogc.wfs.catalog.converter.impl.AbstractFeatureConverter.java

protected Date parseDateFromXml(HierarchicalStreamReader reader) {
    Date date = null;/*w w  w .j a  va2s . co  m*/
    boolean processingChildNode = false;

    if (reader.hasMoreChildren()) {
        reader.moveDown();
        processingChildNode = true;
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("node name: {}", reader.getNodeName());
        LOGGER.debug("value: {}", reader.getValue());
    }
    if (StringUtils.isBlank(reader.getValue())) {
        date = null;
        if (processingChildNode) {
            reader.moveUp();
        }
        return date;
    }

    try { // trying to parse xsd:date
        date = DatatypeConverter.parseDate(reader.getValue()).getTime();
    } catch (IllegalArgumentException e) {
        LOGGER.debug("Unable to parse date, attempting to parse as xsd:dateTime, Exception was {}", e);
        try { // try to parse it as a xsd:dateTime
            date = DatatypeConverter.parseDateTime(reader.getValue()).getTime();
        } catch (IllegalArgumentException ie) {
            LOGGER.debug("Unable to parse date from XML; defaulting \"{}\" to current datetime.  Exception {}",
                    reader.getNodeName(), ie);
            date = new Date();
        }
    }

    if (processingChildNode) {
        reader.moveUp();
        processingChildNode = false;
    }
    LOGGER.debug("node name: {}", reader.getNodeName());
    return date;
}

From source file:org.eclipse.skalli.core.persistence.XStreamPersistenceTest.java

@Test
public void testSaveLoadCycle() throws Exception {
    TestExtensibleEntityBase entity = getExtensibleEntity();
    TestExtensibleEntityEntityService entityService = new TestExtensibleEntityEntityService(
            CURRENT_MODEL_VERSION);/*from  w w  w  .ja  va2 s .  c o m*/
    TestExtension ext1 = entity.getExtension(TestExtension.class);
    ext1.setStr(TEXT1);
    ext1.setBool(false);

    Map<String, Class<?>> aliases = getAliases();
    Set<Converter> converters = getConverters();

    TestXStreamPersistence xp = new TestXStreamPersistence();

    //saveEntity
    Calendar beforeSaveDate = Calendar.getInstance();
    xp.saveEntity(entityService, entity, USER0, aliases, converters);
    Calendar afterSaveDate = Calendar.getInstance();

    //test that entity is now in the HashMap available and lastModified is set.
    Document savedHashMapDoc = xp.getDocumentFromHashMap(entity);
    String lastModified = xp.getLastModifiedAttribute(savedHashMapDoc.getDocumentElement());
    assertNotNull(lastModified);
    assertIsXsdDateTime(lastModified);
    Calendar lastModifiedDate = DatatypeConverter.parseDateTime(lastModified);
    assertTrue(beforeSaveDate.compareTo(lastModifiedDate) <= 0);
    assertTrue(lastModifiedDate.compareTo(afterSaveDate) <= 0);

    //test that lastModifiedDate is set for extensions as well
    SortedMap<String, Element> extensions = xp.getExtensionsByAlias(savedHashMapDoc, aliases);
    assertEquals(2, extensions.size());
    String lastModifiedExt1 = xp.getLastModifiedAttribute(extensions.get(ALIAS_EXT1));
    assertIsXsdDateTime(lastModifiedExt1);
    String lastModifiedExt2 = xp.getLastModifiedAttribute(extensions.get(ALIAS_EXT1));
    assertIsXsdDateTime(lastModifiedExt2);

    //loadEntity again
    Set<ClassLoader> entityClassLoaders = getTestExtensibleEntityBaseClassLodades();
    TestExtensibleEntityBase loadedEntity = xp.loadEntity(entityService, entity.getUuid().toString(),
            entityClassLoaders, null, aliases, converters);
    assertLoadedEntityIsExpectedOne(loadedEntity, USER0, USER0, USER0, lastModified, lastModifiedExt1,
            lastModifiedExt2, TEXT1, false);

    // and check that loadEntities can read it
    List<? extends TestExtensibleEntityBase> loadedEntities = xp.loadEntities(entityService, entityClassLoaders,
            null, aliases, converters);
    assertEquals(1, loadedEntities.size());
    assertLoadedEntityIsExpectedOne(loadedEntities.get(0), USER0, USER0, USER0, lastModified, lastModifiedExt1,
            lastModifiedExt2, TEXT1, false);

    //change the entity and save  again
    ext1 = entity.getExtension(TestExtension.class);
    ext1.setStr(TEXT1 + " is now updated");
    xp.saveEntity(entityService, entity, USER1, aliases, converters);

    TestExtensibleEntityBase updatedEntity = xp.loadEntity(entityService, entity.getUuid().toString(),
            entityClassLoaders, null, aliases, converters);
    Document updatedHashMapDoc = xp.getDocumentFromHashMap(entity);
    lastModified = xp.getLastModifiedAttribute(updatedHashMapDoc.getDocumentElement());
    SortedMap<String, Element> updatedExtensions = xp.getExtensionsByAlias(updatedHashMapDoc, aliases);
    lastModifiedExt1 = xp.getLastModifiedAttribute(updatedExtensions.get(ALIAS_EXT1));
    assertLoadedEntityIsExpectedOne(updatedEntity, USER1, USER1, USER0, lastModified, lastModifiedExt1,
            lastModifiedExt2, TEXT1 + " is now updated", false);
}

From source file:org.eclipse.skalli.core.persistence.XStreamPersistenceTest.java

private void assertLastModifiedTime(String expected, String actual) {
    if (ANY_XSD_TIME.equals(expected)) {
        assertIsXsdDateTime(actual);/* w  ww. j a v a 2 s . c  o m*/
    } else if (expected.startsWith(">")) {
        assertIsXsdDateTime(actual);
        long actualMillis = DatatypeConverter.parseDateTime(actual).getTimeInMillis();
        long expectedMillis = DatatypeConverter.parseDateTime(expected.substring(1)).getTimeInMillis();
        assertTrue(actualMillis > expectedMillis);
    } else {
        assertEquals(actual, expected);
    }
}

From source file:org.eclipse.skalli.core.persistence.XStreamPersistenceTest.java

private void assertIsXsdDateTime(String lexicalXSDDateTime) {
    assertTrue(StringUtils.isNotBlank(lexicalXSDDateTime));
    DatatypeConverter.parseDateTime(lexicalXSDDateTime);
}

From source file:org.eclipse.skalli.core.rest.admin.StatisticsQuery.java

private long parseDateTime(String s, long now) {
    long dateTime = 0;
    if (StringUtils.isNotBlank(s)) {
        try {/*ww w. j a va  2 s .c  om*/
            dateTime = DatatypeConverter.parseDateTime(s).getTimeInMillis();
        } catch (IllegalArgumentException e) {
            if ("now".equalsIgnoreCase(s)) { //$NON-NLS-1$
                dateTime = now;
            } else if (s.startsWith("-")) { //$NON-NLS-1$
                //check if s is something like "-7d" indicating a time interval
                long duration = getTimeInterval(s);
                dateTime = duration < 0 ? now + duration : 0;
            }
        }
    }
    return dateTime;
}

From source file:org.eclipse.skalli.core.rest.JSONRestReader.java

@Override
public Calendar valueDatetime() throws IOException {
    assertNotFinal();/*  w ww .j a  va2  s. c o  m*/
    skipKey();
    Calendar value = json.peek() != JsonToken.NULL ? DatatypeConverter.parseDateTime(valueString()) : null;
    sequenceState = EXPECT_KEY;
    return value;
}

From source file:org.eclipse.skalli.model.EntityBase.java

/**
 * Sets the date/time of the last modification.
 *
 * Note, this method should not be called directly except for
 * testing purposes. The date/time of the last modification
 * is determined when the entity is persisted.
 *
 * @param lastModified  an ISO8061-compliant date/time string following the
 * pattern <tt>[-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]</tt> as defined for
 * type <tt>xsd:dateTime</tt>) in <tt>"XML Schema Part 2: Datatypes"</tt>,
 * or <code>null</code> to indicate that the date/time of the last modification
 * is unknown.//w  w  w .  ja v  a2s. co m
 *
 * @throws IllegalArgumentException  if the date/time string does not conform to
 * type <tt>xsd:dateTime</tt>.
 */
public void setLastModified(String lastModified) {
    if (StringUtils.isBlank(lastModified)) {
        this.lastModifiedMillis = -1L;
        this.lastModified = null;
    } else {
        this.lastModifiedMillis = DatatypeConverter.parseDateTime(lastModified).getTimeInMillis();
        this.lastModified = lastModified;
    }
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

protected void revokeCertBackdated() throws Exception {

    final P12TestUser p12TestUser = new P12TestUser();
    final X509Certificate cert = p12TestUser.getCertificate(null);

    final String issuerdn = cert.getIssuerDN().toString();
    final String serno = cert.getSerialNumber().toString(16);
    final String sDate = "2012-06-07T23:55:59+02:00";

    final CertificateProfile certProfile = this.certificateProfileSession.getCertificateProfile(WS_CERTPROF_EI);
    certProfile.setAllowBackdatedRevocation(false);
    this.certificateProfileSession.changeCertificateProfile(intAdmin, WS_CERTPROF_EI, certProfile);
    try {/*from  www .j a v a 2  s .  c  o  m*/
        this.ejbcaraws.revokeCertBackdated(issuerdn, serno, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE,
                sDate);
        assertTrue(false);
    } catch (RevokeBackDateNotAllowedForProfileException_Exception e) {
        // do nothing
    }
    certProfile.setAllowBackdatedRevocation(true);
    this.certificateProfileSession.changeCertificateProfile(intAdmin, WS_CERTPROF_EI, certProfile);
    this.ejbcaraws.revokeCertBackdated(issuerdn, serno, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE, sDate);
    final RevokeStatus revokestatus = this.ejbcaraws.checkRevokationStatus(issuerdn, serno);
    assertNotNull(revokestatus);
    final Date realRevokeDate = revokestatus.getRevocationDate().toGregorianCalendar().getTime();
    final Date expectedRevokeDate;
    try {
        expectedRevokeDate = DatatypeConverter.parseDateTime(sDate).getTime();
    } catch (IllegalArgumentException e) {
        assertTrue("Not a valid ISO8601 date revocation date", false);
        return;
    }
    assertEquals("Revocation date not the expected.", expectedRevokeDate, realRevokeDate);
}

From source file:org.ejbca.core.protocol.ws.EjbcaWS.java

@Override
public void revokeCertBackdated(final String issuerDN, final String certificateSN, final int reason,
        String sDate) throws CADoesntExistsException, AuthorizationDeniedException, NotFoundException,
        EjbcaException, ApprovalException, WaitingForApprovalException, AlreadyRevokedException,
        RevokeBackDateNotAllowedForProfileException, DateNotValidException {
    final IPatternLogger logger = TransactionLogger.getPatternLogger();
    try {//w w  w  . j a  v  a 2 s.  c  om
        if (sDate == null) {
            revokeCert(issuerDN, certificateSN, reason);
            return;
        }
        final Date date;
        try {
            date = DatatypeConverter.parseDateTime(sDate).getTime();
        } catch (IllegalArgumentException e) {
            throw new DateNotValidException(intres.getLocalizedMessage("ra.bad.date", sDate));
        }
        if (date.after(new Date())) {
            throw new DateNotValidException("Revocation date in the future: '" + sDate + "'.");
        }
        revokeCert(issuerDN, certificateSN, reason, date, logger);
    } finally {
        logger.writeln();
        logger.flush();
    }
}

From source file:org.forgerock.openidm.scheduler.ScheduleConfig.java

public ScheduleConfig(JsonValue config) {
    JsonValue enabledValue = config.get(SchedulerService.SCHEDULE_ENABLED);
    if (enabledValue.isString()) {
        enabled = Boolean.parseBoolean(enabledValue.defaultTo("true").asString());
    } else {/* w  w  w.j  a v  a2  s. c om*/
        enabled = enabledValue.defaultTo(Boolean.TRUE).asBoolean();
    }
    JsonValue persistedValue = config.get(SchedulerService.SCHEDULE_PERSISTED);
    if (persistedValue.isString()) {
        persisted = Boolean.parseBoolean(persistedValue.defaultTo("false").asString());
    } else {
        persisted = persistedValue.defaultTo(Boolean.FALSE).asBoolean();
    }
    JsonValue concurrentExecutionValue = config.get(SchedulerService.SCHEDULE_CONCURRENT_EXECUTION);
    if (concurrentExecutionValue.isString()) {
        concurrentExecution = Boolean.parseBoolean(concurrentExecutionValue.defaultTo("false").asString());
    } else {
        concurrentExecution = concurrentExecutionValue.defaultTo(Boolean.FALSE).asBoolean();
    }
    misfirePolicy = config.get(SchedulerService.SCHEDULE_MISFIRE_POLICY)
            .defaultTo(SchedulerService.MISFIRE_POLICY_FIRE_AND_PROCEED).asString();
    if (!misfirePolicy.equals(SchedulerService.MISFIRE_POLICY_FIRE_AND_PROCEED)
            && !misfirePolicy.equals(SchedulerService.MISFIRE_POLICY_DO_NOTHING)) {
        throw new InvalidException(
                new StringBuilder("Invalid misfire policy: ").append(misfirePolicy).toString());
    }
    cronSchedule = config.get(SchedulerService.SCHEDULE_CRON_SCHEDULE).asString();
    scheduleType = config.get(SchedulerService.SCHEDULE_TYPE).asString();
    invokeService = config.get(SchedulerService.SCHEDULE_INVOKE_SERVICE).asString();
    if (!StringUtils.isNotBlank(invokeService)) {
        throw new InvalidException(
                "Invalid scheduler configuration, the " + SchedulerService.SCHEDULE_INVOKE_SERVICE
                        + " property needs to be set but is empty. " + "Complete config:" + config);
    } else {
        // service PIDs fragments are prefixed with openidm qualifier
        if (!invokeService.contains(".")) {
            String fragment = invokeService;
            invokeService = SchedulerService.SERVICE_RDN_PREFIX + fragment;
        }
    }
    invokeContext = config.get(SchedulerService.SCHEDULE_INVOKE_CONTEXT).getObject();
    invokeLogLevel = config.get(SchedulerService.SCHEDULE_INVOKE_LOG_LEVEL).defaultTo("info").asString();
    String timeZoneString = config.get(SchedulerService.SCHEDULE_TIME_ZONE).asString();
    String startTimeString = config.get(SchedulerService.SCHEDULE_START_TIME).asString();
    String endTimeString = config.get(SchedulerService.SCHEDULE_END_TIME).asString();
    if (StringUtils.isNotBlank(timeZoneString)) {
        timeZone = TimeZone.getTimeZone(timeZoneString);
        // JDK has fall-back behavior to GMT if it doesn't understand timezone passed
        if (!timeZoneString.equals(timeZone.getID())) {
            throw new InvalidException("Scheduler configured timezone is not understood: " + timeZoneString);
        }
    }
    if (StringUtils.isNotBlank(startTimeString)) {
        Calendar parsed = DatatypeConverter.parseDateTime(startTimeString);
        startTime = parsed.getTime();
        // TODO: enhanced logging for failure
    }

    if (StringUtils.isNotBlank(endTimeString)) {
        Calendar parsed = DatatypeConverter.parseDateTime(endTimeString);
        endTime = parsed.getTime();
        // TODO: enhanced logging for failure
    }

    if (StringUtils.isNotBlank(scheduleType)) {
        if (!scheduleType.equals(SchedulerService.SCHEDULE_TYPE_CRON)) {
            throw new InvalidException("Scheduler configuration contains unknown schedule type " + scheduleType
                    + ". Known types include " + SchedulerService.SCHEDULE_TYPE_CRON);
        }
    }
}