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.haulmont.chile.core.datatypes.impl.DateTimeDatatype.java

@Nullable
@Override/*from   w ww .j av a  2 s .  c  om*/
public Date parse(@Nullable String value, Locale locale, TimeZone timeZone) throws ParseException {
    if (StringUtils.isBlank(value)) {
        return null;
    }

    FormatStrings formatStrings = AppBeans.get(FormatStringsRegistry.class).getFormatStrings(locale);
    if (formatStrings == null) {
        return parse(value);
    }

    DateFormat format = new SimpleDateFormat(formatStrings.getDateTimeFormat());

    if (timeZone != null) {
        format.setTimeZone(timeZone);
    }

    return format.parse(value.trim());
}

From source file:crawler.AScraper.java

@Transformer(inputChannel = "channel3", outputChannel = "channel4")
public Artwork convert(Element payload) throws ParseException, MalformedURLException {
    Matcher m = patter.matcher(payload.text());
    if (m.find()) {
        String year = m.group("year");
        String month = m.group("month");
        String day = m.group("day");
        int id = Integer.parseInt(m.group("id"));
        String model = m.group("model").split("[\\s\\[\\]]")[0];
        URL link = new URL(payload.attr("href"));
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        Date date = format.parse(String.format("%s-%s-%s", year, month, day));
        String thread_title = payload.text();
        return new Artwork(thread_title, id, -1, -1, null, link, null, model, date);
    } else {//from  w w  w .ja va 2s  .  co m
        LOG.error(payload.text());
        return null;
    }

}

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

/**
 * @throws Exception/*  ww  w  .ja v a2 s  .  c  o m*/
 */
@Test
public void saveFileEntryAnswer() throws Exception {
    DateFormat dirNameDateFormat = new SimpleDateFormat("yyyy_MM");
    DateFormat fileNameDateFormat = new SimpleDateFormat("hh_mm_ss");

    Disease psoriasis = diseaseService.findByCode(DiseaseCodes.PSORIASIS_CODE);
    List<Haq> haqs = haqService.findByDisease(psoriasis.getId());
    Haq haq1 = haqs.get(0);
    assertEquals(1, haq1.getQuestions().size());

    Question question = haq1.getQuestions().get(0);
    Answer noAnswer = question.getQuestionType().getAnswers().get(0);
    assertFalse(noAnswer.isActive());
    Answer fileAnswer = question.getQuestionType().getAnswers().get(1);
    assertTrue(fileAnswer.isActive());

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

    DateFormat dateFormat = DateFormat.getDateInstance();
    Date logDate = dateFormat.parse("1.1.2011");

    File tmpFile = File.createTempFile("projecth", ".test");

    configurationService.setImagesRootDirectoryPath(tmpFile.getParent());

    int count = patientQuestionAnswerService.findAll().size();

    patientQuestionAnswerService.saveAnswer(patient.getId(), question.getId(), noAnswer.getId(),
            tmpFile.getPath(), logDate);
    List<PatientQuestionAnswer> answers = patientQuestionAnswerService.findAll();
    assertEquals(count + 1, answers.size());
    assertEquals(null, answers.get(answers.size() - 1).getCustomAnswer());

    /////////////// POSITIVE
    patientQuestionAnswerService.saveAnswer(patient.getId(), question.getId(), fileAnswer.getId(),
            tmpFile.getPath(), logDate);

    answers = patientQuestionAnswerService.findAll();
    assertEquals(count + 2, answers.size());
    assertEquals(
            patient.getId() + File.separator + psoriasis.getId() + File.separator
                    + dirNameDateFormat.format(new Date()) + File.separator
                    + fileNameDateFormat.format(new Date()) + ".test",
            answers.get(answers.size() - 1).getCustomAnswer());

}

From source file:datawarehouse.CSVLoader.java

/**
 * Parse CSV file using OpenCSV library and load in given database table.
 *
 * @param csvFile Input CSV file/* www .j  a va 2  s . c  om*/
 * @param tableName Database table name to import data
 * @param truncateBeforeLoad Truncate the table before inserting new
 * records.
 * @throws Exception
 */
