Example usage for java.time.format DateTimeFormatter format

List of usage examples for java.time.format DateTimeFormatter format

Introduction

In this page you can find the example usage for java.time.format DateTimeFormatter format.

Prototype

public String format(TemporalAccessor temporal) 

Source Link

Document

Formats a date-time object using this formatter.

Usage

From source file:org.hawkular.alerter.elasticsearch.ElasticsearchQuery.java

public String formatTimestamp(Date date) {
    String definedPattern = properties.get(TIMESTAMP_PATTERN);
    if (definedPattern != null) {
        DateTimeFormatter formatter = null;
        try {//from  w w  w  .jav a2s  . c o  m
            formatter = DateTimeFormatter.ofPattern(definedPattern);
            return formatter.format(ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), UTC));
        } catch (Exception e) {
            log.debugf("Not able to format [%s] with pattern [%s]", date, formatter);
        }
    }
    return DEFAULT_DATE_FORMATS[0].format(ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), UTC));
}

From source file:com.bdb.weather.display.windrose.WindRosePane.java

/**
 * Load the wind rose data./*ww w.  j  a  v  a  2s .com*/
 * 
 * @param data The data
 */
public void loadData(WindRoseData data) {
    windRosePlot.clearCornerTextItems();

    if (data == null) {
        windRosePlot.setDataset((WindRoseData) null);
        return;
    }

    init(data.getSpeedBins());

    DateTimeFormatter sdf = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
    windRosePlot.setDataset(data);
    float calmPercent = ((float) data.getCalmDuration().getSeconds()
            / (float) data.getTotalDuration().getSeconds()) * 100.0f;
    windRosePlot.addCornerTextItem(String.format("Calm: %.1f%%", calmPercent));
    calmField.setText(String.format("%.1f", calmPercent));
    timeField.setText(sdf.format(data.getTime()));

    Speed maxSpeed = new Speed(0.0);
    Heading maxSpeedHeading = null;
    double speedSum = 0.0;

    //
    // Calculate annotation data
    //
    for (int i = 0; i < data.getNumSlices(); i++) {
        WindSlice slice = data.getSlice(i);

        Heading heading = Heading.headingForSlice(slice.getHeadingIndex(), data.getNumSlices());

        if (slice.getMaxSpeed().get() > maxSpeed.get()) {
            maxSpeed = slice.getMaxSpeed();
            maxSpeedHeading = heading;
        }

        speedSum += slice.getAvgSpeed().get() * slice.getSliceDuration().getSeconds();
    }

    //
    // Add annotations to the panel
    //
    if (maxSpeedHeading != null) {
        windRosePlot
                .addCornerTextItem(String.format("Max: %s@%s", maxSpeedHeading.getCompassLabel(), maxSpeed));
        Speed avgSpeed = new Speed(speedSum / data.getTotalDuration().getSeconds());
        windRosePlot.addCornerTextItem(String.format("Avg: %s", avgSpeed));
    }

    dataTable.setItems(FXCollections.observableList(data.getSlices()));
}

From source file:org.deeplearning4j.patent.LocalTraining.java

/**
 * JCommander entry point//  w w w .  j av  a 2 s.  c  om
 *
 * @param args
 * @throws Exception
 */
