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:fr.paris.lutece.plugins.document.service.docsearch.DocSearchService.java

/**
 * Format the date/*from  w  ww  .  j ava  2 s  .c o  m*/
 * @param date the date
 * @return formatedDate the formated date
 */
private String formatDate(String date) {
    DateFormat dateFormat = new SimpleDateFormat(PATTERN_DATE, Locale.FRENCH);
    dateFormat.setLenient(false);

    Date formatedDate;

    try {
        formatedDate = dateFormat.parse(date.trim());
    } catch (ParseException e) {
        AppLogService.error(e);

        return null;
    }

    return dateFormat.format(formatedDate);
}

From source file:com.jaspersoft.jasperserver.war.themes.ThemeResolverServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // Check if we can find a resource in the current theme
    //String resPath = req.getRequestURI().substring((req.getContextPath() + req.getServletPath()).length());
    String resPath = req.getRequestURI().substring(req.getContextPath().length() + 1);
    ThemeResource themeResource = themeCache.getThemeResource(resPath);
    if (themeResource == null) {
        resp.sendError(404);/*w w  w .j a  va2s  .  com*/
        return;
    }

    // Set contentType
    String filename = resPath;
    if (filename.indexOf("/") >= 0) {
        filename = filename.substring(filename.lastIndexOf("/") + 1);
    }
    String contentType = servletContext.getMimeType(filename);
    if (contentType == null) {
        log.error("Cannot detect a response content type for the file : " + filename);
        resp.sendError(404);
        return;
    }
    resp.setContentType(contentType);

    // Get Last Modified date
    Date lastModified = themeResource.getLastModified();
    // Get rid of ms
    lastModified.setTime(lastModified.getTime() / 1000 * 1000);

    // Set cache controlling HTTP Response Headers
    DateFormat df = getFormat(req.getLocale());
    resp.setHeader("Cache-Control", "max-age=" + expiresInSecs + ", public");
    resp.setHeader("Pragma", "");
    resp.setHeader("Last-Modified", df.format(lastModified));
    resp.setHeader("Expires", df.format(new Date(new Date().getTime() + expiresInSecs * 1000)));

    // Send 304 if resource has not been modified since last time requested
    String ifModSince = req.getHeader("If-Modified-Since");
    try {
        Date modDate = df.parse(ifModSince);
        if (!lastModified.after(modDate)) {
            resp.setStatus(304);
            return;
        }
    } catch (Exception e) {
    }

    // Send the full content
    resp.setContentLength(themeResource.getContent().length);
    ServletOutputStream os = resp.getOutputStream();
    os.write(themeResource.getContent());
    os.flush();
    os.close();
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

private Object doConvertToDate(Map<String, Object> context, Object value, Class toType) {
    Date result = null;//from  w  ww.ja va 2s  . c o m

    if (value instanceof String && value != null && ((String) value).length() > 0) {
        String sa = (String) value;
        Locale locale = getLocale(context);

        DateFormat df = null;
        if (java.sql.Time.class == toType) {
            df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
        } else if (java.sql.Timestamp.class == toType) {
            Date check = null;
            SimpleDateFormat dtfmt = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT,
                    DateFormat.MEDIUM, locale);
            SimpleDateFormat fullfmt = new SimpleDateFormat(dtfmt.toPattern() + MILLISECOND_FORMAT, locale);

            SimpleDateFormat dfmt = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);

            SimpleDateFormat[] fmts = { fullfmt, dtfmt, dfmt };
            for (SimpleDateFormat fmt : fmts) {
                try {
                    check = fmt.parse(sa);
                    df = fmt;
                    if (check != null) {
                        break;
                    }
                } catch (ParseException ignore) {
                }
            }
        } else if (java.util.Date.class == toType) {
            Date check = null;
            DateFormat[] dfs = getDateFormats(locale);
            for (DateFormat df1 : dfs) {
                try {
                    check = df1.parse(sa);
                    df = df1;
                    if (check != null) {
                        break;
                    }
                } catch (ParseException ignore) {
                }
            }
        }
        //final fallback for dates without time
        if (df == null) {
            df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        }
        try {
            df.setLenient(false); // let's use strict parsing (XW-341)
            result = df.parse(sa);
            if (!(Date.class == toType)) {
                try {
                    Constructor constructor = toType.getConstructor(new Class[] { long.class });
                    return constructor.newInstance(new Object[] { Long.valueOf(result.getTime()) });
                } catch (Exception e) {
                    throw new XWorkException(
                            "Couldn't create class " + toType + " using default (long) constructor", e);
                }
            }
        } catch (ParseException e) {
            throw new XWorkException("Could not parse date", e);
        }
    } else if (Date.class.isAssignableFrom(value.getClass())) {
        result = (Date) value;
    }
    return result;
}

From source file:com.salesmanager.central.orders.OrderListAction.java

/**
 * Page entry point//from   ww w. ja  v a 2  s  .  c o m
 * 
 * @return
 * @throws Exception
 */

