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:Main.java

/**
 * Parses a date value from a string.//  ww w .ja va2  s. c  o m
 * This method should be used only for occasional parsing.
 *
 * @param  date The date to parse, or {@code null}.
 * @return The parsed date, or {@code null} if the given string was null.
 * @throws IllegalArgumentException If string parameter does not conform to
 *         XML Schema Part 2: Datatypes for {@code xsd:dateTime}.
 *
 * @see DatatypeConverter#parseDateTime(String)
 *
 * @since 3.06
 */
public static Date parseDateTime(final String date) throws IllegalArgumentException {
    if (date == null) {
        return null;
    }
    return DatatypeConverter.parseDateTime(date).getTime();
}

From source file:api.util.JsonUtil.java

public static Date asDate(Object val) {
    if (val == JSONObject.NULL)
        return null;
    if (val instanceof String) {
        String stringValue = (String) val;
        try {/*  ww w . java2s.  c o  m*/
            // try ISO 8601
            Calendar cal = DatatypeConverter.parseDateTime(stringValue);
            if (!iso8601Timezone.matcher(stringValue).matches()) {
                // timezone is absent from input string. Assume UTC
                cal.setTimeZone(TimeZone.getTimeZone("UTC"));
            }
            return cal.getTime();
        } catch (IllegalArgumentException iae) {
            // fallback to RFC 2822
            for (String format : new String[] { "EEE, dd MMM yyyy HH:mm:ss Z", "dd MMM yyyy HH:mm:ss Z",
                    "EEE, dd MMM yyyy HH:mm Z", "dd MMM yyyy HH:mm Z", "EEE, dd MMM yyyy HH:mm:ss",
                    "dd MMM yyyy HH:mm:ss", "EEE, dd MMM yyyy HH:mm", "dd MMM yyyy HH:mm" }) {
                SimpleDateFormat rfc2822Fmt = new SimpleDateFormat(format, Locale.ENGLISH);
                rfc2822Fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
                try {
                    return rfc2822Fmt.parse(stringValue);
                } catch (ParseException e) {
                }
            }
        }
    } else if (val instanceof Number) {
        return new Date(((Number) val).longValue() * 1000);
    }
    throw new IllegalArgumentException(
            "Value is expected to be a unix timestamp or a string in either ISO 8601 or RFC 2822 format: "
                    + val);
}

From source file:com.recalot.model.data.connections.reddit.RedditDataSource.java

private void readFile(String userName, File file) {

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
        String line = null;//  w  w  w . ja va 2 s.  co  m

        while ((line = reader.readLine()) != null) {
            int i = 0;
            String[] split = line.split("00;");

            if (split.length == 2) {

                Date date = DatatypeConverter.parseDateTime(split[0] + "00").getTime();

                List<String> words = splitIntoWords(split[1]);

                for (String word : words) {
                    addNewItem(word.intern());
                    addWordInteraction(userName.intern(), word.intern(), (interactionId++) + "", date, i++);
                }
            }
        }
    } catch (IOException x) {
        x.printStackTrace();
    }
}

From source file:ddf.catalog.impl.operations.OverrideAttributesSupport.java

private static AttributeImpl overrideAttributeValue(AttributeDescriptor attributeDescriptor,
        Serializable overrideValue) {
    List<Serializable> newValue = new ArrayList<>();
    for (Object o : overrideValue instanceof List ? (List) overrideValue
            : Collections.singletonList(overrideValue)) {
        try {/*www .j a  va  2  s . com*/
            String override = String.valueOf(o);
            switch (attributeDescriptor.getType().getAttributeFormat()) {
            case INTEGER:
                newValue.add(Integer.parseInt(override));
                break;
            case FLOAT:
                newValue.add(Float.parseFloat(override));
                break;
            case DOUBLE:
                newValue.add(Double.parseDouble(override));
                break;
            case SHORT:
                newValue.add(Short.parseShort(override));
                break;
            case LONG:
                newValue.add(Long.parseLong(override));
                break;
            case DATE:
                Calendar calendar = DatatypeConverter.parseDateTime(override);
                newValue.add(calendar.getTime());
                break;
            case BOOLEAN:
                newValue.add(Boolean.parseBoolean(override));
                break;
            case BINARY:
                newValue.add(override.getBytes(Charset.forName("UTF-8")));
                break;
            case OBJECT:
            case STRING:
            case GEOMETRY:
            case XML:
                newValue.add(override);
                break;
            }
        } catch (IllegalArgumentException e) {
            return null;
        }
    }
    return new AttributeImpl(attributeDescriptor.getName(), newValue);
}

From source file:com.marklogic.client.test.BitemporalTest.java

@Test
public void a_testCreate() throws Exception {
    String contents = "<test>" + "<system-start></system-start>" + "<system-end></system-end>"
            + "<valid-start>2014-08-19T00:00:00Z</valid-start>" + "<valid-end>2014-08-19T00:00:01Z</valid-end>"
            + "</test>";
    TemporalDescriptor desc = docMgr.create(docMgr.newDocumentUriTemplate("xml"), null,
            new StringHandle(contents), null, null, temporalCollection);
    assertNotNull("Missing TemporalDescriptor from create", desc);
    assertNotNull(desc.getUri());/*from w w w.  ja  v  a  2s.c om*/
    assertTrue(desc.getUri().endsWith(".xml"));
    String lastWriteTimestamp = desc.getTemporalSystemTime();
    Calendar lastWriteTime = DatatypeConverter.parseDateTime(lastWriteTimestamp);
    assertNotNull(lastWriteTime);
}

From source file:de.slub.fedora.oai.OaiHarvesterTestIT.java

