Example usage for java.text DateFormat parse

List of usage examples for java.text DateFormat parse

Introduction

In this page you can find the example usage for java.text DateFormat parse.

Prototype

public Date parse(String source) throws ParseException 

Source Link

Document

Parses text from the beginning of the given string to produce a date.

Usage

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

private void setLastModified(HttpMessage response, int statusCode) {
    long lastModified = 0;
    Header header = response.getFirstHeader("Last-Modified");
    if (header != null) {
        try {//from  w w  w.j  a  v a 2s .  c o  m
            DateFormat format = new SimpleDateFormat();
            // TODO lock down the expected format (wasn't specified in orig code...
            lastModified = format.parse(header.getValue()).getTime();
        } catch (java.text.ParseException e) {
            log.error(e, e);
        }
    } else if (statusCode == 200) {
        lastModified = System.currentTimeMillis();
    }
    if (lastModified != 0) {
        setValue("LastModified", lastModified);
    }
}

From source file:com.datatorrent.contrib.parser.FixedWidthParser.java

/**
 * Function to validate and set the current field.
 * @param currentField the field which is to be validated and set
 * @param value the parsed value of the field
 * @param typeInfo information about the field in POJO
 * @param pojoObject POJO which is to be set
 * @param toEmit the map to be emitted//  w w  w. j  a v  a2  s  .  c  o m
 */
private void validateAndSetCurrentField(FixedWidthSchema.Field currentField, String value,
        FixedWidthParser.TypeInfo typeInfo, Object pojoObject, HashMap toEmit) {
    try {
        String fieldName = currentField.getName();
        if (value != null && !value.isEmpty()) {
            Object result;
            switch (currentField.getType()) {
            case INTEGER:
                result = Integer.parseInt(value);
                break;
            case DOUBLE:
                result = Double.parseDouble(value);
                break;
            case STRING:
                result = value;
                break;
            case CHARACTER:
                result = value.charAt(0);
                break;
            case FLOAT:
                result = Float.parseFloat(value);
                break;
            case LONG:
                result = Long.parseLong(value);
                break;
            case SHORT:
                result = Short.parseShort(value);
                break;
            case BOOLEAN:
                if (value.compareToIgnoreCase(currentField.getTrueValue()) == 0) {
                    result = Boolean.parseBoolean("true");
                } else if (value.compareToIgnoreCase(currentField.getFalseValue()) == 0) {
                    result = Boolean.parseBoolean("false");
                } else {
                    throw new NumberFormatException();
                }
                break;
            case DATE:
                DateFormat df = new SimpleDateFormat(currentField.getDateFormat());
                df.setLenient(false);
                result = df.parse(value);
                break;
            default:
                throw new RuntimeException("Invalid Type in Field", new Exception());
            }
            toEmit.put(fieldName, result);
            if (typeInfo != null && pojoObject != null) {
                typeInfo.setter.set(pojoObject, result);
            }
        } else {
            toEmit.put(fieldName, value);
        }
    } catch (NumberFormatException e) {
        throw new RuntimeException("Error parsing" + value + " to Integer type", e);
    } catch (ParseException e) {
        throw new RuntimeException("Error parsing" + value, e);
    } catch (Exception e) {
        throw new RuntimeException("Error setting " + value + " in the given class" + typeInfo.toString(), e);
    }
}

From source file:com.mobileman.projecth.business.patient.PatientQuestionAnswerServiceTest.java

/**
 * @throws Exception/*  w  ww .  j  av  a 2s . co  m*/
 */
@Test
public void findAll() throws Exception {

    User patient = userService.findUserByLogin("sysuser1");
    assertNotNull(patient);

    List<Haq> haqs = haqService.findAll();

    DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
    Question question = null;
    for (Question q : haqs.get(0).getQuestions()) {
        if ("Geschwollen rechte Hand Daumen vorne".equals(q.getText())) {
            question = q;
            break;
        }
    }

    List<PatientQuestionAnswer> result = patientQuestionAnswerService.findAll(patient.getId(), question.getId(),
            dateFormat.parse("1.1.2010"), dateFormat.parse("1.11.2010"));
    assertEquals(1, result.size());

}

From source file:ch.icclab.cyclops.services.iaas.openstack.persistence.TSDBResource.java

/**
 * Receives the usage data array and the gauge meter name. The usage data is transformed
 * to a json data and saved into the the InfluxDB
 * <p>//from ww  w.j ava2  s.  c  o m
 * Pseudo Code
 * 1. Iterate through the data array to save the data into an ArraList of objects
 * 2. Save the data into the TSDB POJO class
 * 3. Convert the POJO class to a JSON obj
 * 4. Invoke the InfluxDb client to save the data
 *
 * @param dataArr   An array list consisting of usage data
 * @param meterName Name of the Gauge Meter
 * @return result A boolean output as a result of saving the meter data into the db
 */
