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.xeiam.datasets.reuters21578.bootstrap.Reuters21578Data2DB.java

/**
 * Get a Reuters21578 object from a story String
 * //from  w w  w  .j  a  va  2  s . c  om
 * @param storyText
 * @return
 */
private Reuters21578 getReuters21578StoryFromText(String storyText) {

    // System.out.println(storyText);

    // ATTRIBUTES /////////////////////////
    String firstLine = storyText.split(System.getProperty("line.separator"))[0];
    // System.out.println(firstLine);
    String newIdString = extractAttribute(firstLine, "NEWID");
    int newId = Integer.parseInt(newIdString);
    String oldIdString = extractAttribute(firstLine, "OLDID");
    int oldId = Integer.parseInt(oldIdString);
    String topicsString = extractAttribute(firstLine, "TOPICS");
    boolean topicsBool = topicsString.equalsIgnoreCase("YES");
    String lewissplitString = extractAttribute(firstLine, "LEWISSPLIT");
    String cgisplitString = extractAttribute(firstLine, "CGISPLIT");

    // DATE /////////////////////////
    String dateString = extractTextBetweenTags(storyText, "DATE");
    // System.out.println("date=" + dateString);
    Date date = null;
    try {
        DateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SS");
        date = sdf.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // TOPICS /////////////////////////
    String topicsText = extractTextBetweenTags(storyText, "TOPICS");
    List<String> topicsArray = extractElementAsLines(topicsText, "D");
    String topicsCSV = Joiner.on(", ").join(topicsArray);
    // PLACES /////////////////////////
    String placesText = extractTextBetweenTags(storyText, "PLACES");
    List<String> placesArray = extractElementAsLines(placesText, "D");
    String placesCSV = Joiner.on(", ").join(placesArray);
    // PEOPLE /////////////////////////
    String peopleText = extractTextBetweenTags(storyText, "PEOPLE");
    List<String> peopleArray = extractElementAsLines(peopleText, "D");
    String peopleCSV = Joiner.on(", ").join(peopleArray);
    // ORGS /////////////////////////
    String orgsText = extractTextBetweenTags(storyText, "ORGS");
    List<String> orgsArray = extractElementAsLines(orgsText, "D");
    String orgsCSV = Joiner.on(", ").join(orgsArray);
    // EXCHANGES /////////////////////////
    String exchangesText = extractTextBetweenTags(storyText, "EXCHANGES");
    List<String> exchangesArray = extractElementAsLines(exchangesText, "D");
    String exchangesCSV = Joiner.on(", ").join(exchangesArray);
    // COMPANIES /////////////////////////
    String companiesText = extractTextBetweenTags(storyText, "COMPANIES");
    List<String> companiesArray = extractElementAsLines(companiesText, "D");
    String companiesCSV = Joiner.on(", ").join(companiesArray);

    // TITLE /////////////////////////
    String titleText = extractTextBetweenTags(storyText, "TITLE");
    // DATELINE /////////////////////////
    String datelineText = extractTextBetweenTags(storyText, "DATELINE");
    // BODY /////////////////////////
    String body = extractTextBetweenTags(storyText, "BODY").replaceAll("\\s+", " ");
    // System.out.println(body);
    if (body.length() > maxBodyLength) {
        maxBodyLength = body.length();
    }

    Reuters21578 reuters21578 = new Reuters21578();
    reuters21578.setNewid(newId);
    reuters21578.setOldid(oldId);
    reuters21578.setTopicsbool(topicsBool);
    reuters21578.setLewissplit(lewissplitString);
    reuters21578.setCgisplit(cgisplitString);
    reuters21578.setDate(date);
    reuters21578.setTopics(topicsCSV);
    reuters21578.setPlaces(placesCSV);
    reuters21578.setPeople(peopleCSV);
    reuters21578.setOrgs(orgsCSV);
    reuters21578.setExchanges(exchangesCSV);
    reuters21578.setCompanies(companiesCSV);
    reuters21578.setTitle(titleText);
    reuters21578.setDateline(datelineText);
    reuters21578.setBody(body);

    return reuters21578;

}

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

/**
 * @throws Exception//from   ww  w  .j  a  va  2  s.c om
 */
@Test
public void exportData() throws Exception {

    HaqService haqService = (HaqService) applicationContext.getBean(ComponentNames.HAQ_SERVICE);
    assertNotNull(haqService);

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

    DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");

    List<PatientQuestionAnswer> result = patientQuestionAnswerService.exportData(haqs.get(0).getId(),
            dateFormat.parse("1.11.2010"), dateFormat.parse("1.11.2010"));
    assertEquals(4, result.size());

    result = patientQuestionAnswerService.exportData(haqs.get(0).getId(), dateFormat.parse("1.11.2010"),
            dateFormat.parse("3.11.2010"));
    assertEquals(12, result.size());

    result = patientQuestionAnswerService.exportData(null, dateFormat.parse("1.2.2010"),
            dateFormat.parse("1.12.2010"));
    assertEquals(27, result.size());
}

From source file:com.parse.ParseObjectCurrentCoderTest.java

@Test
public void testObjectSerializationFormat() throws Exception {
    ParseObject childObject = new ParseObject("child");
    childObject.setObjectId("childObjectId");

    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
    format.setTimeZone(new SimpleTimeZone(0, "GMT"));

    String dateString = "2011-08-12T01:06:05Z";
    Date date = format.parse(dateString);

    String jsonString = "{" + "'id':'wnAiJVI3ra'," + "'updated_at':'" + dateString + "',"
            + "'pointers':{'child':['child','" + childObject.getObjectId() + "']}," + "'classname':'myClass',"
            + "'dirty':true," + "'data':{'foo':'bar'}," + "'created_at':'2011-08-12T01:06:05Z',"
            + "'deletedKeys':['toDelete']" + "}";

    ParseObjectCurrentCoder coder = ParseObjectCurrentCoder.get();
    JSONObject json = new JSONObject(jsonString);
    ParseObject.State state = coder.decode(new ParseObject.State.Builder("Test"), json, ParseDecoder.get())
            .build();/*w  w  w . j a  va2  s. c o m*/

    assertEquals("wnAiJVI3ra", state.objectId());
    assertEquals("bar", state.get("foo"));
    assertEquals(date.getTime(), state.createdAt());
    assertEquals(((ParseObject) state.get("child")).getObjectId(), childObject.getObjectId());

    // Test that objects can be serialized and deserialized without timestamps
    String jsonStringWithoutTimestamps = "{" + "'id':'wnAiJVI3ra'," + "'pointers':{'child':['child','"
            + childObject.getObjectId() + "']}," + "'classname':'myClass'," + "'dirty':true,"
            + "'data':{'foo':'bar'}," + "'deletedKeys':['toDelete']" + "}";

    json = new JSONObject(jsonStringWithoutTimestamps);
    state = coder.decode(new ParseObject.State.Builder("Test"), json, ParseDecoder.get()).build();
    assertEquals("wnAiJVI3ra", state.objectId());
}

From source file:com.streamreduce.rest.resource.agent.AgentResource.java

/**
 * Takes a JSON payload representing an agent metrics payload, validates it and
 * persists validated payloads.  This will also result in a stream message
 * with the agent metric information in the message stream.  (Note: The JSON
 * payload can be either a singular agent metrics payload or an array of agent
 * metrics payload objects.)//  w w  w .  j  a  va  2  s . co  m
 * <br /><br />
 * The request object should be structured as described below:
 *
 * <ul class="indented">
 *     <li><b>node_id*:</b> The instance id as known by the cloud provider (Must correspond to a cloud inventory item's node id)</li>
 *     <li><b>data*:</b> The JSON object describing the agent metric payload
 *         <ul>
 *             <li><b>generated*:</b> The timestamp of when the metric was gathered/created (Format: yyyy-MM-dd'T'HH:mm:ss.SSSSSS)</li>
 *             <li>... (This data can be whatever you want really and since we do not validate this, no need in documenting it at this time.)</li>
 *         </ul>
 *     </li>
 * </ul>
 *
 * <b>* denotes a required field.</b>
 *
 * @param jsonString the raw JSON payload representing either a singular agent
 * metrics payload or an array of singular agent metrics payloads
 *
 * @return the result of the request
 *
 * @response.representation.405.doc Returned if the request was invalid in any way:
 * Invalid agent metrics payload structure, invalid cloud inventory item id in the
 * payload or whenever any deeper level exception occurs
 *
 * @response.representation.201.doc Returned if the request was successful
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createAgentMetricsEntry(String jsonString) {

    if (isEmpty(jsonString)) {
        return error("Missing payload", Response.status(Response.Status.BAD_REQUEST));
    }

    try {
        JSONObject json = JSONObject.fromObject(jsonString);

        if (!json.has("node_id")) {
            return error("Request is missing the node id to associate the metrics with.",
                    Response.status(Response.Status.BAD_REQUEST));
        }

        if (!json.has("data")) {
            return error("Request is missing the 'data'.", Response.status(Response.Status.BAD_REQUEST));
        }

        try {
            json.getJSONArray("data");
        } catch (JSONException je) {
            return error("'data' should be an array.", Response.status(Response.Status.BAD_REQUEST));
        }

        String nodeId = json.getString("node_id");
        List<InventoryItem> inventoryItems = applicationManager.getInventoryService()
                .getInventoryItemsForExternalId(nodeId);

        if (inventoryItems == null || inventoryItems.isEmpty()) {
            return error("'node_id' does not correspond with an inventory item, no metrics stored.",
                    Response.status(Response.Status.BAD_REQUEST));
        }

        // we might have multiple inventoryItems with this nodeId
        // if keys are shared across the account boundary (you never know!)
        for (InventoryItem inventoryItem : inventoryItems) {
            JSONArray metrics = json.getJSONArray("data");

            for (Object rawMetric : metrics) {
                JSONObject metric = (JSONObject) rawMetric;
                String generated = metric.getString("generated");
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
                Date dateGenerated;

                try {
                    dateGenerated = df.parse(generated);
                } catch (ParseException pe) {
                    logger.error("Unable to parse the generated date of the metric.", pe);
                    dateGenerated = new Date();
                }

                Map<String, Object> eventContext = new HashMap<>();

                eventContext.put("activityGenerated", dateGenerated);
                eventContext.put("activityPayload", metric);

                inventoryItem.addHashtag("agent");

                // Create the event stream entry
                Event event = applicationManager.getEventService().createEvent(EventId.ACTIVITY, inventoryItem,
                        eventContext);

                // create the message
                // note: all messages will have the #agent tag now.
                applicationManager.getMessageService().sendAccountMessage(event, inventoryItem,
                        inventoryItem.getConnection(), dateGenerated.getTime(), MessageType.AGENT,
                        inventoryItem.getHashtags(), null);

            }

        }

        return Response.status(Response.Status.CREATED).build();

    } catch (Exception e) {
        logger.error("Agent Exception", e);
        return error(e.getMessage(), Response.status(Response.Status.BAD_REQUEST));
    }
}

From source file:MainFrame.HttpCommunicator.java

public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel)
        throws MalformedURLException, IOException {
    BufferedReader in = null;/* ww w . ja  va  2s  . c o m*/
    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));

        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(new JSONObject().toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);

        InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));

        in = new BufferedReader(new InputStreamReader(stream));
    } else {
        URL obj = new URL(SingleDataHolder.getInstance().hostAdress);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "apideskviewer.getAllLessons={}";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + SingleDataHolder.getInstance().hostAdress);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }

    JSONParser parser = new JSONParser();
    try {
        Object parsedResponse = parser.parse(in);

        JSONObject jsonParsedResponse = (JSONObject) parsedResponse;

        for (int i = 0; i < jsonParsedResponse.size(); i++) {
            String s = (String) jsonParsedResponse.get(String.valueOf(i));
            String[] splittedPath = s.split("/");
            DateFormat DF = new SimpleDateFormat("yyyyMMdd");
            Date d = DF.parse(splittedPath[1].replaceAll(".bin", ""));
            Lesson lesson = new Lesson(splittedPath[0], d, false);
            String group = splittedPath[0];
            String date = new SimpleDateFormat("dd.MM.yyyy").format(d);

            if (((DefaultComboBoxModel) comboGroups.getModel()).getIndexOf(group) == -1) {
                comboGroups.addItem(group);
            }
            if (((DefaultComboBoxModel) comboDates.getModel()).getIndexOf(date) == -1) {
                comboDates.addItem(date);
            }
            tableModel.addLesson(lesson);
        }
    } catch (Exception ex) {
    }
}

