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:com.xpfriend.fixture.cast.temp.ObjectValidatorBase.java

private Date parse(DateFormat dateFormat, String actual) {
    try {/*from w w  w .j  a v  a  2 s  . c o m*/
        return dateFormat.parse(actual);
    } catch (ParseException e) {
        ExceptionHandler.ignore(e);
    }
    return null;
}

From source file:info.rmapproject.core.rmapservice.impl.openrdf.ORMapResourceMgrTest.java

@SuppressWarnings("unused")
@Test//from  w  w w.  java2  s. c o  m
public void testGetRelatedTriples() {

    try {

        //create disco            
        InputStream stream = new ByteArrayInputStream(discoRDF.getBytes(StandardCharsets.UTF_8));
        RioRDFHandler handler = new RioRDFHandler();
        Set<Statement> stmts = handler.convertRDFToStmtList(stream, RDFType.RDFXML, "");
        ORMapDiSCO disco = new ORMapDiSCO(stmts);
        requestAgent.setAgentKeyId(new java.net.URI("rmap:testkey"));
        ORMapEvent event = discomgr.createDiSCO(disco, requestAgent, triplestore);

        //get related triples         
        IRI iri = ORAdapter.getValueFactory()
                .createIRI("http://ieeexplore.ieee.org/ielx7/6287639/6705689/6842585/html/mm/6842585-mm.zip");

        Set<URI> sysAgents = new HashSet<URI>();
        sysAgents.add(agentId);

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dateFrom = dateFormat.parse("2014-1-1");
        Date dateTo = dateFormat.parse("2050-1-1");

        RMapSearchParams params = new RMapSearchParams();
        params.setDateRange(dateFrom, dateTo);
        params.setSystemAgents(sysAgents);

        Set<Statement> matchingStmts = resourcemgr.getRelatedTriples(iri, params, triplestore);

        //should return 3 results - agent creator stmt, agent isFormatOf stmt, and disco creator stmt.
        assertTrue(matchingStmts.size() == 5);

        Iterator<Statement> iter = matchingStmts.iterator();
        Statement stmt = iter.next();
        assertTrue(stmt.getSubject().toString().equals(iri.toString())
                || stmt.getObject().toString().equals(iri.toString()));
        stmt = iter.next();
        assertTrue(stmt.getSubject().toString().equals(iri.toString())
                || stmt.getObject().toString().equals(iri.toString()));
        stmt = iter.next();
        assertTrue(stmt.getSubject().toString().equals(iri.toString())
                || stmt.getObject().toString().equals(iri.toString()));
        stmt = iter.next();
        assertTrue(stmt.getSubject().toString().equals(iri.toString())
                || stmt.getObject().toString().equals(iri.toString()));
        rmapService.deleteDiSCO(disco.getId().getIri(), requestAgent);
    } catch (Exception e) {
        e.printStackTrace();
        fail();
    } finally {
        rmapService.closeConnection();
    }

}

From source file:SportsBroadcastsSpeechlet.java

/**
 * Function to accept an intent containing a Day slot (date object) and return the Calendar
 * representation of that slot value. If the user provides a date, then use that, otherwise use
 * today. The date is in server time, not in the user's time zone. So "today" for the user may
 * actually be tomorrow./* ww w . j a v a2 s  .  c o  m*/
 * 
 * @param intent
 *            the intent object containing the day slot
 * @return the Calendar representation of that date
 */
private Calendar getCalendar(Intent intent) {
    Slot daySlot = intent.getSlot(SLOT_DAY);
    Date date;
    Calendar calendar = Calendar.getInstance();
    if (daySlot != null && daySlot.getValue() != null) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-d");
        try {
            date = dateFormat.parse(daySlot.getValue());
        } catch (ParseException e) {
            date = new Date();
        }
    } else {
        date = new Date();
    }
    calendar.setTime(date);
    return calendar;
}

From source file:com.redhat.rcm.maven.plugin.buildmetadata.io.SdocBuilder.java

