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:br.com.binarti.simplesearchexpr.converter.DateSearchDataConverter.java

@SuppressWarnings("unchecked")
@Override//from  www  .  jav  a  2 s .  c  om
protected Object asSingleObject(SimpleSearchExpressionField field, String value, Map<String, Object> params,
        Class<?> targetType) {
    String[] parsePatterns = new String[] { defaultPattern };
    if (params != null && params.containsKey(PATTERN_PARAM_NAME)) {
        Object paramValue = params.get(PATTERN_PARAM_NAME);
        if (paramValue instanceof Collection) {
            parsePatterns = ((Collection<String>) paramValue).toArray(new String[0]);
        } else if (paramValue instanceof String[]) {
            parsePatterns = (String[]) paramValue;
        } else if (paramValue instanceof String) {
            parsePatterns = new String[] { (String) params.get(PATTERN_PARAM_NAME) };
        } else {
            throw new SimpleSearchDataConverterException(
                    "Invalid param pattern, expected Collection<String>, String[] or String, but found "
                            + paramValue.getClass());
        }
    }
    try {
        return DateUtils.parseDate(value.trim(), parsePatterns);
    } catch (ParseException e) {
        throw new SimpleSearchDataConverterException("Date " + value + " invalid format");
    }
}

From source file:ch.aonyx.broker.ib.api.execution.ExecutionReportFilter.java

public DateTime getDateTime() {
    try {//  ww  w .  java  2s . co m
        return new DateTime(DateUtils.parseDate(time, "yyyyMMdd-HH:mm:ss"));
    } catch (final ParseException e) {
    }
    return null;
}

From source file:ch.aonyx.broker.ib.api.execution.CommissionReport.java