public boolean saveGaugeMeterData(ArrayList<GaugeMeterData> dataArr, String meterName) {
    GaugeMeterData gMeterData;
    boolean result = true;
    dbname = settings.getInfluxDBDatabaseName();
    try {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        format.setTimeZone(TimeZone.getTimeZone("UTC"));
        logger.debug("Data Array length before writing points: " + dataArr.size());
        for (int i = 0; i < dataArr.size(); i++) {
            gMeterData = dataArr.get(i);
            Date date = format.parse(gMeterData.getPeriod_end());
            long timeMillisec = date.getTime();
            logger.debug("Attempting to build a Point for: " + meterName);
            Point point = Point.measurement(meterName).time(timeMillisec, TimeUnit.MILLISECONDS)
                    .tag("userid", gMeterData.getGroupby().getUser_id())
                    .tag("resourceid", gMeterData.getGroupby().getResource_id())
                    .tag("projectid", gMeterData.getGroupby().getProject_id()).tag("type", "gauge")
                    .field("min", gMeterData.getMin()).field("max", gMeterData.getMax())
                    .field("sum", gMeterData.getSum()).field("avg", gMeterData.getAvg())
                    .tag("unit", gMeterData.getUnit()).field("count", gMeterData.getCount()).build();
            logger.debug("Attempting to write the Point (" + meterName + ")");
            influxDB.write(dbname, "default", point);
            logger.debug("Point successfully written.");
        }
    } catch (Exception e) {
        logger.error("Error while trying to save Gauge meter data into the DB: " + e.getMessage());
        return false;
    }
    return result;
}

From source file:ch.icclab.cyclops.services.iaas.openstack.persistence.TSDBResource.java

/**
 * Receives the usage data array and the gauge meter name. The usage data is transformed
 * to a json data and saved into the the InfluxDB
 * <p>/*from w w w .  j  a v  a2s  .c  o m*/
 * Pseudo Code
 * 1. Iterate through the data array to save the data into an ArraList of objects
 * 2. Save the data into the TSDB POJO class
 * 3. Convert the POJO class to a JSON obj
 * 4. Invoke the InfluxDb client to save the data
 *
 * @param dataArr   An array list consisting of usage data
 * @param meterName Name of the Gauge Meter
 * @return result A boolean output as a result of saving the meter data into the db
 */
public boolean saveCumulativeMeterData(ArrayList<CumulativeMeterData> dataArr, String meterName) {
    CumulativeMeterData cMeterData;
    boolean result = true;
    dbname = settings.getInfluxDBDatabaseName();
    try {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        format.setTimeZone(TimeZone.getTimeZone("UTC"));
        logger.debug("Data Array length before writing points: " + dataArr.size());
        for (int i = 0; i < dataArr.size(); i++) {
            cMeterData = dataArr.get(i);
            Date date = format.parse(cMeterData.getRecorded_at());
            long timeMillisec = date.getTime();
            logger.debug("Attempting to build a Point for: " + meterName);
            Point point = Point.measurement(meterName).time(timeMillisec, TimeUnit.MILLISECONDS)
                    .tag("userid", cMeterData.getUser_id()).tag("resourceid", cMeterData.getResource_id())
                    .field("volume", cMeterData.getVolume()).field("usage", cMeterData.getUsage())
                    .tag("source", cMeterData.getSource()).tag("project_id", cMeterData.getProject_id())
                    .tag("type", cMeterData.getType()).tag("id", cMeterData.getId())
                    .field("unit", cMeterData.getUnit())
                    .tag("instance_id", cMeterData.getMetadata().getInstance_id())
                    .tag("instance_type", cMeterData.getMetadata().getInstance_type())
                    .tag("mac", cMeterData.getMetadata().getMac())
                    .tag("fref", cMeterData.getMetadata().getFref())
                    .tag("name", cMeterData.getMetadata().getName()).build();
            logger.debug("Attempting to write the Point (" + meterName + ")");
            influxDB.write(dbname, "default", point);
            logger.debug("Point successfully written.");
        }
    } catch (Exception e) {
        logger.error("Error while trying to save Cumulative meter data into the DB: " + e.getMessage());
        return false;
    }
    return result;
}

From source file:com.netflix.governator.lifecycle.LifecycleManager.java