private String formatDate(final String datePropertyKey) {
    final String originalDateString = buildMetaDataProperties.getProperty(datePropertyKey);
    if (StringUtils.isNotBlank(originalDateString)) {
        try {/*  w ww  .  j a v a  2s  .  c om*/
            final String originalPattern = buildMetaDataProperties
                    .getProperty(Constant.PROP_NAME_BUILD_DATE_PATTERN);
            final DateFormat format = new SimpleDateFormat(originalPattern, Locale.ENGLISH);
            final Date date = format.parse(originalDateString);
            final String dateString = DateFormatUtils.ISO_DATETIME_FORMAT.format(date);
            return dateString;
        } catch (final ParseException e) {
            if (getLog().isDebugEnabled()) {
                getLog().debug("Cannot parse date of property '" + datePropertyKey + "': " + originalDateString
                        + ". Skipping...");
            }
            return null;
        }
    }
    return null;
}

From source file:view.App.java

private XYDataset createDataset(SpreadObject obj) throws ParseException {
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    TimeSeries series = new TimeSeries(
            obj.getBaseStock().getTicker() + " : " + obj.getSecondStock().getTicker());

    List<SpreadData> data = obj.getData();
    for (SpreadData item : data) {
        String date = item.getDate();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date dateRes = df.parse(date);
        Day d = new Day(dateRes);
        RegularTimePeriod regTime = d.next();
        series.add(regTime, item.getSpreadValue().doubleValue());
    }/*from  w  w  w  . j  a  va 2s  .c o m*/

    dataset.addSeries(series);
    return dataset;
}

From source file:jef.tools.DateUtils.java

/**
 * ? ??//  w w  w  . j  av  a  2 s .c o m
 * 
 * @return defaultValue ?defaultValue
 * @throws?ParseException
 */
public static Date parse(String s, DateFormat format, Date defaultValue) {
    if (StringUtils.isBlank(s))
        return defaultValue;
    try {
        return format.parse(s);
    } catch (ParseException e) {
        LogUtil.exception(e);
        return defaultValue;
    }
}

From source file:eu.serco.dhus.plugin.olcil1eo.OlciL1EoPlugin.java

