Example usage for java.time ZoneOffset UTC

List of usage examples for java.time ZoneOffset UTC

Introduction

In this page you can find the example usage for java.time ZoneOffset UTC.

Prototype

ZoneOffset UTC

To view the source code for java.time ZoneOffset UTC.

Click Source Link

Document

The time-zone offset for UTC, with an ID of 'Z'.

Usage

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

/** {@inheritDoc} */
@Override/* w w  w . ja va2  s .c o 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:com.match_tracker.twitter.TwitterSearch.java

protected ZonedDateTime calculatePostedTimeEnd(ZonedDateTime endTime) {
    ZonedDateTime postedTimeEnd = ZonedDateTime.now(ZoneOffset.UTC).minusSeconds(SEARCH_END_DELAY_SECONDS);
    if (postedTimeEnd.isAfter(endTime)) {
        postedTimeEnd = endTime;//from   w  w w.java 2  s.c  o m
    }

    return postedTimeEnd;
}

From source file:com.seleniumtests.util.logging.SeleniumRobotLogger.java

/**
 * Clean result directories//  www. j  ava2 s  . c o  m
 * Delete the directory that will be used to write these test results
 * Delete also directories in "test-output" which are older than 300 minutes. Especially useful when test is requested to write result
 * to a sub-directory of test-output with timestamp (for example). Without this mechanism, results would never be cleaned
 */
private static void cleanResults() {
    // clean output dir
    try {
        FileUtils.deleteDirectory(new File(outputDirectory));
        WaitHelper.waitForSeconds(1);
    } catch (IOException e) {
        // do nothing
    }

    new File(outputDirectory).mkdirs();
    WaitHelper.waitForSeconds(1);

    if (new File(defaultOutputDirectory).exists()) {
        for (File directory : new File(defaultOutputDirectory).listFiles(file -> file.isDirectory())) {
            try {
                if (Files.readAttributes(directory.toPath(), BasicFileAttributes.class).lastAccessTime()
                        .toInstant().atZone(ZoneOffset.UTC).toLocalTime().isBefore(ZonedDateTime.now()
                                .minusMinutes(300).withZoneSameInstant(ZoneOffset.UTC).toLocalTime())) {
                    FileUtils.deleteDirectory(directory);
                }
            } catch (IOException e) {
            }

        }
    }
}

From source file:org.apache.metron.parsers.syslog.BaseSyslogParser.java

@SuppressWarnings("unchecked")
private void setTimestamp(JSONObject message) throws ParseException {
    String timeStampString = (String) message.get(SyslogFieldKeys.HEADER_TIMESTAMP.getField());
    if (!StringUtils.isBlank(timeStampString) && !timeStampString.equals("-")) {
        message.put("timestamp", SyslogUtils.parseTimestampToEpochMillis(timeStampString, deviceClock));
    } else {/*w w w .  ja va  2s.  c  o m*/
        message.put("timestamp", LocalDateTime.now().toEpochSecond(ZoneOffset.UTC));
    }
}

From source file:org.openmhealth.shim.ihealth.mapper.IHealthDataPointMapper.java

/**
 * This method transforms a timestamp from an iHealth response (which is in the form of local time as epoch
 * seconds) into an {@link OffsetDateTime} with the correct date/time and offset. The timestamps provided in
 * iHealth responses are not unix epoch seconds in UTC but instead a unix epoch seconds value that is offset by the
 * time zone of the data point.//from  w w  w .  j av  a  2s  .  co m
 */
protected static OffsetDateTime getDateTimeWithCorrectOffset(Long localTimeAsEpochSeconds,
        ZoneOffset zoneOffset) {

    /*
    iHealth provides the local time of a measurement as if it had occurred in UTC, along with the timezone
    offset where the measurement occurred. To retrieve the correct OffsetDateTime, we must retain the local
    date/time value, but replace the timezone offset.
    */
    return OffsetDateTime.ofInstant(Instant.ofEpochSecond(localTimeAsEpochSeconds), ZoneOffset.UTC)
            .withOffsetSameLocal(zoneOffset);
}

From source file:com.caricah.iotracah.datastore.ignitecache.internal.AbstractHandler.java

public void initializeSequence(String nameOfSequence, Ignite ignite) {

    long currentTime = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
    IgniteAtomicSequence idSequence = ignite.atomicSequence(nameOfSequence, currentTime, true);
    setIdSequence(idSequence);/*  w  w  w  .j av  a 2  s  .c  o m*/
}

From source file:com.synopsys.integration.blackduck.codelocation.signaturescanner.command.ScanPathsUtility.java

