Example usage for java.time LocalDateTime parse

List of usage examples for java.time LocalDateTime parse

Introduction

In this page you can find the example usage for java.time LocalDateTime parse.

Prototype

public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) 

Source Link

Document

Obtains an instance of LocalDateTime from a text string using a specific formatter.

Usage

From source file:scouterx.webapp.request.CounterRequestByType.java

private void setTimeAsYmd() {
    ZoneId zoneId = ZoneId.systemDefault();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    LocalDateTime startDateTime = LocalDateTime.parse(startYmdHms, formatter);
    LocalDateTime endDateTime = LocalDateTime.parse(endYmdHms, formatter);

    startTimeMillis = startDateTime.atZone(zoneId).toEpochSecond() * 1000L;
    endTimeMillis = endDateTime.atZone(zoneId).toEpochSecond() * 1000L;
}

From source file:com.oembedler.moon.graphql.engine.type.GraphQLLocalDateTimeType.java

public GraphQLLocalDateTimeType(String name, String description, String dateFormat) {
    super(name, description, new Coercing() {
        private final TimeZone timeZone = TimeZone.getTimeZone("UTC");

        @Override/* w  ww  .ja  va2 s  . c  o  m*/
        public Object serialize(Object input) {
            if (input instanceof String) {
                return parse((String) input);
            } else if (input instanceof LocalDateTime) {
                return format((LocalDateTime) input);
            } else if (input instanceof Long) {
                return LocalDateTime.ofEpochSecond((Long) input, 0, ZoneOffset.UTC);
            } else if (input instanceof Integer) {
                return LocalDateTime.ofEpochSecond((((Integer) input).longValue()), 0, ZoneOffset.UTC);
            } else {
                throw new GraphQLException("Wrong timestamp value");
            }
        }

        @Override
        public Object parseValue(Object input) {
            return serialize(input);
        }

        @Override
        public Object parseLiteral(Object input) {
            if (!(input instanceof StringValue))
                return null;
            return parse(((StringValue) input).getValue());
        }

        private String format(LocalDateTime input) {
            return getDateTimeFormatter().format(input);
        }

        private LocalDateTime parse(String input) {
            LocalDateTime date = null;
            try {
                date = LocalDateTime.parse(input, getDateTimeFormatter());
            } catch (Exception e) {
                throw new GraphQLException("Can not parse input date", e);
            }
            return date;
        }

        private DateTimeFormatter getDateTimeFormatter() {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
            return formatter;
        }
    });
    Assert.notNull(dateFormat, "Date format must not be null");
}

From source file:ExifUtils.ExifReadWrite.java

private static List<meta> exifToMetaIMR(ArrayList<String> filenames, File dir) {
    List<meta> results = new ArrayList<>();
    for (String filename : filenames) {
        ArrayList<String[]> tags;
        String model = null;// ww  w.j a v a2  s.  c  o m
        String note = "";
        String iID = null;
        String dID = null;
        String odID = null;
        String captureDate = null;
        Boolean dateFormat = false;
        try {
            tags = readMeta(new File(dir + "\\" + filename));
        } catch (ImageProcessingException | IOException ex) {
            meta meta = new meta(dir + "\\" + filename, getZonedTimeFromStr(captureDate), dateFormat, model,
                    iID, dID, odID, ex.toString());
            System.out.println(meta);
            results.add(meta);
            continue;
        }
        for (String[] tag : tags) {
            //                System.out.println(tag[0]);
            switch (tag[0]) {
            case "Model":
                model = tag[1];
                break;
            case "xmpMM:InstanceID":
                iID = tag[1];
                break;
            case "xmpMM:DocumentID":
                dID = tag[1];
                break;
            case "xmpMM:OriginalDocumentID":
                odID = tag[1];
                break;
            case "Date/Time Original":
                captureDate = tag[1];
                break;
            case "exif:DateTimeOriginal":
                try {
                    ZonedDateTime wTZ = ZonedDateTime.parse(tag[1], XmpDateFormatTZ);
                    if (LocalDateTime.parse(captureDate, ExifDateFormat).equals(wTZ.toLocalDateTime()))
                        dateFormat = true;
                } catch (DateTimeParseException exc) {
                }
                break;
            }
        }
        meta meta = new meta(dir + "\\" + filename, getZonedTimeFromStr(captureDate), dateFormat, model, iID,
                dID, odID, note);
        System.out.println(meta);
        results.add(meta);
    }
    return results;
}