From source file:com.salesmanager.checkout.files.FilesAction.java

public String accessUrl() {

    try {//  w w w  .j  ava2  s.c o  m

        // parse file download request
        String fileId = getServletRequest().getParameter("fileId");
        String lang = getServletRequest().getParameter("lang");

        if (StringUtils.isBlank(fileId)) {
            List msg = new ArrayList();
            msg.add(getText("error.downloadurl.invalid"));
            super.setActionErrors(msg);
            return "GENERICERROR";
        }

        Map fileInfo = FileUtil.getUrlTokens(fileId);

        String order = (String) fileInfo.get("ID");
        String date = (String) fileInfo.get("DATE");

        orderId = order;

        // Compare the date
        Date today = new Date();
        DateFormat d = new SimpleDateFormat("yyyy-MM-dd");
        Date dt = null;

        dt = d.parse(date);

        if (dt.before(new Date(today.getTime()))) {
            // expired
            CoreException excpt = new CoreException(ErrorConstants.DELAY_EXPIRED);
            throw excpt;
        }

    } catch (Exception e) {

        if (e instanceof CoreException) {
            String message = getText("error.downloadurl.expired");
            this.setFileMessage(message);
            return "DELAYEXPIRED";
        } else {
            log.error(e);
            super.setTechnicalMessage();
            return "GENERICERROR";
        }

    }

    return SUCCESS;

}