private String getOrdersList() throws Exception {
    try {

        super.setPageTitle("label.order.orderlist.title");
        this.buildCriteria();

        // override start date & end date with page navigation criteria submission
        DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date sDate = null;
        Date eDate = null;
        try {
            if (super.getServletRequest().getParameter("navstartdate") != null) {
                if (criteria.getSdate() == null) {
                    sDate = myDateFormat.parse(super.getServletRequest().getParameter("navstartdate"));
                }
            }
            if (super.getServletRequest().getParameter("navenddate") != null) {
                if (criteria.getEdate() == null) {
                    eDate = myDateFormat.parse(super.getServletRequest().getParameter("navenddate"));
                }
            }
            criteria.setSdate(sDate);
            criteria.setEdate(eDate);
        } catch (Exception e) {
            log.error(e);
        }

        this.setSize(ordersize);
        super.setPageStartNumber();

        criteria.setQuantity(ordersize);
        criteria.setStartindex(super.getPageStartIndex());

        OrderService oservice = (OrderService) ServiceFactory.getService(ServiceFactory.OrderService);
        SearchOrderResponse response = oservice.searchOrders(criteria);

        orders = response.getOrders();

        super.setListingCount(response.getCount());
        super.setRealCount(response.getOrders().size());
        super.setPageElements();

    } catch (Exception e) {
        log.error(e);
        MessageUtil.addErrorMessage(super.getServletRequest(),
                LabelUtil.getInstance().getText("errors.technical"));
    }

    return SUCCESS;

}

From source file:cz.tyr.android.currencyrates.bank.UniCreditBank.java

@Override
public int downloadData() {
    if (mCurrency == null) {
        mCurrency = getDefaultCurrencyValue();
    }/*from  w ww  .  ja  va  2 s. c  o  m*/

    String dateStr = null;
    String rateStr = null;

    String url = getDataUrl();

    if (DEBUG > 0) {
        Log.d(TAG, "Download data for UCB_CZ");
        Log.d(TAG, " * url = : " + url);
        Log.d(TAG, " * currency = " + mCurrency);
        Log.d(TAG, " * exchange = " + mExchangeType);
        Log.d(TAG, " * direction = " + mExchangeDirection);
    }

    HttpClient sClient = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    InputStream stream = null;

    try {
        stream = sClient.execute(request).getEntity().getContent();
    } catch (IOException e) {
        Log.d(TAG, "Problem downloading the XML data.");
        return 1;
    }

    try {
        if (DEBUG > 1)
            Log.d(TAG, " - Factory start");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document doc = dbf.newDocumentBuilder().parse(stream);
        if (DEBUG > 1)
            Log.d(TAG, " - Factory end");

        if (doc != null && doc.hasChildNodes()) {
            if (DEBUG > 1)
                Log.d(TAG, " - Parse start");

            // find the root element
            for (int i = 0; i < doc.getChildNodes().getLength(); i++) {
                Node root = doc.getChildNodes().item(i);

                if (root.getNodeType() == Node.ELEMENT_NODE || root.getNodeName().equals("exchange_rates")) {
                    NodeList list = doc.getChildNodes().item(i).getChildNodes();

                    // find first node
                    for (int j = 0; j < list.getLength(); j++) {
                        Node n = list.item(j);

                        // check the attributes of this element
                        if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals("exchange_rate")) {
                            boolean go = false;

                            if (DEBUG > 1)
                                Log.d(TAG, " # Got EXCHANGE_RATE element!");

                            for (int k = 0; k < n.getAttributes().getLength(); k++) {
                                Node a = n.getAttributes().item(k);

                                if (a.getNodeName().equals("type") && a.getNodeValue().equals(
                                        "XML_RATE_TYPE_UCB_" + mExchangeDirection + "_" + mExchangeType)) {
                                    if (DEBUG > 1)
                                        Log.d(TAG, " - CORRECT ELEMENT! TAKE THE DATE!");

                                    go = true;
                                } else if (go && a.getNodeName().equals("valid_from")) {
                                    if (DEBUG > 1)
                                        Log.d(TAG, " - GOT DATE! " + a.getNodeValue());

                                    DateFormat formatter = new SimpleDateFormat("HH:mm");
                                    String time = formatter.format(new Date());
                                    formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
                                    Date fdate = (Date) formatter.parse(a.getNodeValue() + " " + time);
                                    formatter = new SimpleDateFormat(
                                            mResources.getString(R.string.date_time_format));

                                    dateStr = formatter.format(fdate);

                                    // stop the loop
                                    break;
                                }
                            }

                            // if it is correct element, go for the rate
                            if (go) {
                                if (DEBUG > 1)
                                    Log.d(TAG, " - Searching for the rate!");

                                NodeList currencies = n.getChildNodes();

                                // check the attributes
                                for (int k = 0; k < currencies.getLength(); k++) {
                                    Node c = currencies.item(k);

                                    if (c.getNodeType() == Node.ELEMENT_NODE
                                            && c.getNodeName().equals("currency")) {
                                        boolean bool = false;
                                        String rateTmp = null;

                                        for (int l = 0; l < c.getAttributes().getLength(); l++) {
                                            Node a = c.getAttributes().item(l);

                                            if (a.getNodeName().equals("name")
                                                    && a.getNodeValue().equals(mCurrency)) {
                                                if (DEBUG > 1)
                                                    Log.d(TAG, " -- Got the Currency!!!");

                                                bool = true;
                                            } else if (a.getNodeName().equals("rate")) {
                                                if (DEBUG > 1)
                                                    Log.d(TAG, " -- Got the RATE!!!" + a.getNodeValue());
                                                rateTmp = a.getNodeValue();
                                            }

                                            if (bool && rateTmp != null) {
                                                rateStr = rateTmp;

                                                if (DEBUG > 1)
                                                    Log.d(TAG, " -- Got the Currency VALUE: " + rateStr);

                                                // stop the loop
                                                break;
                                            }
                                        }
                                    }

                                    // stop the loop
                                    if (rateStr != null) {
                                        break;
                                    }
                                }
                            }
                        }

                        // stop the loop
                        if (rateStr != null) {
                            break;
                        }
                    }
                }

                // stop the loop
                if (rateStr != null) {
                    break;
                }
            }

            if (DEBUG > 1)
                Log.d(TAG, " - Parse end");
        }
    } catch (Exception e) {
        e.printStackTrace();
        return 1;
    }

    // Check the values
    if (dateStr == null || rateStr == null) {
        Log.d(TAG, " # One of the values is null!");
        return 1;
    }

    setCurrencyDate(dateStr);
    setCurrencyRate(Float.parseFloat(rateStr));

    return 0;
}