protected void entryPoint(String[] args) throws Exception {
    JCommanderUtils.parseArgs(this, args);
    File resultFile = new File(outputPath, "results.txt"); //Output will be written here
    Preconditions.checkArgument(convergenceEvalFrequencyBatches > 0,
            "convergenceEvalFrequencyBatches must be positive: got %s", convergenceEvalFrequencyBatches);

    Nd4j.getMemoryManager().setAutoGcWindow(15000);

    // Prepare neural net
    ComputationGraph net = new ComputationGraph(NetworkConfiguration.getConf());
    net.init();
    net.setListeners(new PerformanceListener(listenerFrequency, true));
    log.info("Parameters: {}", net.params().length());

    //Write configuration
    writeConfig();

    // Train neural net
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    int subsetCount = 0;
    boolean firstSave = true;
    long overallStart = System.currentTimeMillis();
    boolean exit = false;
    for (int epoch = 0; epoch < numEpochs; epoch++) {
        // Training
        log.info("epoch {} training begin: {}", epoch + 1, dtf.format(LocalDateTime.now()));
        // Prepare training data. Note we'll get this again for each epoch in case we are using early termination iterator
        // plus randomization. This is to ensure consistency between epochs
        DataSetIterator trainData = getDataIterator(dataDir, true, totalExamplesTrain, batchSize, rngSeed);

        //For convergence purposes: want to split into subsets, time training on each subset, an evaluate
        while (trainData.hasNext()) {
            subsetCount++;
            log.info("Starting training: epoch {} of {}, subset {} ({} minibatches)", (epoch + 1), numEpochs,
                    subsetCount, convergenceEvalFrequencyBatches);
            DataSetIterator subset = new EarlyTerminationDataSetIterator(trainData,
                    convergenceEvalFrequencyBatches);
            int itersBefore = net.getIterationCount();
            long start = System.currentTimeMillis();
            net.fit(subset);
            long end = System.currentTimeMillis();
            int iterAfter = net.getIterationCount();

            //Save model
            if (saveConvergenceNets) {
                String fileName = "net_" + System.currentTimeMillis() + "_epoch" + epoch + "_subset"
                        + subsetCount + ".zip";
                String outpath = FilenameUtils.concat(outputPath, "nets/" + fileName);
                File f = new File(outpath);
                if (firstSave) {
                    firstSave = false;
                    f.getParentFile().mkdirs();
                }
                ModelSerializer.writeModel(net, f, true);
                log.info("Saved network to {}", outpath);
            }

            DataSetIterator test = getDataIterator(dataDir, false, totalExamplesTrain, batchSize, rngSeed);
            long startEval = System.currentTimeMillis();
            IEvaluation[] evals = net.doEvaluation(test, new Evaluation(), new ROCMultiClass());
            long endEval = System.currentTimeMillis();

            StringBuilder sb = new StringBuilder();
            Evaluation e = (Evaluation) evals[0];
            ROCMultiClass r = (ROCMultiClass) evals[1];
            sb.append("epoch ").append(epoch + 1).append(" of ").append(numEpochs).append(" subset ")
                    .append(subsetCount).append(" subsetMiniBatches ").append(iterAfter - itersBefore) //Note: "end of epoch" effect - may be smaller than subset size
                    .append(" trainMS ").append(end - start).append(" evalMS ").append(endEval - startEval)
                    .append(" accuracy ").append(e.accuracy()).append(" f1 ").append(e.f1()).append(" AvgAUC ")
                    .append(r.calculateAverageAUC()).append(" AvgAUPRC ").append(r.calculateAverageAUCPR())
                    .append("\n");

            FileUtils.writeStringToFile(resultFile, sb.toString(), Charset.forName("UTF-8"), true); //Append new output to file
            saveEvaluation(false, evals);
            log.info("Evaluation: {}", sb.toString());

            if (maxTrainingTimeMin > 0
                    && (System.currentTimeMillis() - overallStart) / 60000 > maxTrainingTimeMin) {
                log.info("Exceeded max training time of {} minutes - terminating", maxTrainingTimeMin);
                exit = true;
                break;
            }
        }
        if (exit)
            break;
    }

    File dir = new File(outputPath, "trainedModel.bin");
    net.save(dir, true);
}

From source file:org.openhab.binding.ntp.test.NtpOSGiTest.java

private void assertFormat(String initialDate, String formatPattern) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatPattern);

    final ZonedDateTime date;
    date = ZonedDateTime.parse(initialDate, formatter);

    String formattedDate = formatter.format(date);

    assertEquals(initialDate, formattedDate);
}

From source file:hash.HashFilesController.java

/**
 * Initializes the controller class./*  w w w  .  ja v a 2s .co m*/
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    SessionFactory sFactory = HibernateUtilities.getSessionFactory();
    Session session = sFactory.openSession();
    session.beginTransaction();

    Query query = session.createQuery("from Checksum where caseFile = " + CreateCaseController.getCaseNumber());
    List<Checksum> checksumsForCase = (List<Checksum>) query.list();

    checksumIDColumn.setCellValueFactory(new PropertyValueFactory("checksumID"));
    fileNameColumn.setCellValueFactory(new PropertyValueFactory("fileName"));
    filePathColumn.setCellValueFactory(new PropertyValueFactory("filePath"));
    dateTimeGeneratedColumn.setCellValueFactory(new PropertyValueFactory("dateTimeGenerated"));

    DateTimeFormatter format = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT);
    dateTimeGeneratedColumn.setCellFactory(column -> {
        return new TableCell<Checksum, LocalDateTime>() {
            @Override
            protected void updateItem(LocalDateTime item, boolean empty) {
                super.updateItem(item, empty);

                if (item == null || empty) {
                    setText(null);
                    setStyle("");
                } else {
                    // Format date.
                    setText(format.format(item));
                }
            }
        };
    });

    md5Column.setCellValueFactory(new PropertyValueFactory("MD5Value"));

    checksumTableView.getItems().addAll(checksumsForCase);
    session.getTransaction().commit();
    session.close();

}