From source file:at.ac.tuwien.ifs.tita.dao.test.time.EffortDaoTest.java

/**
 * Test: Get TimeEffort by day.//from   w w  w.j av a2  s  .  co m
 */
@Test
public void testGetTimeEffortByDay() {
    List<Effort> list = null;

    String strdate1 = "01.01.2010";
    DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
    Date date1 = null;

    try {
        date1 = formatter.parse(strdate1);
    } catch (ParseException e1) {
        fail();
    }

    try {
        list = timeEffortDAO.getTimeEffortsDailyView(date1, 1L);
        Assert.assertNotNull(list);
        Assert.assertFalse(list.isEmpty());
    } catch (PersistenceException e) {
        fail();
    }
}

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

private Calendar convertStringToCalendar(String dataRecebida) {

    Calendar dataNascimento = null;
    try {/* ww  w. j a va  2s . c o m*/
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        Date dataNas = df.parse(dataRecebida);
        dataNascimento = Calendar.getInstance();
        dataNascimento.setTime(dataNas);

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

From source file:edu.um.umflix.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HashMap<String, String> mapValues = new HashMap<String, String>();
    List<Clip> clips = new ArrayList<Clip>();
    List<Byte[]> listData = new ArrayList<Byte[]>();
    int i = 0;/*from   w  w  w.j a  v a 2 s  .  c o  m*/

    try {
        List<FileItem> items = getFileItems(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process normal fields here.

                mapValues.put(item.getFieldName(), item.getString());
                // w.print("Field name: " + item.getFieldName());
                // w.print("Field value: " + item.getString());
            } else {
                // Process <input type="file"> here.

                InputStream movie = item.getInputStream();
                byte[] bytes = IOUtils.toByteArray(movie);
                Byte[] clipBytes = ArrayUtils.toObject(bytes);
                Clip clip = new Clip(Long.valueOf(0), i);
                clips.add(i, clip);
                listData.add(i, clipBytes);
                i++;
                // w.print(movie);

            }
        }
    } catch (FileUploadException e) {
        log.error("Error uploading file, please try again.");
        request.setAttribute("error", "Error uploading file, please try again");
        request.setAttribute("token", mapValues.get("token"));
        request.getRequestDispatcher("/upload.jsp").forward(request, response);
    }
    //Sets duration of clip and saves clipdata
    for (int j = 0; j < clips.size(); j++) {
        int duration = timeToInt(mapValues.get("clipduration" + j));
        clips.get(j).setDuration(Long.valueOf(duration));
        ClipData clipData = new ClipData(listData.get(j), clips.get(j));

        try {
            vManager.uploadClip(mapValues.get("token"), new Role(Role.RoleType.MOVIE_PROVIDER.getRole()),
                    clipData);
            log.info("ClipData uploader!");
        } catch (InvalidTokenException e) {
            log.error("Unknown user, please try again.");
            request.setAttribute("error", "Unknown user, please try again.");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

    }

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    Date endDate = null;
    Date startDate = null;
    Date premiereDate = null;
    try {
        endDate = formatter.parse(mapValues.get("endDate"));
        startDate = formatter.parse(mapValues.get("startDate"));
        premiereDate = formatter.parse(mapValues.get("premiere"));
    } catch (ParseException e) {
        log.error("Error parsing date");
        request.setAttribute("token", mapValues.get("token"));
        request.setAttribute("error", "Invalid date, please try again");
        request.getRequestDispatcher("/upload.jsp").forward(request, response);
        return;

    }

    License license = new License(false, Long.valueOf(0), mapValues.get("licenseDescription"), endDate,
            Long.valueOf(mapValues.get("maxViews")), Long.valueOf(1), startDate, mapValues.get("licenseName"));
    List<License> licenses = new ArrayList<License>();
    licenses.add(license);

    ArrayList<String> cast = new ArrayList<String>();
    cast.add(mapValues.get("actor"));
    Movie movie = new Movie(cast, clips, mapValues.get("director"), Long.valueOf(mapValues.get("duration")),
            false, mapValues.get("genre"), licenses, premiereDate, mapValues.get("title"));

    try {
        vManager.uploadMovie(mapValues.get("token"), new Role(Role.RoleType.MOVIE_PROVIDER.getRole()), movie);
        log.info("Movie uploaded!");
    } catch (InvalidTokenException e) {
        log.error("Unknown user, please try again.");
        request.setAttribute("error", "Unknown user, please try again.");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
        return;
    }
    request.setAttribute("message", "Movie uploaded successfully.");
    request.setAttribute("token", mapValues.get("token"));
    request.getRequestDispatcher("/upload.jsp").forward(request, response);
}

From source file:de.meisl.eisstockitems.ImportTest.java

@Test
public void importJahreskennbuchstaben() throws IOException, ParseException {
    List<String> readLines = FileUtils.readLines(new File("data/jahreskennbuchstaben.csv"), "UTF-8");
    for (String line : readLines) {

        DateFormat format = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);

        String[] split = line.split(",", -1);
        Date year = format.parse(split[0]);
        String character = split[1];
        String remark = split[2];

        List<YearCharacter> category = yearCharRepository.findByYear(year);
        if (category.isEmpty()) {
            log.info(String.format("Add new YearCharacter '%s' for year '%s'", character, year));
            YearCharacter item = new YearCharacter();
            item.setYearCharacter(character);
            item.setYear(year);//w  w  w . j av  a2  s.  c om
            item.setRemark(remark);

            item = yearCharRepository.save(item);

            log.info("Created YearCharacter for RegNr '" + character + "': " + item);
        }
    }

}