Example usage for java.time Instant parse

List of usage examples for java.time Instant parse

Introduction

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

Prototype

public static Instant parse(final CharSequence text) 

Source Link

Document

Obtains an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z .

Usage

From source file:no.ssb.jsonstat.v2.DatasetDeserializationTest.java

@Test
public void testGalicia() throws Exception {

    URL galicia = Resources.getResource(getClass(), "./galicia.json");

    Dataset jsonStat = mapper.readValue(new BufferedInputStream(galicia.openStream()), DatasetBuildable.class)
            .build();/*from w ww .  j a v  a2  s  .  c o m*/

    assertThat(jsonStat.getVersion()).isEqualTo("2.0");
    assertThat(jsonStat.getClazz()).isEqualTo("dataset");
    assertThat(jsonStat.getLabel())
            .contains("Population by province of residence, place of birth, age, gender and year in Galicia");
    assertThat(jsonStat.getSource()).contains("INE and IGE");
    assertThat(jsonStat.getUpdated()).contains(Instant.parse("2012-12-27T12:25:09Z"));

    Iterable<Map.Entry<List<String>, Number>> limit = Iterables.limit(jsonStat.asMap().entrySet(), 5);
    assertThat(limit).containsExactly(entry(asList("T", "T", "T", "2001", "T", "pop"), 2695880),
            entry(asList("T", "T", "T", "2001", "15", "pop"), 1096027),
            entry(asList("T", "T", "T", "2001", "27", "pop"), 357648),
            entry(asList("T", "T", "T", "2001", "32", "pop"), 338446),
            entry(asList("T", "T", "T", "2001", "36", "pop"), 903759));

}

From source file:com.linecorp.bot.model.event.CallbackRequestTest.java

@Test
public void testLocation() throws IOException {
    parse("callback/location.json", callbackRequest -> {
        assertThat(callbackRequest.getEvents()).hasSize(1);
        Event event = callbackRequest.getEvents().get(0);
        assertThat(event).isInstanceOf(MessageEvent.class);
        assertThat(event.getSource()).isInstanceOf(UserSource.class);
        assertThat(event.getSource().getUserId()).isEqualTo("u206d25c2ea6bd87c17655609a1c37cb8");
        assertThat(event.getTimestamp()).isEqualTo(Instant.parse("2016-05-07T13:57:59.859Z"));

        MessageEvent messageEvent = (MessageEvent) event;
        assertThat(messageEvent.getReplyToken()).isEqualTo("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA");
        MessageContent message = messageEvent.getMessage();
        assertThat(message).isInstanceOf(LocationMessageContent.class);
        if (message instanceof LocationMessageContent) {
            assertThat(((LocationMessageContent) message).getAddress())
                    .isEqualTo("150-0002 ??");
        }// w w w  .jav  a  2  s .c om
    });
}

From source file:org.apache.james.transport.mailets.DSNBounceTest.java

@Test
public void serviceShouldSendMultipartMailToTheSender() throws Exception {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME)
            .mailetContext(fakeMailContext).build();
    dsnBounce.init(mailetConfig);//from w w  w.  j  a v a 2 s.c  o m

    MailAddress senderMailAddress = new MailAddress("sender@domain.com");
    FakeMail mail = FakeMail.builder().sender(senderMailAddress)
            .mimeMessage(MimeMessageBuilder.mimeMessageBuilder().setText("My content")).name(MAILET_NAME)
            .recipient("recipient@domain.com").lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z")))
            .build();

    dsnBounce.service(mail);

    List<SentMail> sentMails = fakeMailContext.getSentMails();
    assertThat(sentMails).hasSize(1);
    SentMail sentMail = sentMails.get(0);
    assertThat(sentMail.getSender()).isNull();
    assertThat(sentMail.getRecipients()).containsOnly(senderMailAddress);
    MimeMessage sentMessage = sentMail.getMsg();
    assertThat(sentMessage.getContentType()).contains("multipart/report;");
    assertThat(sentMessage.getContentType()).contains("report-type=delivery-status");
}