public void loadCSV(String csvFile, String tableName, boolean truncateBeforeLoad) throws Exception {

    CSVReader csvReader = null;
    if (null == this.connection) {
        throw new Exception("Not a valid connection.");
    }
    try {

        csvReader = new CSVReader(new FileReader(csvFile), this.seprator);

    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Error occured while executing file. " + e.getMessage());
    }

    String[] headerRow = csvReader.readNext();

    if (null == headerRow) {
        throw new FileNotFoundException(
                "No columns defined in given CSV file." + "Please check the CSV file format.");
    }

    String questionmarks = StringUtils.repeat("?,", headerRow.length);
    questionmarks = (String) questionmarks.subSequence(0, questionmarks.length() - 1);

    String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
    query = query.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ","));
    query = query.replaceFirst(VALUES_REGEX, questionmarks);

    System.out.println("Query: " + query);

    String[] nextLine;
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = this.connection;
        con.setAutoCommit(false);
        ps = con.prepareStatement(query);

        if (truncateBeforeLoad) {
            //delete data from table before loading csv
            con.createStatement().execute("DELETE FROM " + tableName);
        }

        final int batchSize = 1000;
        int count = 0;
        while ((nextLine = csvReader.readNext()) != null) {
            if (null != nextLine) {
                int index = 1;
                for (String string : nextLine) {
                    //System.out.print(string + ": ");
                    try {
                        DateFormat format = new SimpleDateFormat("dd.mm.yyyy");
                        Date date = format.parse(string);
                        ps.setDate(index++, new java.sql.Date(date.getTime()));
                        //System.out.println("date");
                    } catch (ParseException | SQLException e) {
                        try {
                            Double income = parseDouble(string.replace(",", "."));
                            ps.setDouble(index++, income);
                            //System.out.println("double");
                        } catch (NumberFormatException | SQLException err) {
                            ps.setString(index++, string);
                            //System.out.println("string");
                        }
                    }
                }
                ps.addBatch();
            }
            if (++count % batchSize == 0) {
                ps.executeBatch();
            }
        }
        ps.executeBatch(); // insert remaining records
        con.commit();
    } catch (Exception e) {
        con.rollback();
        e.printStackTrace();
        throw new Exception("Error occured while loading data from file to database." + e.getMessage());
    } finally {
        if (null != ps) {
            ps.close();
        }
        if (null != con) {
            con.close();
        }

        csvReader.close();
    }
}

From source file:com.google.livingstories.server.dataservices.entities.BaseContentEntity.java