From source file:OandaProviderDriver.java

public ArrayList<SM230Candle> getRecentCandles(String instrument, String granularity, int count)
        throws ClientProtocolException, IOException {
    String normalized_instrument = instrument;

    // e.g., EUR/USD (ISO format) => EUR_USD (endpoint format)
    if (instrument.contains("/")) {
        normalized_instrument = instrument.replace("/", "_");
    }//from ww  w.j ava 2 s. c o  m

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet("https://api-fxtrade.oanda.com/v3/instruments/" + normalized_instrument
            + "/candles?count=" + String.valueOf(count) + "&price=M&granularity=" + granularity);

    System.out.println("Api KEY: " + apiKey);

    request.addHeader("Content-Type", "application/json");
    request.addHeader("Authorization", "Bearer " + apiKey);
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "", l = "";

    while ((l = rd.readLine()) != null) {
        line += l;
    }

    System.out.println("Line: " + line);

    JSONObject root = new JSONObject(line);
    JSONArray candles_json = root.getJSONArray("candles");
    JSONObject candle_json, mid;

    ArrayList<SM230Candle> candles = new ArrayList<>();

    for (int i = 0; i < candles_json.length(); i++) {
        candle_json = candles_json.getJSONObject(i);
        mid = candle_json.getJSONObject("mid");

        SM230Candle candle = new SM230Candle(instrument,
                LocalDateTime.parse(candle_json.get("time").toString(),
                        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSz")),
                granularity, Double.valueOf(mid.get("o").toString()), Double.valueOf(mid.get("h").toString()),
                Double.valueOf(mid.get("l").toString()), Double.valueOf(mid.get("c").toString()));

        candles.add(candle);
    }

    return candles;
}

From source file:com.hotelbeds.hotelapimodel.auto.util.AssignUtils.java

public static LocalDateTime getLocalDateTime(final String date, final DateTimeFormatter formatter) {
    return date != null ? LocalDateTime.parse(date, formatter) : null;
}

From source file:fr.pilato.elasticsearch.crawler.fs.tika.TikaDocParser.java

public static void generate(FsSettings fsSettings, InputStream inputStream, String filename, Doc doc,
        MessageDigest messageDigest, long filesize) throws IOException {
    logger.trace("Generating document [{}]", filename);
    // Extracting content with Tika
    // See #38: https://github.com/dadoonet/fscrawler/issues/38
    int indexedChars = 100000;
    if (fsSettings.getFs().getIndexedChars() != null) {
        if (fsSettings.getFs().getIndexedChars().percentage()) {
            indexedChars = (int) Math.round(filesize * fsSettings.getFs().getIndexedChars().asDouble());
            logger.trace("using percentage [{}] to define indexed chars: [{}]",
                    fsSettings.getFs().getIndexedChars(), indexedChars);
        } else {/*from   w ww .  ja v a2  s.  c  om*/
            indexedChars = (int) fsSettings.getFs().getIndexedChars().value();
            logger.trace("indexed chars [{}]",
                    indexedChars == -1 ? "has been disabled. All text will be extracted" : indexedChars);
        }
    }
    Metadata metadata = new Metadata();

    String parsedContent = null;

    if (messageDigest != null) {
        logger.trace("Generating hash with [{}]", messageDigest.getAlgorithm());
        inputStream = new DigestInputStream(inputStream, messageDigest);
    }

    ByteArrayOutputStream bos = null;
    if (fsSettings.getFs().isStoreSource()) {
        logger.debug("Using a TeeInputStream as we need to store the source");
        bos = new ByteArrayOutputStream();
        inputStream = new TeeInputStream(inputStream, bos);
    }

    try {
        // Set the maximum length of strings returned by the parseToString method, -1 sets no limit
        logger.trace("Beginning Tika extraction");
        parsedContent = tika().parseToString(inputStream, metadata, indexedChars);
        logger.trace("End of Tika extraction");
    } catch (Throwable e) {
        logger.debug("Failed to extract [" + indexedChars + "] characters of text for [" + filename + "]", e);
    }

    // Adding what we found to the document we want to index

    // File
    doc.getFile().setContentType(metadata.get(Metadata.CONTENT_TYPE));
    doc.getFile().setExtension(FilenameUtils.getExtension(filename));

    // We only add `indexed_chars` if we have other value than default or -1
    if (fsSettings.getFs().getIndexedChars() != null && fsSettings.getFs().getIndexedChars().value() != -1) {
        doc.getFile().setIndexedChars(indexedChars);
    }

    if (fsSettings.getFs().isAddFilesize()) {
        if (metadata.get(Metadata.CONTENT_LENGTH) != null) {
            // We try to get CONTENT_LENGTH from Tika first
            doc.getFile().setFilesize(Long.parseLong(metadata.get(Metadata.CONTENT_LENGTH)));
        }
    }
    if (messageDigest != null) {
        byte[] digest = messageDigest.digest();
        String result = "";
        // Convert to Hexa
        for (int i = 0; i < digest.length; i++) {
            result += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1);
        }
        doc.getFile().setChecksum(result);
    }
    // File

    // Meta
    doc.getMeta().setAuthor(metadata.get(TikaCoreProperties.CREATOR));
    doc.getMeta().setTitle(metadata.get(TikaCoreProperties.TITLE));
    String sDate = metadata.get(TikaCoreProperties.MODIFIED);
    if (sDate != null) {
        try {
            LocalDateTime date = LocalDateTime.parse(sDate, DateTimeFormatter.ISO_DATE_TIME);
            doc.getMeta().setDate(date);
        } catch (DateTimeParseException e) {
            logger.warn("Can not parse date [{}] for [{}]. Skipping date field...", sDate, filename);
        }
    }
    doc.getMeta().setKeywords(commaDelimitedListToStringArray(metadata.get(TikaCoreProperties.KEYWORDS)));

    if (fsSettings.getFs().isRawMetadata()) {
        logger.trace("Listing all available metadata:");
        for (String metadataName : metadata.names()) {
            String value = metadata.get(metadataName);
            // This is a logger trick which helps to generate our unit tests
            // You need to change test/resources/log4j2.xml fr.pilato.elasticsearch.crawler.fs.tika level to trace
            logger.trace("  assertThat(raw, hasEntry(\"{}\", \"{}\"));", metadataName, value);
            doc.getMeta().addRaw(metadataName, value);
        }
    }
    // Meta

    // Doc content
    doc.setContent(parsedContent);

    // Doc as binary attachment
    if (fsSettings.getFs().isStoreSource()) {
        doc.setAttachment(Base64.getEncoder().encodeToString(bos.toByteArray()));
    }
    logger.trace("End document generation");
    // End of our document
}