private Date parseDate(String configurationName, String value, Configuration configuration) {
    DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
    formatter.setLenient(false);/*from  ww w.jav  a  2  s  .co m*/

    try {
        return formatter.parse(value);
    } catch (ParseException e) {
        // ignore as the fallback is the DatattypeConverter.
    }

    try {
        return DatatypeConverter.parseDateTime(value).getTime();
    } catch (IllegalArgumentException e) {
        ignoreTypeMismtachIfConfigured(configuration, configurationName, e);
    }

    return null;
}

From source file:com.charts.YTDChart.java

protected OHLCDataItem[] getData(YStockQuote currentStock) throws ParseException {
    ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
    DateFormat df;
    if (currentStock instanceof Index)
        df = new SimpleDateFormat("y-MM-dd");
    else//from w  ww .ja  v  a  2s.  co  m
        df = new SimpleDateFormat("d-MM-yy");
    String OneYearDate = df.format(DayRange.ytd);
    ArrayList<String> historicalData = currentStock.get_historical_data();
    int length = historicalData.size();
    for (int i = 1; i < length; i++) {

        String[] data = historicalData.get(i).split(",");

        Date date = df.parse(data[0]);
        double open = Double.parseDouble(data[1]);
        double high = Double.parseDouble(data[2]);
        double low = Double.parseDouble(data[3]);
        double close = Double.parseDouble(data[4]);
        this.close.addOrUpdate(new Day(date), close);
        double volume;
        try {
            volume = Double.parseDouble(data[5]);
        } catch (NumberFormatException nfe) {
            volume = 0;
        }
        if (data[0].equals(OneYearDate)) {
            break;
        }

        OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
        dataItems.add(item);
    }
    Collections.reverse(dataItems);

    OHLCDataItem[] OHLCData = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
    return OHLCData;
}

From source file:net.sourceforge.subsonic.service.PodcastService.java

private Date parseDate(String s) {
    for (DateFormat dateFormat : RSS_DATE_FORMATS) {
        try {//from w ww  .ja  v  a  2 s . c o  m
            return dateFormat.parse(s);
        } catch (Exception x) {
            // Ignored.
        }
    }
    LOG.warn("Failed to parse publish date: '" + s + "'.");
    return null;
}

From source file:net.frontlinesms.plugins.reminders.RemindersDialogHandler.java

/**
 * Get time ticks from date fields//from   www. j a v  a  2s. co m
 * @param textDate
 * @param comboHour
 * @param comboMinute
 * @param comboAmPm
 * @return time ticks
 */
private long getLongFromDateFields(Object textDate, Object comboHour, Object comboMinute, Object comboAmPm) {
    try {
        String date = this.ui.getText(textDate);
        int hour = this.ui.getSelectedIndex(comboHour) + 1;
        int minute = this.ui.getSelectedIndex(comboMinute);
        boolean isAM = this.ui.getSelectedIndex(comboAmPm) == 0;
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date dateTime = dateFormat.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateTime);
        if (isAM && hour == 12) {
            calendar.set(Calendar.HOUR_OF_DAY, 0);
        } else if (isAM && hour < 12) {
            calendar.set(Calendar.HOUR_OF_DAY, hour);
        } else if (!isAM && hour == 12) {
            calendar.set(Calendar.HOUR_OF_DAY, 12);
        } else if (!isAM) {
            calendar.set(Calendar.HOUR_OF_DAY, hour + 12);
        }
        calendar.set(Calendar.MINUTE, minute);
        return calendar.getTimeInMillis();
    } catch (ParseException e) {
        return 0;
    }
}

From source file:com.charts.OneYearChart.java

protected OHLCDataItem[] getData(YStockQuote currentStock) throws ParseException {
    ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
    DateFormat df;
    if (currentStock instanceof Index)
        df = new SimpleDateFormat("y-MM-dd");
    else/*  w  w w  . j  a v a 2s. co m*/
        df = new SimpleDateFormat("d-MM-yy");
    String OneYearDate = df.format(DayRange.one_year);
    ArrayList<String> historicalData = currentStock.get_historical_data();
    int length = historicalData.size();
    for (int i = 1; i < length; i++) {

        String[] data = historicalData.get(i).split(",");

        Date date = df.parse(data[0]);
        double open = Double.parseDouble(data[1]);
        double high = Double.parseDouble(data[2]);
        double low = Double.parseDouble(data[3]);
        double close = Double.parseDouble(data[4]);
        this.close.addOrUpdate(new Day(date), close);
        double volume;
        try {
            volume = Double.parseDouble(data[5]);
        } catch (NumberFormatException nfe) {
            volume = 0;
        }
        if (data[0].equals(OneYearDate)) {
            break;
        }

        OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
        dataItems.add(item);
    }
    Collections.reverse(dataItems);

    OHLCDataItem[] OHLCData = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
    return OHLCData;
}