From source file:org.apereo.openlrs.storage.aws.elasticsearch.XApiOnlyAwsElasticsearchTierTwoStorage.java

@Override
public Page<OpenLRSEntity> findWithFilters(Map<String, String> filters, Pageable pageable) {
    int offset = (pageable == null) ? 0 : pageable.getOffset();
    int pagesize = (pageable == null) ? 100 : pageable.getPageSize();

    String actor = filters.get(StatementUtils.ACTOR_FILTER);
    String activity = filters.get(StatementUtils.ACTIVITY_FILTER);
    String since = filters.get(StatementUtils.SINCE_FILTER);
    String until = filters.get(StatementUtils.UNTIL_FILTER);
    int limit = getLimit(filters.get(StatementUtils.LIMIT_FILTER));

    FilteredQueryBuilder filterQueryBuilder = null;
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

    if (StringUtils.isNotBlank(actor)) {
        String mailbox = String.format("mailto:%s@adlnet.gov", actor);
        filterQueryBuilder = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
                FilterBuilders.nestedFilter("actor", FilterBuilders.termFilter("actor.mbox", mailbox)));
    }/*from  w w  w.  j a  va2  s .  c  o  m*/

    if (StringUtils.isNotBlank(activity)) {
        if (filterQueryBuilder != null) {
            filterQueryBuilder = QueryBuilders.filteredQuery(filterQueryBuilder,
                    FilterBuilders.nestedFilter("object", FilterBuilders.termFilter("object.id", activity)));
        } else {
            filterQueryBuilder = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
                    FilterBuilders.nestedFilter("object", FilterBuilders.termFilter("object.id", activity)));
        }
    }

    if (StringUtils.isNotBlank(since) || StringUtils.isNotBlank(until)) {
        FilterBuilder rangeFilter = null;
        if (StringUtils.isNotBlank(since) && StringUtils.isNotBlank(until)) {
            rangeFilter = FilterBuilders.rangeFilter("stored").from(since).to(until);
        } else {
            if (StringUtils.isNotBlank(since)) {
                rangeFilter = FilterBuilders.rangeFilter("stored").from(since).to("now");
            }

            if (StringUtils.isNotBlank(until)) {
                try {

                    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                    TimeZone tz = TimeZone.getTimeZone("UTC");
                    formatter.setTimeZone(tz);
                    Date date = (Date) formatter.parse(until);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.YEAR, -1);
                    rangeFilter = FilterBuilders.rangeFilter("stored")
                            .from(formatter.format(calendar.getTime())).to(until);
                } catch (ParseException e) {
                    log.error(e.getMessage(), e);
                    return null;
                }
            }
        }

        if (filterQueryBuilder != null) {
            filterQueryBuilder = QueryBuilders.filteredQuery(filterQueryBuilder, rangeFilter);
        } else {
            filterQueryBuilder = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), rangeFilter);
        }
    }

    if (limit > 0) {
        pagesize = limit;
    }

    searchSourceBuilder.query(filterQueryBuilder).sort("stored", SortOrder.DESC);
    Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(STATEMENT_INDEX)
            .addType(STATEMENT_TYPE).setParameter("from", offset).setParameter(Parameters.SIZE, pagesize)
            .build();

    try {
        SearchResult result = jestClient.execute(search);
        //TODO remove deprecated.
        Iterable<Statement> statements = result.getSourceAsObjectList(Statement.class);
        return createPage(statements);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        e.printStackTrace();
    }
    return null;
}