public List<Request> retrieveRequests(String productType, String startTime, String stopTime) {

    List<Request> requests = new ArrayList<Request>();
    Date startDate;/*from w  w  w. j  av  a 2s.  co  m*/
    Date stopDate;
    long startDateInMillis;
    long stopDateInMillis;

    DateFormat inputFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
    //2016-07-16T00:00:00.000Z
    DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    try {
        startDate = inputFormat.parse(startTime);
        stopDate = inputFormat.parse(stopTime);
        startDateInMillis = startDate.getTime();
        stopDateInMillis = stopDate.getTime();

        if (taskTables.get(productType) != null) {

            for (Task task : taskTables.get(productType).getTasks()) {
                logger.info("task.getName()" + task.getName());
                logger.info("task.getInputs()" + task.getInputs());
                Request request;
                for (Input in : task.getInputs()) {
                    request = new Request();
                    request.setMandatory(in.getMandatory());
                    // TODO: Manage Mode when getting requests to perform
                    request.setMode(in.getMode());
                    List<InputRequest> inputRequests = new ArrayList<InputRequest>();
                    for (Alternative alternative : in.getAlternatives()) {
                        InputRequest inReq = new InputRequest();
                        String url = propFiles.get(productType).getProperty(alternative.getRetrievalMode());
                        url = url.replace("<filename>", alternative.getFileType());
                        long startValidity;
                        long stopValidity;
                        if (alternative.getT0() > 0) {
                            startValidity = startDateInMillis - (long) Math.ceil(alternative.getT0() * 1000);
                        } else {
                            startValidity = startDateInMillis;
                        }
                        if (alternative.getT1() > 0) {
                            stopValidity = stopDateInMillis + (long) Math.ceil(alternative.getT1() * 1000);
                        } else {
                            stopValidity = stopDateInMillis;
                        }
                        Date startValidityDate = new Date(startValidity);
                        String beginPosition = outputFormat.format(startValidityDate) + ".000Z";
                        Date stopValidityDate = new Date(stopValidity);
                        String endPosition = outputFormat.format(stopValidityDate) + ".000Z";
                        url = url.replace("<beginPosition>", beginPosition);
                        url = url.replace("<endPosition>", endPosition);
                        url = externalDHuSUrl + url;
                        inReq.setUrl(url);
                        inReq.setType(alternative.getFileType());
                        inputRequests.add(inReq);
                        logger.info("----------");
                        logger.info("Request to perform: " + externalDHuSUrl + url);
                    }
                    logger.info("How many urls???: " + inputRequests.size());
                    request.setRequests(inputRequests);
                    requests.add(request);
                }
            }
        }

    } catch (ParseException pe) {

        pe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    logger.info("Request size is:    ????? **** " + requests.size());
    return requests;
}

From source file:eu.serco.dhus.plugin.synergy1eo.Synergy1EoPlugin.java

public List<Request> retrieveRequests(String productType, String startTime, String stopTime) {

    List<Request> requests = new ArrayList<Request>();
    Date startDate;/*from  w w w.  j  a va  2 s.c o m*/
    Date stopDate;
    long startDateInMillis;
    long stopDateInMillis;

    DateFormat inputFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
    //2016-07-16T00:00:00.000Z
    DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    try {
        startDate = inputFormat.parse(startTime);
        stopDate = inputFormat.parse(stopTime);
        startDateInMillis = startDate.getTime();
        stopDateInMillis = stopDate.getTime();

        if (taskTables.get(productType) != null) {

            for (Task task : taskTables.get(productType).getTasks()) {
                logger.info("task.getName()" + task.getName());
                logger.info("task.getInputs()" + task.getInputs());
                Request request;
                for (Input in : task.getInputs()) {
                    request = new Request();
                    request.setMandatory(in.getMandatory());
                    // TODO: Manage Mode when getting requests to perform
                    request.setMode(in.getMode());
                    List<InputRequest> inputRequests = new ArrayList<InputRequest>();
                    for (Alternative alternative : in.getAlternatives()) {
                        InputRequest inReq = new InputRequest();
                        String url = propFiles.get(productType)
                                .getProperty(alternative.getRetrievalMode().trim());
                        url = url.replace("<filename>", alternative.getFileType());
                        long startValidity;
                        long stopValidity;
                        if (alternative.getT0() > 0) {
                            startValidity = startDateInMillis - (long) Math.ceil(alternative.getT0() * 1000);
                        } else {
                            startValidity = startDateInMillis;
                        }
                        if (alternative.getT1() > 0) {
                            stopValidity = stopDateInMillis + (long) Math.ceil(alternative.getT1() * 1000);
                        } else {
                            stopValidity = stopDateInMillis;
                        }
                        Date startValidityDate = new Date(startValidity);
                        String beginPosition = outputFormat.format(startValidityDate) + ".000Z";
                        Date stopValidityDate = new Date(stopValidity);
                        String endPosition = outputFormat.format(stopValidityDate) + ".000Z";
                        url = url.replace("<beginPosition>", beginPosition);
                        url = url.replace("<endPosition>", endPosition);
                        url = externalDHuSUrl + url;
                        inReq.setUrl(url);
                        inReq.setType(alternative.getFileType());
                        inputRequests.add(inReq);
                        logger.info("----------");
                        logger.info("Request to perform: " + externalDHuSUrl + url);
                    }
                    logger.info("How many urls???: " + inputRequests.size());
                    request.setRequests(inputRequests);
                    requests.add(request);
                }
            }
        }

    } catch (ParseException pe) {

        pe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    logger.info("Request size is:    ????? **** " + requests.size());
    return requests;
}

From source file:com.salesmanager.central.invoice.InvoiceListAction.java

public String displayInvoiceList() {

    // for page navigation
    String sstartindex = super.getServletRequest().getParameter("startindex");

    try {/*from  w  w  w .j  a va 2  s .  co  m*/

        DateUtil dh = new DateUtil();
        dh.processPostedDates(super.getServletRequest());

        if (criteria == null) {
            criteria = new SearchOrdersCriteria();
        }

        criteria.setSdate(dh.getStartDate());
        criteria.setEdate(dh.getEndDate());

        if (dh.getStartDate() != null) {
            super.getServletRequest().setAttribute("sdate", DateUtil.formatDate(dh.getStartDate()));
        }
        if (dh.getEndDate() != null) {
            super.getServletRequest().setAttribute("edate", DateUtil.formatDate(dh.getEndDate()));
        }

        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);
        }

        if (!StringUtils.isBlank(this.getInvoiceId())) {

            try {
                long invId = Long.parseLong(this.getInvoiceId());
                criteria.setOrderId(invId);
            } catch (Exception e) {
                log.error("Cannot parse invoiceId " + this.getInvoiceId());
            }

        }

        int startindex = 0;
        if (sstartindex != null) {
            try {
                startindex = Integer.parseInt(sstartindex);
            } catch (Exception e) {
                log.error("Did not received the index for page iterator, will reset to 0");
            }
        }

        Context ctx = (Context) super.getServletRequest().getSession().getAttribute(ProfileConstants.context);
        Integer merchantid = ctx.getMerchantid();

        this.setSize(invoicesize);
        this.getCriteria().setQuantity(invoicesize);
        this.getCriteria().setMerchantId(ctx.getMerchantid());
        this.getCriteria().setStartindex(this.getPageStartIndex());
        OrderService oservice = (OrderService) ServiceFactory.getService(ServiceFactory.OrderService);

        super.setPageStartNumber();
        SearchOrderResponse resp = oservice.searchInvoices(this.getCriteria());

        if (resp != null) {
            invoices = resp.getOrders();
            super.setListingCount(resp.getCount());
            super.setRealCount(resp.getOrders().size());
            super.setPageElements();
        }

        LocaleUtil.setLocaleToEntityCollection(invoices, super.getLocale());

    } catch (Exception e) {
        log.error(e);
        super.setTechnicalMessage();
    }

    return SUCCESS;

}

