Example usage for org.apache.commons.lang3.time DateUtils parseDate

List of usage examples for org.apache.commons.lang3.time DateUtils parseDate

Introduction

In this page you can find the example usage for org.apache.commons.lang3.time DateUtils parseDate.

Prototype

public static Date parseDate(final String str, final String... parsePatterns) throws ParseException 

Source Link

Document

Parses a string representing a date by trying a variety of different parsers.

The parse will try each parse pattern in turn.

Usage

From source file:ren.hankai.cordwood.jackson.DateTimeDeserializerTest.java

@Test
public void testDeserializeWithCustomFormat() throws Exception {
    final ObjectMapper om = new ObjectMapper();
    final DateTimeDeserializer des = new DateTimeDeserializer("yyyy|MM|dd HH|mm|ss");
    final JsonParser jp = om.getFactory().createParser("{\"date\": \"2018|09|01 13|23|12\"}");

    String val = null;
    do {/* w w w  . j  a  v a  2 s  .c o  m*/
        val = jp.nextTextValue();
    } while (val == null);

    final Date date = des.deserialize(jp, om.getDeserializationContext());
    final Date expDate = DateUtils.parseDate(jp.getText(), "yyyy|MM|dd HH|mm|ss");
    Assert.assertTrue(DateUtils.truncatedEquals(date, expDate, Calendar.SECOND));
}

From source file:ren.hankai.cordwood.jackson.DateTimeSerializerTest.java

@Test
public void testSerialize() throws Exception {
    final ObjectMapper om = new ObjectMapper();
    final StringWriter sw = new StringWriter();
    final JsonGenerator jgen = om.getFactory().createGenerator(sw);

    final Date date = DateUtils.parseDate("2018-11-12 13:22:22", "yyyy-MM-dd HH:mm:ss");
    final DateTimeSerializer ser = new DateTimeSerializer();
    ser.serialize(date, jgen, om.getSerializerProvider());
    jgen.flush();/*from   w  w  w .  j  av  a  2s .co  m*/

    Assert.assertEquals("\"2018-11-12 13:22:22\"", sw.toString());
}

From source file:ren.hankai.cordwood.jackson.DateTimeSerializerTest.java

@Test
public void testSerializeWithCustomFormat() throws Exception {
    final ObjectMapper om = new ObjectMapper();
    final StringWriter sw = new StringWriter();
    final JsonGenerator jgen = om.getFactory().createGenerator(sw);

    final Date date = DateUtils.parseDate("2018-11-12 11:11:11", "yyyy-MM-dd HH:mm:ss");
    final DateTimeSerializer ser = new DateTimeSerializer("yyyy|MM|dd HH|mm|ss");
    ser.serialize(date, jgen, om.getSerializerProvider());
    jgen.flush();//from w w  w  . java2  s  .  c  o m

    Assert.assertEquals("\"2018|11|12 11|11|11\"", sw.toString());
}

From source file:top.gabin.oa.web.utils.date.UtilDateTime.java

public static Date parseDate(String str, String dateFromat) {
    Set<String> patterns = new HashSet<String>();
    patterns.addAll(PARSE_PATTERNS);/*from  ww  w.j a va  2 s . c o m*/
    patterns.add(dateFromat);
    try {
        return DateUtils.parseDate(str, patterns.toArray(new String[patterns.size()]));
    } catch (ParseException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException("?" + str, e);
    }
}

From source file:ubic.gemma.core.loader.entrez.pubmed.PubMedXMLParser.java

public void extractBookPublicationYear(BibliographicReference bibRef, Node item) {
    NodeList c = item.getChildNodes();
    for (int i = 0; i < c.getLength(); i++) {
        Node a = c.item(i);//from   w  ww  . j  a  va  2  s.c  o m
        if (!(a instanceof Element)) {
            continue;
        }
        if (a.getNodeName().equals("Year")) {
            try {
                bibRef.setPublicationDate(DateUtils.parseDate(XMLUtils.getTextValue((Element) a), formats));
            } catch (ParseException e) {
                PubMedXMLParser.log.warn(
                        "Could not extract date of publication from : " + XMLUtils.getTextValue((Element) a));
            }
        }
    }
}

From source file:ubic.gemma.core.loader.entrez.pubmed.PubMedXMLParser.java