From source file:svc.managers.SMSManagerTest.java

@Test
public void citationDetailMessageGetsGenerated() throws TwiMLException, ParseException {
    setStageInSession(session, SMS_STAGE.VIEW_CITATION);
    session.setAttribute("dob", "06/01/1963");
    session.setAttribute("license_number", "F917801962");

    Citation citation = new Citation();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    citation.citation_date = LocalDate.parse("02/03/1990", formatter);
    citation.citation_number = "a1234";
    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm");
    citation.court_dateTime = LocalDateTime.parse("11/20/2015 04:22", formatter2);
    citation.court_id = new HashableEntity<Court>(Court.class, 1L);
    List<Citation> citations = new ArrayList<Citation>();
    citations.add(citation);//w  w w.  j a  v a2s.c o  m

    Court court = new Court();
    court.address = "1 Anystreet";
    court.city = "myCity";
    court.state = "myState";
    court.zip = "myZip";

    Violation violation = new Violation();
    violation.violation_number = "Y246";
    violation.violation_description = "myDescription";
    violation.status = VIOLATION_STATUS.CONT_FOR_PAYMENT;
    violation.fine_amount = new BigDecimal(200.54);
    violation.court_cost = new BigDecimal(22.34);
    List<Violation> violations = new ArrayList<Violation>();
    violations.add(violation);

    when(citationManagerMock.findCitations((CitationSearchCriteria) notNull())).thenReturn(citations);
    when(courtManagerMock.getCourtById(citations.get(0).court_id.getValue())).thenReturn(court);
    when(violationManagerMock.getViolationsByCitationNumber(anyString())).thenReturn(violations);
    TwimlMessageRequest twimlMessageRequest = new TwimlMessageRequest();
    twimlMessageRequest.setBody("1");
    String message = "Ticket Date: 02/03/1990\nCourt Date: 11/20/2015\nCourt Time: 04:22 AM\nTicket #: "
            + citation.citation_number;
    message += "\nCourt Address: " + court.address + " " + court.city + ", " + court.state + " " + court.zip;
    message += "\nViolation #: " + violation.violation_number + "\nViolation: "
            + violation.violation_description;
    message += "\nStatus: " + violation.status.toString();
    message += "\nFine Amount: $" + violation.fine_amount;
    message += "\nCourt Costs: $" + violation.court_cost;
    message += "\nReply with '1' to view another ticket";
    message += "\nReply with '2' for payment options";
    message += "\nReply with '3' to receive text message reminders about this court date";
    message += "\nReply with '4' to remove text message reminders about this court date";
    MessagingResponse twimlResponse = manager.getTwimlResponse(twimlMessageRequest, requestMock, session);
    assertEquals(createTwimlResponse(message).toXml(), twimlResponse.toXml());
}