From source file:net.sf.logsaw.dialect.websphere.WebsphereDialect.java

private void extractField(LogEntry entry, int group, String val, DateFormat dateFormat) throws CoreException {
    switch (group) {
    case 1:/*from ww  w  .  ja  v  a2s  .c  o  m*/
        try {
            // Timestamp
            // This is a bit complicated because WebSphere will write it out in some localized format
            entry.put(WebsphereFieldProvider.FIELD_TIMESTAMP, dateFormat.parse(val.trim()));
        } catch (ParseException e) {
            throw new CoreException(new Status(IStatus.ERROR, WebsphereDialectPlugin.PLUGIN_ID,
                    NLS.bind(Messages.WebsphereDialect_error_failedToParseTimestamp, val.trim())));
        }
        break;
    case 2:
        // Thread ID
        entry.put(WebsphereFieldProvider.FIELD_THREAD_ID, val.trim());
        break;
    case 3:
        // Short Name
        entry.put(WebsphereFieldProvider.FIELD_SHORT_NAME, val.trim());
        break;
    case 4:
        // Event Type
        Level lvl = WebsphereFieldProvider.FIELD_EVENT_TYPE.getLevelProvider().findLevel(val.trim());
        if (ILogLevelProvider.ID_LEVEL_UNKNOWN == lvl.getValue()) {
            throw new CoreException(new Status(IStatus.WARNING, WebsphereDialectPlugin.PLUGIN_ID,
                    NLS.bind(Messages.WebsphereDialect_warning_unknownEventType, val.trim())));
        }
        entry.put(WebsphereFieldProvider.FIELD_EVENT_TYPE, lvl);
        break;
    case 5:
        // Class Name (optional)
        entry.put(WebsphereFieldProvider.FIELD_CLASS_NAME, val.trim());
        break;
    case 6:
        // Method Name (optional)
        entry.put(WebsphereFieldProvider.FIELD_METHOD_NAME, val.trim());
        break;
    case 7:
        // Message
        entry.put(WebsphereFieldProvider.FIELD_MESSAGE, val.trim());
        break;
    default:
        throw new CoreException(new Status(IStatus.ERROR, WebsphereDialectPlugin.PLUGIN_ID,
                NLS.bind(Messages.WebsphereDialect_error_regexGroupNotSupported, group)));
    }
}