public static BaseContentEntity fromJSON(JSONObject json) {
    DateFormat dateFormatter = SimpleDateFormat.getInstance();

    try {/*from w  ww. ja v  a2 s  . c o m*/
        ContentItemType contentItemType = ContentItemType.valueOf(json.getString("contentItemType"));
        Long livingStoryId = json.has("livingStoryId") ? json.getLong("livingStoryId") : null;
        BaseContentEntity entity = new BaseContentEntity(dateFormatter.parse(json.getString("timestamp")),
                contentItemType, json.getString("content"), Importance.valueOf(json.getString("importance")),
                livingStoryId);

        entity.setPublishState(PublishState.valueOf(json.getString("publishState")));

        Set<Long> contributorIds = new HashSet<Long>();
        JSONArray contributorIdsJSON = json.getJSONArray("contributorIds");
        for (int i = 0; i < contributorIdsJSON.length(); i++) {
            contributorIds.add(contributorIdsJSON.getLong(i));
        }
        entity.setContributorIds(contributorIds);

        Set<Long> linkedContentEntityIds = new HashSet<Long>();
        JSONArray linkedContentEntityIdsJSON = json.getJSONArray("linkedContentEntityIds");
        for (int i = 0; i < linkedContentEntityIdsJSON.length(); i++) {
            linkedContentEntityIds.add(linkedContentEntityIdsJSON.getLong(i));
        }
        entity.setLinkedContentEntityIds(linkedContentEntityIds);

        Set<Long> themeIds = new HashSet<Long>();
        JSONArray themeIdsJSON = json.getJSONArray("themeIds");
        for (int i = 0; i < themeIdsJSON.length(); i++) {
            themeIds.add(themeIdsJSON.getLong(i));
        }
        entity.setThemeIds(themeIds);

        entity.setLocation(LocationEntity.fromJSON(json.getJSONObject("location")));

        if (json.has("sourceDescription")) {
            entity.setSourceDescription(json.getString("sourceDescription"));
        }
        if (json.has("sourceContentEntityId")) {
            entity.setSourceContentEntityId(json.getLong("sourceContentEntityId"));
        }

        // Optional properties depending on contentItemType
        switch (contentItemType) {
        case EVENT:
            if (json.has("startDate")) {
                entity.setEventStartDate(dateFormatter.parse(json.getString("startDate")));
            }
            if (json.has("endDate")) {
                entity.setEventEndDate(dateFormatter.parse(json.getString("endDate")));
            }
            entity.setEventUpdate(json.getString("eventUpdate"));
            entity.setEventSummary(json.getString("eventSummary"));
            break;
        case PLAYER:
            if (livingStoryId == null) {
                entity.setName(json.getString("name"));
                entity.setPlayerType(PlayerType.valueOf(json.getString("playerType")));
                if (json.has("aliases")) {
                    List<String> aliases = new ArrayList<String>();
                    JSONArray aliasesJSON = json.getJSONArray("aliases");
                    for (int i = 0; i < aliasesJSON.length(); i++) {
                        aliases.add(aliasesJSON.getString(i));
                    }
                    entity.setAliases(aliases);
                }
                if (json.has("photoContentEntityId")) {
                    entity.setPhotoContentEntityId(json.getLong("photoContentEntityId"));
                }
            } else {
                entity.setParentPlayerContentEntityId(json.getLong("parentPlayerContentEntityId"));
            }
            break;
        case ASSET:
            entity.setAssetType(AssetType.valueOf(json.getString("assetType")));
            entity.setCaption(json.getString("caption"));
            entity.setPreviewUrl(json.getString("previewUrl"));
            break;
        case NARRATIVE:
            entity.setHeadline(json.getString("headline"));
            entity.setNarrativeType(NarrativeType.valueOf(json.getString("narrativeType")));
            // To convert exports that may have been done before the isStandalone field was
            // introduced, set the value to 'false' if the field is not present
            entity.setIsStandalone(json.has("isStandalone") ? json.getBoolean("isStandalone") : false);
            if (json.has("narrativeDate")) {
                entity.setNarrativeDate(dateFormatter.parse(json.getString("narrativeDate")));
            }
            if (json.has("narrativeSummary")) {
                entity.setNarrativeSummary(json.getString("narrativeSummary"));
            }
            break;
        case BACKGROUND:
            if (json.has("name")) {
                entity.setName(json.getString("name"));
            }
            break;
        }

        return entity;
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    } catch (ParseException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:net.java.dev.weblets.impl.faces.WebletsPhaseListener.java

protected void doBeforePhase(PhaseEvent event) {
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext external = context.getExternalContext();
    // test stuff remove me once verified
    /*/*from w  w  w . j av a  2  s  . co  m*/
       * req = utils.getRequestFromPath(external.getRequest(), "/weblets-demo/faces/weblets/demo$1.0/welcome.js");
       *
       * ServletContext ctx = (ServletContext) external.getContext(); String mime = ctx.getMimeType("/faces/weblets/demo$1.0/welcome.js");
       *
       * InputStream strm = utils.getResourceAsStream(req, mime); BufferedReader istrm = new BufferedReader(new InputStreamReader(strm)); try { String line =
       * ""; while ((line = istrm.readLine() ) != null) { System.out.println(line); } istrm.close();
       *
       * } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. }
       *
       *
       * req = utils.getRequestFromPath(external.getRequest(), "/faces/weblets/demo$1.0/welcome.js"); utils.getResourceAsStream(req, mime);
       *
       * req = utils.getRequestFromPath(external.getRequest(), "http://localhost:8080/weblets-demo/faces/weblets/demo$1.0/welcome.js");
       * utils.getResourceAsStream(req, mime);
       *
       * req = utils.getRequestFromPath(external.getRequest(), "/xxx/aa/demo$1.0/welcome.js"); utils.getResourceAsStream(req, mime);
       *
       *
       * req = utils.getRequestFromPath(external.getRequest(), "/xxx/aa/demo$1.0/booga.js"); Object strobj = utils.getResourceAsStream(req, mime);
       */
    WebletContainerImpl container = (WebletContainerImpl) WebletContainer.getInstance();
    String pathInfo = external.getRequestServletPath();
    if (pathInfo != null && external.getRequestPathInfo() != null)
        pathInfo += external.getRequestPathInfo();
    if (pathInfo == null && event.getPhaseId() == PhaseId.RESTORE_VIEW) {
        // we are in a portlet environment here, since we do not get an external path info
        // we skip this phase and renter after the restore view
        event.getFacesContext().getExternalContext().getRequestMap().put(WEBLETS_PHASE_LISTENER_ENTERED,
                Boolean.FALSE);
        return;
    }
    // special portlet treatment here
    // we move to later phases here to the apply request values
    // to become portlet compatible, unfortunately
    // we lose a little bit of performance then
    // but the determination of the pathInfo over
    // the view id is more neutral than over
    // the request servlet which is rundered null
    // in some portlet environments
    if (pathInfo == null)
        pathInfo = context.getViewRoot().getViewId();
    Matcher matcher = null;
    try {
        matcher = container.getPattern().matcher(pathInfo);
    } catch (NullPointerException ex) {
        Log log = LogFactory.getLog(this.getClass());
        log.error(
                "An error has occurred no pattern or matcher has been detected, this is probably a sign that the weblets context listener has not been started. please add following lines to your web.xml \n"
                        + " <listener>\n"
                        + "       <listener-class>net.java.dev.weblets.WebletsContextListener</listener-class>\n"
                        + " </listener>");
        log.error("Details of the original Error:" + ex.toString());
        return;
    }
    if (matcher.matches()) {
        Map requestHeaders = external.getRequestHeaderMap();
        String contextPath = external.getRequestContextPath();
        String requestURI = matcher.group(1);
        String ifModifiedHeader = (String) requestHeaders.get("If-Modified-Since");
        long ifModifiedSince = -1L;
        if (ifModifiedHeader != null) {
            try {
                DateFormat rfc1123 = new HttpDateFormat();
                Date parsed = rfc1123.parse(ifModifiedHeader);
                ifModifiedSince = parsed.getTime();
            } catch (ParseException e) {
                throw new FacesException(e);
            }
        }
        try {
            String[] parsed = container.parseWebletRequest(contextPath, requestURI, ifModifiedSince);
            if (parsed != null) {
                ServletContext servletContext = (ServletContext) external.getContext();
                ServletRequest httpRequest = (ServletRequest) external.getRequest();
                ServletResponse httpResponse = (ServletResponse) external.getResponse();
                String webletName = parsed[0];
                String webletPath = parsed[1];
                String webletPathInfo = parsed[2];
                WebletRequest webRequest = new WebletRequestImpl(webletName, webletPath, contextPath,
                        webletPathInfo, ifModifiedSince, httpRequest);
                String contentName = webRequest.getPathInfo();
                String contentTypeDefault = servletContext.getMimeType(contentName);
                WebletResponse webResponse = new WebletResponseImpl(contentTypeDefault, httpResponse);
                container.service(webRequest, webResponse);
                context.responseComplete();
            }
        } catch (IOException e) {
            throw new FacesException(e);
        }
    }
}

From source file:com.haulmont.chile.core.datatypes.impl.TimeDatatype.java

@Override
public Date parse(String value) throws ParseException {
    if (StringUtils.isBlank(value)) {
        return null;
    }/*from   ww  w .  j  a v a 2s  . c  o  m*/
    DateFormat format;
    if (formatPattern != null) {
        format = new SimpleDateFormat(formatPattern);
    } else {
        format = DateFormat.getTimeInstance();
    }

    return format.parse(value.trim());
}

From source file:monitoring.tools.AppTweak.java

protected void apiCall() throws MalformedURLException, IOException, JSONException, ParseException {

    String timeStamp = new Timestamp((new Date()).getTime()).toString();

    JSONObject data = urlConnection();//from w w  w.ja v a 2 s  . c om

    List<MonitoringData> dataList = new ArrayList<>();
    JSONArray reviews = data.getJSONArray("content");
    for (int i = 0; i < reviews.length(); ++i) {

        JSONObject obj = reviews.getJSONObject(i);

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss z");
        Date date = format.parse(obj.getString("date"));

        if (date.compareTo(stamp) > 0) {

            Iterator<?> keys = obj.keys();
            MonitoringData review = new MonitoringData();

            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("id"))
                    review.setReviewID(obj.getString("id"));
                else if (key.equals("author"))
                    review.setAuthorName(obj.getJSONObject("author").getString("name"));
                else if (key.equals("title"))
                    review.setReviewTitle(obj.getString("title"));
                else if (key.equals("body"))
                    review.setReviewText(obj.getString("body"));
                else if (key.equals("date"))
                    review.setTimeStamp(obj.getString("date"));
                else if (key.equals("rating"))
                    review.setStarRating(String.valueOf(obj.getInt("rating")));
                else if (key.equals("version"))
                    review.setAppVersion(obj.getString("version"));
            }

            dataList.add(review);
        }
    }
    //kafka.generateResponseKafka(dataList, timeStamp, id, confId, params.getKafkaTopic());
    kafka.generateResponseIF(dataList, timeStamp, id, confId, params.getKafkaTopic());
    logger.debug("Data sent to kafka endpoint");
    ++id;
}

From source file:br.edu.ifes.bd2hibernate.cgt.Menu.java

private Date convertStringToDate(String dataRecebida) {

    Date dataNascimento = null;/*w  w w .jav a 2s.c  o m*/
    try {
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        dataNascimento = df.parse(dataRecebida);

    } catch (ParseException ex) {
        ex.printStackTrace();
    }
    return dataNascimento;
}