From source file:com.orange.cepheus.broker.persistence.RegistrationsRepository.java

/**
 * Get registration/*  w  w w  .j a  v  a 2s . c  o  m*/
 * @param registrationId
 * @return registration
 * @throws RegistrationPersistenceException, EmptyResultDataAccessException
 */
public Registration getRegistration(String registrationId)
        throws RegistrationPersistenceException, EmptyResultDataAccessException {
    try {
        return jdbcTemplate.queryForObject(
                "select expirationDate, registerContext from t_registrations where id=?",
                new Object[] { registrationId }, (ResultSet rs, int rowNum) -> {
                    Registration registration = new Registration();
                    try {
                        registration.setExpirationDate(Instant.parse(rs.getString("expirationDate")));
                        registration.setRegisterContext(
                                mapper.readValue(rs.getString("registerContext"), RegisterContext.class));
                    } catch (IOException e) {
                        throw new SQLException(e);
                    }
                    return registration;
                });
    } catch (EmptyResultDataAccessException e) {
        throw e;
    } catch (DataAccessException e) {
        throw new RegistrationPersistenceException(e);
    }
}

From source file:com.linecorp.bot.model.event.CallbackRequestTest.java

@Test
public void testSticker() throws IOException {
    parse("callback/sticker.json", callbackRequest -> {
        assertThat(callbackRequest.getEvents()).hasSize(1);
        Event event = callbackRequest.getEvents().get(0);
        assertThat(event).isInstanceOf(MessageEvent.class);
        assertThat(event.getSource()).isInstanceOf(UserSource.class);
        assertThat(event.getSource().getUserId()).isEqualTo("u206d25c2ea6bd87c17655609a1c37cb8");
        assertThat(event.getTimestamp()).isEqualTo(Instant.parse("2016-05-07T13:57:59.859Z"));

        MessageEvent messageEvent = (MessageEvent) event;
        assertThat(messageEvent.getReplyToken()).isEqualTo("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA");
        MessageContent message = messageEvent.getMessage();
        assertThat(message).isInstanceOf(StickerMessageContent.class);
        if (message instanceof StickerMessageContent) {
            assertThat(((StickerMessageContent) message).getStickerId()).isEqualTo("1");
            assertThat(((StickerMessageContent) message).getPackageId()).isEqualTo("1");
        }/*w  ww.  j a v a2 s .c  om*/
    });
}

From source file:org.apache.james.transport.mailets.DSNBounceTest.java

@Test
public void serviceShouldSendMultipartMailContainingTextPart() throws Exception {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME)
            .mailetContext(fakeMailContext).build();
    dsnBounce.init(mailetConfig);/*from   w  w w  . j  a v  a  2s . co m*/

    MailAddress senderMailAddress = new MailAddress("sender@domain.com");
    FakeMail mail = FakeMail.builder().sender(senderMailAddress).attribute("delivery-error", "Delivery error")
            .mimeMessage(MimeMessageBuilder.mimeMessageBuilder().setText("My content")).name(MAILET_NAME)
            .recipient("recipient@domain.com").lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z")))
            .build();

    dsnBounce.service(mail);

    String hostname = InetAddress.getLocalHost().getHostName();
    String expectedContent = "Hi. This is the James mail server at " + hostname
            + ".\nI'm afraid I wasn't able to deliver your message to the following addresses.\nThis is a permanent error; I've given up. Sorry it didn't work out.  Below\nI include the list of recipients and the reason why I was unable to deliver\nyour message.\n\n"
            + "Failed recipient(s):\n" + "recipient@domain.com\n" + "\n" + "Error message:\n"
            + "Delivery error\n" + "\n";

    List<SentMail> sentMails = fakeMailContext.getSentMails();
    assertThat(sentMails).hasSize(1);
    SentMail sentMail = sentMails.get(0);
    MimeMessage sentMessage = sentMail.getMsg();
    MimeMultipart content = (MimeMultipart) sentMessage.getContent();
    BodyPart bodyPart = content.getBodyPart(0);
    assertThat(bodyPart.getContentType()).isEqualTo("text/plain; charset=us-ascii");
    assertThat(bodyPart.getContent()).isEqualTo(expectedContent);
}