@Test
public void runWhenLastrunIsInPast() throws Exception {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.YEAR, -1);//from ww w.ja  v  a2  s  . c o  m

    esNode.client().prepareIndex("_river", "fedora", "_last")
            .setSource(jsonBuilder().startObject().field("timestamp", cal).endObject()).execute().actionGet();

    embeddedHttpHandler.resourcePath = OAI_LIST_RECORDS_XML;
    runAndWait(oaiHarvester);

    GetResponse response = esNode.client().get(new GetRequest("_river", "fedora", "_last")).actionGet();

    TimeValue lastRunTime = TimeValue.timeValueMillis(cal.getTimeInMillis());
    TimeValue actualRunTime = TimeValue.timeValueMillis(DatatypeConverter
            .parseDateTime(String.valueOf(response.getSourceAsMap().get("timestamp"))).getTimeInMillis());

    assertTrue("Actual run should happen after last run", actualRunTime.getMillis() > lastRunTime.getMillis());
}

From source file:com.fluidops.iwb.api.ValueResolver.java

/**
 * Resolves a value string using a specified resolver (as string).
 * Can be extended on demand by new resolvers. Should not return
 * null./*from   www .j ava 2s .  co  m*/
 * 
 * @param value
 * @param resolver
 * @return
 */
public static String resolve(Value value, ResolverType resolver) {
    if (resolver == null)
        resolver = ResolverType.DEFAULT;
    if (value == null)
        value = ValueFactoryImpl.getInstance().createLiteral("");

    try {
        switch (resolver) {
        case MS_TIMESTAMP2DATE:
            return resolveDateFromTimestamp(value.stringValue(), 1);
        case S_TIMESTAMP2DATE:
            return resolveDateFromTimestamp(value.stringValue(), 1000);
        case DATE:
            return resolveCalendar(DatatypeConverter.parseDate(value.stringValue()), "MMM dd, yyyy");
        case TIME:
            return resolveCalendar(DatatypeConverter.parseTime(value.stringValue()), "HH:mm:ss");
        case DATETIME:
            return resolveCalendar(DatatypeConverter.parseDateTime(value.stringValue()),
                    "MMM dd, yyyy HH:mm:ss");
        case SYSDATE:
            return resolveSysDate(value.stringValue());
        case IMAGE:
            return resolveImage(value);
        case THUMBNAIL:
            return resolveThumbnail(value, "20px");
        case BIGTHUMBNAIL:
            return resolveThumbnail(value, "50px");
        case DOUBLE2INT:
            return resolveDecimalFromDouble(Double.valueOf(value.stringValue()));
        case URL:
            return resolveURL(value.stringValue(), null);
        case HTML:
            return resolveHtml(value);
        case LOGINLINK:
            return resolveURL(value.stringValue(), "Login");
        case BYTE2KB:
            return resolveByte2X(value.stringValue(), "KB");
        case BYTE2MB:
            return resolveByte2X(value.stringValue(), "MB");
        case BYTE2GB:
            return resolveByte2X(value.stringValue(), "GB");
        case BYTE2TB:
            return resolveByte2X(value.stringValue(), "TB");
        case KBYTE2MB:
            return resolveKByte2X(value.stringValue(), "MB");
        case KBYTE2GB:
            return resolveKByte2X(value.stringValue(), "GB");
        case KBYTE2TB:
            return resolveKByte2X(value.stringValue(), "TB");
        case PERCENT:
            return resolvePercent(value.stringValue());
        case PERCENT_NOCONVERT:
            return resolvePercentNoConvert(value.stringValue());
        case ROUND_DOUBLE:
            return resolveNumber2Places(value.stringValue());
        case CURRENCY_USD:
            return resolveCurrency(value.stringValue(), "USD");
        case CURRENCY_EUR:
            return resolveCurrency(value.stringValue(), "EUR");
        case CURRENCY_CNY:
            return resolveCurrency(value.stringValue(), "CNY");
        case DEFAULT_NOERROR:
            return resolveDefaultNoError(value);
        case DEFAULT:
        default:
            return resolveDefault(value);
        }
    } catch (Exception e) {
        return resolveDefault(value);
    }
}

From source file:com.persistent.cloudninja.controller.AuthFilterUtils.java

/**
 * @param sessionExpiresAt/* w ww.  j  av a2 s  .  co m*/
 * @return
 */
public static Date convertISOTimeStringToDate(String timeString) {
    Calendar calendar = DatatypeConverter.parseDateTime(timeString);
    return calendar.getTime();
}

From source file:de.unioninvestment.eai.portal.portlet.crud.scripting.domain.container.rest.ValueConverter.java

private Object convertStringToDate(String format, Locale locale, String value) {
    try {/*  www  .java  2 s . c  o m*/
        if (StringUtils.isBlank(value)) {
            return null;
        } else if (StringUtils.equalsIgnoreCase(format, "iso8601")) {
            Calendar calendar = DatatypeConverter.parseDateTime(value);
            return calendar.getTime();
        } else {
            // SimpleDateFormat
            return new SimpleDateFormat(format, locale).parse(value);
        }

    } catch (ParseException e) {
        throw new IllegalArgumentException("Cannot convert to date: " + value, e);
    }
}

From source file:de.slub.fedora.oai.OaiHarvester.java

private Date getDate(Map<String, Object> src, String param) {
    if (src.containsKey(param)) {
        String s = (String) src.get(param);
        if (!s.isEmpty()) {
            return DatatypeConverter.parseDateTime(s).getTime();
        }// w w w  . j  a v  a 2  s  .  co  m
    }
    return null;
}