From source file:jgnash.report.pdf.Report.java

private String formatValue(final Object value, final int column, final AbstractReportTableModel reportModel) {
    if (value == null) {
        return " ";
    }//  w  ww.j av a  2s  .  c om

    final ColumnStyle columnStyle = reportModel.getColumnStyle(column);

    switch (columnStyle) {
    case TIMESTAMP:
        final DateTimeFormatter dateTimeFormatter = DateUtils.getShortDateTimeFormatter();
        return dateTimeFormatter.format((LocalDateTime) value);
    case SHORT_DATE:
        final DateTimeFormatter dateFormatter = DateUtils.getShortDateFormatter();
        return dateFormatter.format((LocalDate) value);
    case SHORT_AMOUNT:
        final NumberFormat shortNumberFormat = NumericFormats
                .getShortCommodityFormat(reportModel.getCurrency());
        return shortNumberFormat.format(value);
    case BALANCE:
    case BALANCE_WITH_SUM:
    case BALANCE_WITH_SUM_AND_GLOBAL:
    case AMOUNT_SUM:
        final NumberFormat numberFormat = NumericFormats.getFullCommodityFormat(reportModel.getCurrency());
        return numberFormat.format(value);
    case PERCENTAGE:
        final NumberFormat percentageFormat = NumericFormats.getPercentageFormat();
        return percentageFormat.format(value);
    case QUANTITY:
        final NumberFormat qtyFormat = NumericFormats
                .getFixedPrecisionFormat(MathConstants.SECURITY_QUANTITY_ACCURACY);
        return qtyFormat.format(value);
    default:
        return value.toString();
    }
}

From source file:org.fcrepo.integration.http.api.FedoraVersioningIT.java

@Test
public void testGetLDPRSMementoHeaders() throws Exception {
    final DateTimeFormatter FMT = RFC_1123_DATE_TIME.withZone(ZoneId.of("UTC"));
    createVersionedContainer(id);//from  ww w.  j av a2 s  . com

    final String memento1 = FMT.format(ISO_INSTANT.parse("2001-06-10T16:41:00Z", Instant::from));
    final String version1Uri = createLDPRSMementoWithExistingBody(memento1);
    final HttpGet getRequest = new HttpGet(version1Uri);

    try (final CloseableHttpResponse response = execute(getRequest)) {
        assertMementoDatetimeHeaderMatches(response, memento1);
        checkForLinkHeader(response, MEMENTO_TYPE, "type");
        checkForLinkHeader(response, subjectUri, "original");
        checkForLinkHeader(response, subjectUri, "timegate");
        checkForLinkHeader(response, subjectUri + "/" + FCR_VERSIONS, "timemap");
        checkForLinkHeader(response, RESOURCE.toString(), "type");
        assertNoLinkHeader(response, VERSIONED_RESOURCE.toString(), "type");
        assertNoLinkHeader(response, VERSIONING_TIMEMAP_TYPE.toString(), "type");
        assertNoLinkHeader(response, version1Uri + "/" + FCR_ACL, "acl");
    }
}

From source file:org.fcrepo.integration.http.api.FedoraVersioningIT.java

@Test
public void testDatetimeNegotiationNoMementos() throws Exception {
    final CloseableHttpClient customClient = createClient(true);
    final DateTimeFormatter FMT = RFC_1123_DATE_TIME.withZone(ZoneId.of("UTC"));

    createVersionedContainer(id);//from w  ww . ja va  2s.  c om
    final String requestDatetime = FMT.format(ISO_INSTANT.parse("2017-01-12T00:00:00Z", Instant::from));
    final HttpGet getMemento = getObjMethod(id);
    getMemento.addHeader(ACCEPT_DATETIME, requestDatetime);

    try (final CloseableHttpResponse response = customClient.execute(getMemento)) {
        assertEquals("Did not get NOT_FOUND response", NOT_FOUND.getStatusCode(), getStatus(response));
        assertNull("Did not expect a Location header", response.getFirstHeader(LOCATION));
        assertNotEquals("Did not get Content-Length > 0", 0,
                response.getFirstHeader(CONTENT_LENGTH).getValue());
    }
}