From source file:org.obiba.mica.AbstractGitPersistableResource.java

private String createRestoreComment(CommitInfo commitInfo) {
    LocalDateTime date = LocalDateTime.parse(commitInfo.getDate().toString(),
            DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss zzz yyyy"));
    String formatted = date.format(DateTimeFormatter.ofPattern("MMM dd, yyyy h:mm a"));

    return String.format("Restored revision from '%s' (%s...)", formatted,
            commitInfo.getCommitId().substring(0, 9));
}

From source file:dk.dma.ais.lib.FileConvert.java

/** {@inheritDoc} */
@Override/*from   www  . j av a 2 s .co  m*/
protected void run(Injector injector) throws Exception {
    configureFileEnding();

    final EConsumer<String> consumer = new EConsumer<String>() {

        @Override
        public void accept(String s) throws IllegalArgumentException, IllegalAccessException,
                NoSuchFieldException, SecurityException, IOException, InterruptedException {
            Path path = Paths.get(s);
            LOG.debug("Started processing file " + path);

            Path endPath;
            if (keepFileStructure) {
                Path relative;
                relative = path;
                endPath = Paths.get(Paths.get(convertTo).toString(), relative.toString());
                new File(endPath.toString()).mkdirs();
            } else {
                endPath = Paths.get("");
            }

            String filename = path.getFileName().toString();
            if (!filename.endsWith(fileEnding))
                filename = FilenameUtils.removeExtension(filename) + fileEnding;
            Path filePath = Paths.get(endPath.toString(), filename);

            LOG.debug("Output File: " + filePath.toString());

            final OutputStream fos = new FileOutputStream(filePath.toString()); // 2

            final boolean createSituationFolder = !StringUtils.isBlank(kmzSnapshotAt);
            final long snapshotAtEpochMillis = createSituationFolder
                    ? LocalDateTime.parse(kmzSnapshotAt, formatter).toInstant(ZoneOffset.UTC).toEpochMilli()
                    : -1;

            OutputStreamSink<AisPacket> sink;
            if ("kmz".equals(outputSinkFormat)) {
                //AisPacketKMZOutputSink(filter, createSituationFolder, createMovementsFolder, createTracksFolder, isPrimaryTarget, isSecondaryTarget, triggerSnapshot, snapshotDescriptionSupplier, movementInterpolationStep, supplyTitle, supplyDescription, iconHrefSupplier);
                sink = AisPacketOutputSinks.newKmzSink(e -> true, // this.filter = e -> true;
                        createSituationFolder, // this.createSituationFolder = true;
                        true, // createMovementsFolder = true;
                        true, // this.createTracksFolder = true;
                        e -> kmzPrimaryMmsi <= 0 ? false : e.tryGetAisMessage().getUserId() == kmzPrimaryMmsi, // this.isPrimaryTarget = e -> false;
                        e -> kmzSecondaryMmsi <= 0 ? false
                                : e.tryGetAisMessage().getUserId() == kmzSecondaryMmsi, // this.isSecondaryTarget = e -> false;
                        e -> e.getBestTimestamp() >= snapshotAtEpochMillis, // this.triggerSnapshot = e -> false;
                        () -> "Situation at " + kmzSnapshotAt, // this.snapshotDescriptionSupplier = null;
                        () -> 10, // this.title = defaultTitleSupplier;
                        () -> "description", // this.description = defaultDescriptionSupplier;
                        () -> "10", //this.movementInterpolationStep = defaultMovementInterpolationStepSupplier;
                        (shipTypeCargo, navigationalStatus) -> "" // this.iconHrefSupplier = defaultIconHrefSupplier;
                );

            } else
                sink = AisPacketOutputSinks.getOutputSink(outputSinkFormat, columns);

            sink.closeWhenFooterWritten();

            AisPacketReader apis = AisPacketReader.createFromFile(path, false);

            apis.writeTo(fos, sink);
            apis.close();
            fos.close();
        }
    };

    /*
     * Creates a pool of executors, 4 threads. Each thread will open a file using an aispacket reader, 10000 files can be
     * submitted to the queue, afterwards the calling thread will execute the job instead.
     */
    ThreadPoolExecutor threadpoolexecutor = new ThreadPoolExecutor(4, 4, 1, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10000), new ThreadPoolExecutor.CallerRunsPolicy());
    for (final String s : sources) {
        threadpoolexecutor.execute(() -> {
            try {
                consumer.accept(s);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
    }

    threadpoolexecutor.shutdown();
    threadpoolexecutor.awaitTermination(999, TimeUnit.DAYS);
}

From source file:org.jboss.as.test.integration.web.session.SessionManagementTestCase.java

@Test
public void testSessionManagementOperations() throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {

        ModelNode operation = new ModelNode();
        operation.get(ModelDescriptionConstants.OP).set(LIST_SESSIONS);
        operation.get(ModelDescriptionConstants.OP_ADDR).set(PathAddress
                .parseCLIStyleAddress("/deployment=management.war/subsystem=undertow").toModelNode());
        ModelNode opRes = managementClient.getControllerClient().execute(operation);
        Assert.assertEquals(opRes.toString(), "success",
                opRes.get(ModelDescriptionConstants.OUTCOME).asString());
        Assert.assertEquals(Collections.emptyList(), opRes.get(ModelDescriptionConstants.RESULT).asList());
        long c1 = System.currentTimeMillis();
        HttpGet get = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress()
                + ":8080/management/SessionPersistenceServlet");
        HttpResponse res = client.execute(get);
        long c2 = System.currentTimeMillis();
        String sessionId = null;/*from  www . j  a  va 2  s.  co  m*/
        for (Header cookie : res.getHeaders("Set-Cookie")) {
            if (cookie.getValue().startsWith("JSESSIONID=")) {
                sessionId = cookie.getValue().split("=")[1].split("\\.")[0];
                break;
            }
        }
        Assert.assertNotNull(sessionId);
        opRes = managementClient.getControllerClient().execute(operation);
        Assert.assertEquals(opRes.toString(), "success",
                opRes.get(ModelDescriptionConstants.OUTCOME).asString());
        Assert.assertEquals(opRes.toString(), Collections.singletonList(new ModelNode(sessionId)),
                opRes.get(ModelDescriptionConstants.RESULT).asList());

        operation.get(SESSION_ID).set(sessionId);

        opRes = executeOperation(operation, GET_SESSION_CREATION_TIME_MILLIS);
        long time1 = opRes.get(ModelDescriptionConstants.RESULT).asLong();
        Assert.assertTrue(c1 <= time1);
        Assert.assertTrue(time1 <= c2);

        opRes = executeOperation(operation, GET_SESSION_CREATION_TIME);
        long sessionCreationTime = LocalDateTime
                .parse(opRes.get(ModelDescriptionConstants.RESULT).asString(), DateTimeFormatter.ISO_DATE_TIME)
                .toInstant(ZoneId.systemDefault().getRules().getOffset(Instant.now())).toEpochMilli();
        Assert.assertEquals(time1, sessionCreationTime);

        opRes = executeOperation(operation, GET_SESSION_LAST_ACCESSED_TIME_MILLIS);
        Assert.assertEquals(time1, opRes.get(ModelDescriptionConstants.RESULT).asLong());

        opRes = executeOperation(operation, GET_SESSION_LAST_ACCESSED_TIME);
        long aTime2 = LocalDateTime
                .parse(opRes.get(ModelDescriptionConstants.RESULT).asString(), DateTimeFormatter.ISO_DATE_TIME)
                .toInstant(ZoneId.systemDefault().getRules().getOffset(Instant.now())).toEpochMilli();
        Assert.assertEquals(time1, aTime2);
        Assert.assertEquals(sessionCreationTime, aTime2);

        opRes = executeOperation(operation, LIST_SESSION_ATTRIBUTE_NAMES);
        List<ModelNode> resultList = opRes.get(ModelDescriptionConstants.RESULT).asList();
        Assert.assertEquals(1, resultList.size());
        Assert.assertEquals(opRes.toString(), "val", resultList.get(0).asString());

        opRes = executeOperation(operation, LIST_SESSION_ATTRIBUTES);
        List<Property> properties = opRes.get(ModelDescriptionConstants.RESULT).asPropertyList();
        Assert.assertEquals(opRes.toString(), 1, properties.size());
        Property property = properties.get(0);
        Assert.assertEquals(opRes.toString(), "val", property.getName());
        Assert.assertEquals(opRes.toString(), "0", property.getValue().asString());

        //we want to make sure that the values will be different
        //so we wait 10ms
        Thread.sleep(10);
        long a1 = System.currentTimeMillis();
        client.execute(get);
        long a2 = System.currentTimeMillis();

        do {
            //because the last access time is updated after the request returns there is a possible race here
            //to get around this we execute this op in a loop and wait for the value to change
            //in 99% of cases this will only iterate once
            //because of the 10ms sleep above they should ways be different
            //we have a max wait time of 1s if something goes wrong
            opRes = executeOperation(operation, GET_SESSION_LAST_ACCESSED_TIME_MILLIS);
            time1 = opRes.get(ModelDescriptionConstants.RESULT).asLong();
            if (time1 != sessionCreationTime) {
                break;
            }
        } while (System.currentTimeMillis() < a1 + 1000);
        Assert.assertTrue(a1 <= time1);
        Assert.assertTrue(time1 <= a2);

        opRes = executeOperation(operation, GET_SESSION_LAST_ACCESSED_TIME);
        long time2 = LocalDateTime
                .parse(opRes.get(ModelDescriptionConstants.RESULT).asString(), DateTimeFormatter.ISO_DATE_TIME)
                .toInstant(ZoneId.systemDefault().getRules().getOffset(Instant.now())).toEpochMilli();
        Assert.assertEquals(time1, time2);

        operation.get(ATTRIBUTE).set("val");
        opRes = executeOperation(operation, GET_SESSION_ATTRIBUTE);
        Assert.assertEquals("1", opRes.get(ModelDescriptionConstants.RESULT).asString());

        executeOperation(operation, INVALIDATE_SESSION);

        opRes = executeOperation(operation, LIST_SESSIONS);
        Assert.assertEquals(Collections.emptyList(), opRes.get(ModelDescriptionConstants.RESULT).asList());
    }
}