public DateTime getYieldRedemptionDateTime() {
    try {/*from w w w  .  j  a va 2s.  c o  m*/
        return new DateTime(DateUtils.parseDate(String.valueOf(yieldRedemptionDate), DATE_PATTERN).getTime());
    } catch (final ParseException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:ch.aonyx.broker.ib.api.contract.Contract.java

public Date getExpirationDate() {
    if (StringUtils.isNotEmpty(expiry)) {
        try {//from   www  .ja v a  2  s.  com
            return DateUtils.parseDate(expiry, "YYYYMM");
        } catch (final ParseException e) {
            throw new NeoIbApiClientException(ClientMessageCode.INTERNAL_ERROR, e.getMessage(), e);
        }
    }
    return null;
}

From source file:jp.dip.komusubi.botter.gae.module.jal5971.FlightStatusEntry.java

public Date getScheduledDepartureDate() {
    try {/*from   w  ww . j  av  a  2 s.  c  o  m*/
        return DateUtils.parseDate(getElement(column, 2).getText().trim(), new String[] { HOUR_FORMAT });
    } catch (ParseException e) {
        logger.warn("scheduledDepartureDate() parse error {}", e.getLocalizedMessage());
        return resolver.resolve();
    }
}

From source file:com.adguard.android.contentblocker.ServiceApiClient.java

/**
 * Downloads filter versions./*from   ww w.j a  v a2s  .co m*/
 *
 * @param filters list
 * @return filters list with downloaded versions
 */
public static List<FilterList> downloadFilterVersions(Context context, List<FilterList> filters)
        throws IOException, JSONException {
    String downloadUrl = RawResources.getCheckFilterVersionsUrl(context);
    LOG.info("Sending request to {}", downloadUrl);
    String response = downloadString(downloadUrl);
    if (StringUtils.isBlank(response)) {
        return null;
    }

    Set<Integer> filterIds = new HashSet<>(filters.size());
    for (FilterList filter : filters) {
        filterIds.add(filter.getFilterId());
    }

    Map map = readValue(response, Map.class);
    if (map == null || !map.containsKey("filters")) {
        LOG.error("Filters parse error! Response:\n{}", response);
        return null;
    }

    ArrayList filterList = (ArrayList) map.get("filters");
    List<FilterList> result = new ArrayList<>(filters.size());
    String[] parsePatterns = { "yyyy-MM-dd'T'HH:mm:ssZ" };

    for (Object filterObj : filterList) {
        Map filter = (Map) filterObj;
        int filterId = (int) filter.get("filterId");
        if (!filterIds.contains(filterId)) {
            continue;
        }
        FilterList list = new FilterList();
        list.setName((String) filter.get("name"));
        list.setDescription((String) filter.get("description"));
        list.setFilterId(filterId);
        list.setVersion((String) filter.get("version"));
        try {
            String timeUpdated = (String) filter.get("timeUpdated");
            list.setTimeUpdated(DateUtils.parseDate(timeUpdated, parsePatterns));
        } catch (ParseException e) {
            LOG.error("Unable to parse date from filters:\n", e);
        }
        result.add(list);
    }

    return result;

}

From source file:com.bitplan.vzjava.resources.PowerPlotResource.java

/**
 * http://stackoverflow.com/a/10257341/1497139
 * Sends the file if modified and "not modified" if not modified
 * future work may put each file with a unique id in a separate folder in
 * tomcat/*from   ww  w .  j  a v a  2s .co m*/
 * * use that static URL for each file
 * * if file is modified, URL of file changes
 * * -> client always fetches correct file
 * 
 * method header for calling method public Response
 * getXY(@HeaderParam("If-Modified-Since") String modified) {
 * 
 * @param file
 *          to send
 * @param modified
 *          - HeaderField "If-Modified-Since" - may be "null"
 * @return Response to be sent to the client
 */
public static Response returnFile(File file, String modified) {
    if (!file.exists()) {
        return Response.status(Status.NOT_FOUND).build();
    }

    // do we really need to send the file or can send "not modified"?
    if (modified != null) {
        Date modifiedDate = null;

        // we have to switch the locale to ENGLISH as parseDate parses in the
        // default locale
        Locale old = Locale.getDefault();
        Locale.setDefault(Locale.ENGLISH);
        try {
            modifiedDate = DateUtils.parseDate(modified, DEFAULT_PATTERNS);
        } catch (ParseException e) {
            LOGGER.log(Level.WARNING, e.getMessage());
        }
        Locale.setDefault(old);

        if (modifiedDate != null) {
            // modifiedDate does not carry milliseconds, but fileDate does
            // therefore we have to do a range-based comparison
            // 1000 milliseconds = 1 second
            if (file.lastModified() - modifiedDate.getTime() < DateUtils.MILLIS_PER_SECOND) {
                return Response.status(Status.NOT_MODIFIED).build();
            }
        }
    }
    // we really need to send the file

    try {
        Date fileDate = new Date(file.lastModified());
        return Response.ok(new FileInputStream(file)).lastModified(fileDate).build();
    } catch (FileNotFoundException e) {
        return Response.status(Status.NOT_FOUND).build();
    }
}

From source file:com.mmone.gpdati.allotment.record.AllotmentRecord.java

public Date getJDateTo() throws ParseException {
    return DateUtils.parseDate(dateTo, "ddMMyyyy");
}

From source file:com.trenako.web.infrastructure.RangeRequestArgumentResolver.java

private Date parseDate(Object since) {
    if (since == null)
        return null;

    try {/*from ww w .j av  a 2 s  .c  om*/
        return DateUtils.parseDate(since.toString(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern());
    } catch (Exception e) {
        return null;
    }
}

From source file:com.github.nlloyd.hornofmongo.util.BSONizer.java

public static Object convertJStoBSON(Object jsObject, boolean isJsObj, String dateFormat) {
    Object bsonObject = null;//from www .  ja  va2s.c o  m
    if (jsObject instanceof NativeArray) {
        NativeArray jsArray = (NativeArray) jsObject;
        List<Object> bsonArray = new ArrayList<Object>(Long.valueOf(jsArray.getLength()).intValue());
        for (Object jsEntry : jsArray) {
            bsonArray.add(convertJStoBSON(jsEntry, isJsObj, dateFormat));
        }
        bsonObject = bsonArray;
    } else if (jsObject instanceof NativeRegExp) {
        Object source = ScriptableObject.getProperty((Scriptable) jsObject, "source");
        String fullRegex = (String) Context.jsToJava(jsObject, String.class);
        String options = fullRegex.substring(fullRegex.lastIndexOf("/") + 1);

        bsonObject = Pattern.compile(source.toString(), Bytes.regexFlags(options));
        ;
    } else if (jsObject instanceof NativeObject) {
        BasicDBObject bson = new BasicDBObject();
        bsonObject = bson;

        NativeObject rawJsObject = (NativeObject) jsObject;
        for (Object key : rawJsObject.keySet()) {
            Object value = extractJSProperty(rawJsObject, key);

            //GC: 17/11/15 allow for UTC $date object
            if (key.equals("$date")) {
                try {
                    bsonObject = DateUtils.parseDate(value.toString(),
                            new String[] { "yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" });
                } catch (java.text.ParseException e) {
                    bson.put(key.toString(), convertJStoBSON(value, isJsObj, dateFormat));
                }
            } else {
                bson.put(key.toString(), convertJStoBSON(value, isJsObj, dateFormat));
            }
        }
    } else if (jsObject instanceof ScriptableMongoObject) {
        bsonObject = convertScriptableMongoToBSON((ScriptableMongoObject) jsObject, isJsObj, dateFormat);
    } else if (jsObject instanceof BaseFunction) {
        BaseFunction funcObject = (BaseFunction) jsObject;
        Object classPrototype = ScriptableObject.getClassPrototype(funcObject, funcObject.getFunctionName());
        if ((classPrototype instanceof MinKey) || (classPrototype instanceof MaxKey)) {
            // this is a special case handler for instances where MinKey or
            // MaxKey are provided without explicit constructor calls
            // index_check3.js does this
            bsonObject = convertScriptableMongoToBSON((ScriptableMongoObject) classPrototype, isJsObj,
                    dateFormat);
        } else {
            // comes from eval calls
            String decompiledCode = (String) MongoRuntime.call(new JSDecompileAction(funcObject));
            bsonObject = new Code(decompiledCode);
        }
    } else if (jsObject instanceof ScriptableObject) {
        // we found a ScriptableObject that isn't any of the concrete
        // ScriptableObjects above...
        String jsClassName = ((ScriptableObject) jsObject).getClassName();
        if ("Date".equals(jsClassName)) {
            Date dt = (Date) Context.jsToJava(jsObject, Date.class);
            bsonObject = dt;
            //GC: 18/11/15 use dateFormat parameter to format date fields
            if (dateFormat != null && dateFormat.length() > 0)
                bsonObject = DateFormatUtils.formatUTC(dt, dateFormat);
        } else {
            Context.throwAsScriptRuntimeEx(
                    new MongoScopeException("bsonizer couldnt convert js class: " + jsClassName));
            bsonObject = jsObject;
        }
    } else if (jsObject instanceof ConsString) {
        bsonObject = jsObject.toString();
    } else if (jsObject instanceof Undefined) {
        bsonObject = jsObject;
    } else if (jsObject instanceof Integer) {
        // this may seem strange, but JavaScript only knows about the number
        // type
        // which means in the official client we need to pass a Double
        // this applies to Long and Integer values
        bsonObject = Double.valueOf((Integer) jsObject);
    } else if (jsObject instanceof Long) {
        bsonObject = Double.valueOf((Long) jsObject);
    } else {
        bsonObject = jsObject;
    }

    return bsonObject;
}