private Date extractJournalIssueDate(Node dateNode) {

    String yearText = null;// = XMLUtils.getTextValue( ( Element ) y );
    String medLineText = null;// = XMLUtils.getTextValue( ( Element ) medLineDate );
    String monthText = null;// = XMLUtils.getTextValue( ( Element ) m );
    String dayText = null;// = XMLUtils.getTextValue( ( Element ) dn );

    NodeList childNodes = dateNode.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node c = childNodes.item(i);
        if (!(c instanceof Element)) {
            continue;
        }/*from w  w w .  j  av  a2  s  . c  o m*/
        String t = XMLUtils.getTextValue((Element) c);
        switch (c.getNodeName()) {
        case "Year":
            yearText = t;
            break;
        case "Month":
            monthText = t;
            break;
        case "Day":
            dayText = t;
            break;
        case "MedlineDate":
            medLineText = t;
            break;
        default:
            log.warn("Unrecognized node name " + c.getNodeName());
        }
    }

    df.setLenient(true);

    if (yearText == null && medLineText != null) {
        String[] yearmo = medLineText.split("\\s");
        switch (yearmo.length) {
        case 2:
            // 1983 Aug
            yearText = yearmo[0];
            monthText = yearmo[1];
            monthText = monthText.replaceAll("-\\w+", "");
            break;
        case 4:
            // 1983 Aug 31-Sep 6
            yearText = yearmo[0];
            monthText = yearmo[1];
            dayText = yearmo[2].replaceAll("-\\w+", "");
            break;
        case 3:
            // 1983 Jul 9-16
            yearText = yearmo[0];
            monthText = yearmo[1];
            dayText = yearmo[2].replaceAll("-\\w+", "");
            break;
        case 1:
            // 1983-84
            yearText = yearmo[0];
            yearText = yearText.replaceAll("-\\w+", "");
            break;
        default:
            PubMedXMLParser.log.warn("No data information from medline text: " + medLineText);
            break;
        }
    }

    if (monthText == null) {
        monthText = "Jan"; // arbitrary...
    }

    String dateString = monthText + " " + (dayText == null ? "1" : dayText) + ", " + yearText;

    try {
        return DateUtils.parseDate(dateString, formats);
    } catch (ParseException e) {
        PubMedXMLParser.log.warn("Could not parse date " + dateString + " from medlinetext=" + medLineText);
        return null;
    }
}

From source file:ubic.gemma.core.loader.expression.geo.service.GeoBrowser.java

/**
 * Retrieves and parses tab delimited file from GEO. File contains pageSize GEO records starting from startPage.
 *
 * @param startPage start page/*  w  ww  .  ja va  2  s. c  om*/
 * @param pageSize  page size
 * @return list of GeoRecords
 * @throws IOException    if there is a problem while manipulating the file
 * @throws ParseException if there is a parsing problem
 */
public List<GeoRecord> getRecentGeoRecords(int startPage, int pageSize) throws IOException, ParseException {

    if (startPage < 0 || pageSize < 0)
        throw new IllegalArgumentException("Values must be greater than zero ");

    List<GeoRecord> records = new ArrayList<>();
    URL url;
    try {
        url = new URL(GEO_BROWSE_URL + startPage + GEO_BROWSE_SUFFIX + pageSize);
    } catch (MalformedURLException e) {
        throw new RuntimeException("Invalid URL: " + GEO_BROWSE_URL + startPage + GEO_BROWSE_SUFFIX + pageSize,
                e);
    }

    URLConnection conn = url.openConnection();
    conn.connect();
    try (InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is))) {

        // We are getting a tab delimited file.

        // Read columns headers.
        String headerLine = br.readLine();
        String[] headers = StringUtil.csvSplit(headerLine);

        // Map column names to their indices (handy later).
        Map<String, Integer> columnNameToIndex = new HashMap<>();
        for (int i = 0; i < headers.length; i++) {
            columnNameToIndex.put(headers[i], i);
        }

        // Read the rest of the file.
        String line;
        while ((line = br.readLine()) != null) {
            String[] fields = StringUtil.csvSplit(line);

            GeoRecord geoRecord = new GeoRecord();
            geoRecord.setGeoAccession(fields[columnNameToIndex.get("Accession")]);
            geoRecord.setTitle(StringUtils.strip(
                    fields[columnNameToIndex.get("Title")].replaceAll(GeoBrowser.FLANKING_QUOTES_REGEX, "")));

            String sampleCountS = fields[columnNameToIndex.get("Sample Count")];
            if (StringUtils.isNotBlank(sampleCountS)) {
                try {
                    geoRecord.setNumSamples(Integer.parseInt(sampleCountS));
                } catch (NumberFormatException e) {
                    throw new RuntimeException("Could not parse sample count: " + sampleCountS);
                }
            } else {
                GeoBrowser.log.warn("No sample count for " + geoRecord.getGeoAccession());
            }
            geoRecord.setContactName(
                    fields[columnNameToIndex.get("Contact")].replaceAll(GeoBrowser.FLANKING_QUOTES_REGEX, ""));

            String[] taxons = fields[columnNameToIndex.get("Taxonomy")]
                    .replaceAll(GeoBrowser.FLANKING_QUOTES_REGEX, "").split(";");
            geoRecord.getOrganisms().addAll(Arrays.asList(taxons));

            Date date = DateUtils.parseDate(fields[columnNameToIndex.get("Release Date")]
                    .replaceAll(GeoBrowser.FLANKING_QUOTES_REGEX, ""), DATE_FORMATS);
            geoRecord.setReleaseDate(date);

            geoRecord.setSeriesType(fields[columnNameToIndex.get("Series Type")]);

            records.add(geoRecord);
        }

    }

    if (records.isEmpty()) {
        GeoBrowser.log.warn("No records obtained");
    }
    return records;

}