From source file:org.fcrepo.integration.http.api.FedoraVersioningIT.java

@Test
public void testDatetimeNegotiationLDPRv() throws Exception {
    final CloseableHttpClient customClient = createClient(true);
    final DateTimeFormatter FMT = RFC_1123_DATE_TIME.withZone(ZoneId.of("UTC"));

    createVersionedContainer(id);//from ww w .jav a2 s .c o  m
    final String memento1 = FMT.format(ISO_INSTANT.parse("2017-06-10T11:41:00Z", Instant::from));
    final String version1Uri = createLDPRSMementoWithExistingBody(memento1);
    final String memento2 = FMT.format(ISO_INSTANT.parse("2016-06-17T11:41:00Z", Instant::from));
    final String version2Uri = createLDPRSMementoWithExistingBody(memento2);

    final String request1Datetime = FMT.format(ISO_INSTANT.parse("2017-01-12T00:00:00Z", Instant::from));
    final HttpGet getMemento = getObjMethod(id);
    getMemento.addHeader(ACCEPT_DATETIME, request1Datetime);

    try (final CloseableHttpResponse response = customClient.execute(getMemento)) {
        assertEquals("Did not get FOUND response", FOUND.getStatusCode(), getStatus(response));
        assertNoMementoDatetimeHeaderPresent(response);
        assertEquals("Did not get Location header", version2Uri, response.getFirstHeader(LOCATION).getValue());
        assertEquals("Did not get Content-Length == 0", "0",
                response.getFirstHeader(CONTENT_LENGTH).getValue());
    }

    final String request2Datetime = FMT.format(ISO_INSTANT.parse("2018-01-10T00:00:00Z", Instant::from));
    final HttpGet getMemento2 = getObjMethod(id);
    getMemento2.addHeader(ACCEPT_DATETIME, request2Datetime);

    try (final CloseableHttpResponse response = customClient.execute(getMemento2)) {
        assertEquals("Did not get FOUND response", FOUND.getStatusCode(), getStatus(response));
        assertNoMementoDatetimeHeaderPresent(response);
        assertEquals("Did not get Location header", version1Uri, response.getFirstHeader(LOCATION).getValue());
        assertEquals("Did not get Content-Length == 0", "0",
                response.getFirstHeader(CONTENT_LENGTH).getValue());
    }
}

From source file:org.fcrepo.integration.http.api.FedoraVersioningIT.java

@Test
public void testGetLDPNRMementoHeaders() throws Exception {
    final DateTimeFormatter FMT = RFC_1123_DATE_TIME.withZone(ZoneId.of("UTC"));
    createVersionedBinary(id, "text/plain", "This is some versioned content");

    final String memento1 = FMT.format(ISO_INSTANT.parse("2001-06-10T16:41:00Z", Instant::from));
    final String version1Uri = createLDPNRMementoWithExistingBody(memento1);
    final HttpGet getRequest = new HttpGet(version1Uri);

    try (final CloseableHttpResponse response = execute(getRequest)) {
        assertMementoDatetimeHeaderMatches(response, memento1);
        checkForLinkHeader(response, MEMENTO_TYPE, "type");
        checkForLinkHeader(response, subjectUri, "original");
        checkForLinkHeader(response, subjectUri, "timegate");
        checkForLinkHeader(response, subjectUri + "/" + FCR_VERSIONS, "timemap");
        checkForLinkHeader(response, NON_RDF_SOURCE.toString(), "type");
        assertNoLinkHeader(response, VERSIONED_RESOURCE.toString(), "type");
        assertNoLinkHeader(response, VERSIONING_TIMEMAP_TYPE.toString(), "type");
        assertNoLinkHeader(response, version1Uri + "/" + FCR_ACL, "acl");
    }/*  w  w  w  .  j a  v  a 2s. c o  m*/
}