From source file:de.qaware.chronix.importer.csv.FileImporter.java

/**
 * Reads the given file / folder and calls the bi consumer with the extracted points
 *
 * @param points/*from w  w w . jav  a 2 s .c o  m*/
 * @param folder
 * @param databases
 * @return
 */
public Pair<Integer, Integer> importPoints(Map<Attributes, Pair<Instant, Instant>> points, File folder,
        BiConsumer<List<ImportPoint>, Attributes>... databases) {

    final AtomicInteger pointCounter = new AtomicInteger(0);
    final AtomicInteger tsCounter = new AtomicInteger(0);
    final File metricsFile = new File(METRICS_FILE_PATH);

    LOGGER.info("Writing imported metrics to {}", metricsFile);
    LOGGER.info("Import supports csv files as well as gz compressed csv files.");

    try {
        final FileWriter metricsFileWriter = new FileWriter(metricsFile);

        Collection<File> files = new ArrayList<>();
        if (folder.isFile()) {
            files.add(folder);
        } else {
            files.addAll(FileUtils.listFiles(folder, new String[] { "gz", "csv" }, true));
        }

        AtomicInteger counter = new AtomicInteger(0);

        files.parallelStream().forEach(file -> {
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
            NumberFormat nf = DecimalFormat.getInstance(numberLocal);

            InputStream inputStream = null;
            BufferedReader reader = null;
            try {
                inputStream = new FileInputStream(file);

                if (file.getName().endsWith("gz")) {
                    inputStream = new GZIPInputStream(inputStream);
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                //Read the first line
                String headerLine = reader.readLine();

                if (headerLine == null || headerLine.isEmpty()) {
                    boolean deleted = deleteFile(file, inputStream, reader);
                    LOGGER.debug("File is empty {}. File {} removed {}", file.getName(), deleted);
                    return;
                }

                //Extract the attributes from the file name
                //E.g. first_second_third_attribute.csv
                String[] fileNameMetaData = file.getName().split("_");

                String[] metrics = headerLine.split(csvDelimiter);

                Map<Integer, Attributes> attributesPerTimeSeries = new HashMap<>(metrics.length);

                for (int i = 1; i < metrics.length; i++) {
                    String metric = metrics[i];
                    String metricOnlyAscii = Normalizer.normalize(metric, Normalizer.Form.NFD);
                    metricOnlyAscii = metric.replaceAll("[^\\x00-\\x7F]", "");
                    Attributes attributes = new Attributes(metricOnlyAscii, fileNameMetaData);

                    //Check if meta data is completely set
                    if (isEmpty(attributes)) {
                        boolean deleted = deleteFile(file, inputStream, reader);
                        LOGGER.info("Attributes contains empty values {}. File {} deleted {}", attributes,
                                file.getName(), deleted);
                        continue;
                    }

                    if (attributes.getMetric().equals(".*")) {
                        boolean deleted = deleteFile(file, inputStream, reader);
                        LOGGER.info("Attributes metric{}. File {} deleted {}", attributes.getMetric(),
                                file.getName(), deleted);
                        continue;
                    }
                    attributesPerTimeSeries.put(i, attributes);
                    tsCounter.incrementAndGet();

                }

                Map<Integer, List<ImportPoint>> dataPoints = new HashMap<>();

                String line;
                while ((line = reader.readLine()) != null) {
                    String[] splits = line.split(csvDelimiter);
                    String date = splits[0];

                    Instant dateObject;
                    if (instantDate) {
                        dateObject = Instant.parse(date);
                    } else if (sdfDate) {
                        dateObject = sdf.parse(date).toInstant();
                    } else {
                        dateObject = Instant.ofEpochMilli(Long.valueOf(date));
                    }

                    for (int column = 1; column < splits.length; column++) {

                        String value = splits[column];
                        double numericValue = nf.parse(value).doubleValue();

                        ImportPoint point = new ImportPoint(dateObject, numericValue);

                        if (!dataPoints.containsKey(column)) {
                            dataPoints.put(column, new ArrayList<>());
                        }
                        dataPoints.get(column).add(point);
                        pointCounter.incrementAndGet();
                    }

                }

                dataPoints.values().forEach(Collections::sort);

                IOUtils.closeQuietly(reader);
                IOUtils.closeQuietly(inputStream);

                dataPoints.forEach((key, importPoints) -> {
                    for (BiConsumer<List<ImportPoint>, Attributes> database : databases) {
                        database.accept(importPoints, attributesPerTimeSeries.get(key));
                    }
                    points.put(attributesPerTimeSeries.get(key), Pair.of(importPoints.get(0).getDate(),
                            importPoints.get(importPoints.size() - 1).getDate()));
                    //write the stats to the file
                    Instant start = importPoints.get(0).getDate();
                    Instant end = importPoints.get(importPoints.size() - 1).getDate();

                    try {
                        writeStatsLine(metricsFileWriter, attributesPerTimeSeries.get(key), start, end);
                    } catch (IOException e) {
                        LOGGER.error("Could not write stats line", e);
                    }
                    LOGGER.info("{} of {} time series imported", counter.incrementAndGet(), tsCounter.get());
                });

            } catch (Exception e) {
                LOGGER.info("Exception while reading points.", e);
            } finally {
                //close all streams
                IOUtils.closeQuietly(reader);
                IOUtils.closeQuietly(inputStream);
            }

        });
    } catch (Exception e) {
        LOGGER.error("Exception occurred during reading points.");
    }
    return Pair.of(tsCounter.get(), pointCounter.get());
}

From source file:com.ikanow.aleph2.data_model.utils.TimeUtils.java

/** Returns a date representing an ISO date (with or without trailing "Z")
 * @param iso_date//www  .  j a v a2s.com
 * @return
 */
public static Validation<String, Date> parseIsoString(final String iso_date) {
    try {
        if (iso_date.endsWith("Z"))
            return Validation.success(Date.from(Instant.parse(iso_date)));
        return Validation.success(Date.from(Instant.parse(iso_date + "Z")));
    } catch (Exception e) {
        return Validation.fail(e.getMessage());
    }
}

From source file:com.linecorp.bot.model.event.CallbackRequestTest.java

@Test
public void testFollow() throws IOException {
    parse("callback/follow.json", callbackRequest -> {
        assertThat(callbackRequest.getEvents()).hasSize(1);
        Event event = callbackRequest.getEvents().get(0);
        assertThat(event).isInstanceOf(FollowEvent.class);
        assertThat(event.getSource()).isInstanceOf(UserSource.class);
        assertThat(event.getSource().getUserId()).isEqualTo("u206d25c2ea6bd87c17655609a1c37cb8");
        assertThat(event.getTimestamp()).isEqualTo(Instant.parse("2016-05-07T13:57:59.859Z"));

        FollowEvent followEvent = (FollowEvent) event;
        assertThat(followEvent.getReplyToken()).isEqualTo("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA");
    });/*from ww  w .j  ava2  s.  co m*/
}

From source file:com.linecorp.bot.model.event.CallbackRequestTest.java

@Test
public void testUnfollow() throws IOException {
    parse("callback/unfollow.json", callbackRequest -> {
        assertThat(callbackRequest.getEvents()).hasSize(1);
        Event event = callbackRequest.getEvents().get(0);
        assertThat(event).isInstanceOf(UnfollowEvent.class);
        assertThat(event.getSource()).isInstanceOf(UserSource.class);
        assertThat(event.getSource().getUserId()).isEqualTo("u206d25c2ea6bd87c17655609a1c37cb8");
        assertThat(event.getTimestamp()).isEqualTo(Instant.parse("2016-05-07T13:57:59.859Z"));
    });/*from   w  w w.  j  a  v a2s . co  m*/
}