public File createSpecificRunOutputDirectory(final File generalOutputDirectory)
        throws BlackDuckIntegrationException {
    final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss-SSS")
            .withZone(ZoneOffset.UTC);
    final String timeStringPrefix = Instant.now().atZone(ZoneOffset.UTC).format(dateTimeFormatter);

    final int uniqueThreadIdSuffix = defaultMultiThreadingId.incrementAndGet();
    return createRunOutputDirectory(generalOutputDirectory, timeStringPrefix,
            Integer.toString(uniqueThreadIdSuffix));
}

From source file:org.cryptomator.frontend.webdav.servlet.DavNode.java

private Optional<DavProperty<?>> lastModifiedDateProperty(DavPropertyName name) {
    return attr.map(BasicFileAttributes::lastModifiedTime) //
            .map(FileTime::toInstant) //
            .map(creationTime -> OffsetDateTime.ofInstant(creationTime, ZoneOffset.UTC)) //
            .map(creationDate -> new DefaultDavProperty<>(name,
                    DateTimeFormatter.RFC_1123_DATE_TIME.format(creationDate)));
}

From source file:serposcope.controllers.google.GoogleSearchController.java

protected String getJsonRanks(Group group, List<GoogleTarget> targets, Run firstRun, Run lastRun,
        int searchId) {

    StringBuilder builder = new StringBuilder("{\"targets\":[");
    for (GoogleTarget target : targets) {
        builder.append("{\"id\":").append(target.getId()).append(",\"name\":\"")
                .append(StringEscapeUtils.escapeJson(target.getName())).append("\"},");
    }//www.j a v  a  2s .co m
    if (builder.charAt(builder.length() - 1) == ',') {
        builder.setCharAt(builder.length() - 1, ']');
    } else {
        builder.append(']');
    }
    builder.append(",\"ranks\":[");

    final int[] maxRank = new int[1];

    googleDB.serp.stream(firstRun.getId(), lastRun.getId(), searchId, (GoogleSerp serp) -> {

        builder.append('[').append(serp.getRunDay().toEpochSecond(ZoneOffset.UTC) * 1000l).append(',');

        // calendar
        builder.append("null").append(",");

        for (GoogleTarget target : targets) {
            int position = UNRANKED;
            for (int i = 0; i < serp.getEntries().size(); i++) {
                if (target.match(serp.getEntries().get(i).getUrl())) {
                    position = i + 1;
                    break;
                }
            }

            builder.append(position == UNRANKED ? "null" : position).append(',');
            if (position != UNRANKED && position > maxRank[0]) {
                maxRank[0] = position;
            }
        }

        if (builder.charAt(builder.length() - 1) == ',') {
            builder.setCharAt(builder.length() - 1, ']');
        }
        builder.append(',');
    });
    if (builder.charAt(builder.length() - 1) == ',') {
        builder.setCharAt(builder.length() - 1, ']');
    } else {
        builder.append(']');
    }

    builder.append(",\"maxRank\":").append(maxRank[0]);
    builder.append("}");

    return builder.toString();
}

From source file:org.apache.metron.dataloads.nonbulk.geo.GeoEnrichmentLoader.java

protected void loadGeoIpDatabase(CommandLine cli) throws IOException {
    // Retrieve the database file
    System.out.println("Retrieving GeoLite2 archive");
    String url = GeoEnrichmentOptions.GEO_URL.get(cli,
            "http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz");
    String tmpDir = GeoEnrichmentOptions.TMP_DIR.get(cli, "/tmp") + "/"; // Make sure there's a file separator at the end
    File localGeoFile = downloadGeoFile(url, tmpDir);
    // Want to delete the tar in event of failure
    localGeoFile.deleteOnExit();//w  w w  .j  a  v  a  2  s. c o  m
    System.out.println("GeoIP files downloaded successfully");

    // Push the file to HDFS and update Configs to ensure clients get new view
    String zookeeper = GeoEnrichmentOptions.ZK_QUORUM.get(cli);
    long millis = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli();
    String hdfsLoc = GeoEnrichmentOptions.REMOTE_DIR.get(cli, "/apps/metron/geo/" + millis);
    System.out.println("Putting GeoLite2 file into HDFS at: " + hdfsLoc);

    // Put into HDFS
    Path srcPath = new Path(localGeoFile.getAbsolutePath());
    Path dstPath = new Path(hdfsLoc);
    putDbFile(srcPath, dstPath);
    pushConfig(srcPath, dstPath, zookeeper);

    System.out.println("GeoLite2 file placement complete");
    System.out.println("Successfully created and updated new GeoIP information");
}