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:no.imr.stox.functions.acoustic.PgNapesIO.java

public static void export2(String cruise, String country, String callSignal, String path, String fileName,
        List<DistanceBO> distances, Double groupThickness, Integer freqFilter, String specFilter,
        boolean withZeros) {
    Set<Integer> freqs = distances.stream().flatMap(dist -> dist.getFrequencies().stream())
            .map(FrequencyBO::getFreq).collect(Collectors.toSet());
    if (freqFilter == null && freqs.size() == 1) {
        freqFilter = freqs.iterator().next();
    }//from w  w  w .ja va 2s.co m

    if (freqFilter == null) {
        System.out.println("Multiple frequencies, specify frequency filter as parameter");
        return;
    }
    Integer freqFilterF = freqFilter; // ef.final
    List<String> acList = distances.parallelStream().flatMap(dist -> dist.getFrequencies().stream())
            .filter(fr -> freqFilterF.equals(fr.getFreq())).map(f -> {
                DistanceBO d = f.getDistanceBO();
                LocalDateTime sdt = LocalDateTime.ofInstant(d.getStart_time().toInstant(), ZoneOffset.UTC);
                Double intDist = d.getIntegrator_dist();
                String month = StringUtils.leftPad(sdt.getMonthValue() + "", 2, "0");
                String day = StringUtils.leftPad(sdt.getDayOfMonth() + "", 2, "0");
                String hour = StringUtils.leftPad(sdt.getHour() + "", 2, "0");
                String minute = StringUtils.leftPad(sdt.getMinute() + "", 2, "0");
                String log = Conversion.formatDoubletoDecimalString(d.getLog_start(), "0.0");
                String acLat = Conversion.formatDoubletoDecimalString(d.getLat_start(), "0.000");
                String acLon = Conversion.formatDoubletoDecimalString(d.getLon_start(), "0.000");
                return Stream
                        .of(d.getNation(), d.getPlatform(), d.getCruise(), log, sdt.getYear(), month, day, hour,
                                minute, acLat, acLon, intDist, f.getFreq(), f.getThreshold())
                        .map(o -> o == null ? "" : o.toString()).collect(Collectors.joining("\t")) + "\t";
            }).collect(Collectors.toList());
    String fil1 = path + "/" + fileName + ".txt";
    acList.add(0, Stream.of("Country", "Vessel", "Cruise", "Log", "Year", "Month", "Day", "Hour", "Min",
            "AcLat", "AcLon", "Logint", "Frequency", "Sv_threshold").collect(Collectors.joining("\t")));
    try {
        Files.write(Paths.get(fil1), acList, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException ex) {
        Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex);
    }
    acList.clear();
    // Acoustic values
    distances.stream().filter(d -> d.getPel_ch_thickness() != null)
            .flatMap(dist -> dist.getFrequencies().stream()).filter(fr -> freqFilterF.equals(fr.getFreq()))
            .forEachOrdered(f -> {
                try {
                    Double groupThicknessF = Math.max(f.getDistanceBO().getPel_ch_thickness(), groupThickness);
                    Map<String, Map<Integer, Double>> pivot = f.getSa().stream()
                            .filter(s -> s.getCh_type().equals("P")).map(s -> new SAGroup(s, groupThicknessF))
                            .filter(s -> s.getSpecies() != null
                                    && (specFilter == null || specFilter.equals(s.getSpecies())))
                            // create pivot table: species (dim1) -> depth interval index (dim2) -> sum sa (group aggregator)
                            .collect(Collectors.groupingBy(SAGroup::getSpecies, Collectors.groupingBy(
                                    SAGroup::getDepthGroupIdx, Collectors.summingDouble(SAGroup::sa))));
                    if (pivot.isEmpty() && specFilter != null && withZeros) {
                        pivot.put(specFilter, new HashMap<>());
                    }
                    Integer maxGroupIdx = pivot.entrySet().stream().flatMap(e -> e.getValue().keySet().stream())
                            .max(Integer::compare).orElse(null);
                    if (maxGroupIdx == null) {
                        return;
                    }
                    acList.addAll(pivot.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
                            .flatMap(e -> {
                                return IntStream.range(0, maxGroupIdx + 1).boxed().map(groupIdx -> {
                                    Double chUpDepth = groupIdx * groupThicknessF;
                                    Double chLowDepth = (groupIdx + 1) * groupThicknessF;
                                    Double sa = e.getValue().get(groupIdx);
                                    if (sa == null) {
                                        sa = 0d;
                                    }
                                    String res = null;
                                    if (withZeros || sa > 0d) {
                                        DistanceBO d = f.getDistanceBO();
                                        String log = Conversion.formatDoubletoDecimalString(d.getLog_start(),
                                                "0.0");
                                        LocalDateTime sdt = LocalDateTime
                                                .ofInstant(d.getStart_time().toInstant(), ZoneOffset.UTC);
                                        String month = StringUtils.leftPad(sdt.getMonthValue() + "", 2, "0");
                                        String day = StringUtils.leftPad(sdt.getDayOfMonth() + "", 2, "0");
                                        //String sas = String.format(Locale.UK, "%11.5f", sa);
                                        res = Stream
                                                .of(d.getNation(), d.getPlatform(), d.getCruise(), log,
                                                        sdt.getYear(), month, day, e.getKey(), chUpDepth,
                                                        chLowDepth, sa)
                                                .map(o -> o == null ? "" : o.toString())
                                                .collect(Collectors.joining("\t"));
                                    }
                                    return res;
                                }).filter(s -> s != null);
                            }).collect(Collectors.toList()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

    String fil2 = path + "/" + fileName + "Values.txt";
    acList.add(0, Stream.of("Country", "Vessel", "Cruise", "Log", "Year", "Month", "Day", "Species",
            "ChUppDepth", "ChLowDepth", "SA").collect(Collectors.joining("\t")));
    try {
        Files.write(Paths.get(fil2), acList, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException ex) {
        Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:stroom.pipeline.server.writer.PathCreator.java

public static String replaceTimeVars(String path) {
    // Replace some of the path elements with system variables.
    final ZonedDateTime dateTime = ZonedDateTime.now(ZoneOffset.UTC);
    path = replace(path, "year", dateTime.getYear(), 4);
    path = replace(path, "month", dateTime.getMonthValue(), 2);
    path = replace(path, "day", dateTime.getDayOfMonth(), 2);
    path = replace(path, "hour", dateTime.getHour(), 2);
    path = replace(path, "minute", dateTime.getMinute(), 2);
    path = replace(path, "second", dateTime.getSecond(), 2);
    path = replace(path, "millis", dateTime.toInstant().toEpochMilli(), 3);
    path = replace(path, "ms", dateTime.toInstant().toEpochMilli(), 0);

    return path;//from  www . jav a 2s  . com
}

From source file:no.digipost.api.useragreements.client.response.ResponseUtilsTest.java

@Test
public void parsesDateFromRetryAfterHeader() {
    Clock clock = Clock.fixed(Instant.now().truncatedTo(SECONDS), ZoneOffset.UTC);
    HttpResponse tooManyRequestsErrorResponse = tooManyRequestsResponseWithRetryAfter(
            RFC_1123_DATE_TIME.format(ZonedDateTime.now(clock).plusSeconds(42)));

    Optional<Duration> parsedDuration = ResponseUtils
            .parseDelayDurationOfRetryAfterHeader(tooManyRequestsErrorResponse, clock);
    assertThat(parsedDuration, contains(Duration.ofSeconds(42)));
}

From source file:com.synopsys.integration.hub.bdio.BdioNodeFactory.java

public BdioBillOfMaterials createBillOfMaterials(final String codeLocationName, final String projectName,
        final String projectVersion) {
    final BdioBillOfMaterials billOfMaterials = new BdioBillOfMaterials();
    billOfMaterials.id = String.format("uuid:%s", UUID.randomUUID());
    if (StringUtils.isNotBlank(codeLocationName)) {
        billOfMaterials.spdxName = codeLocationName;
    } else {//from w  w  w  . jav  a 2s . c  om
        billOfMaterials.spdxName = String.format("%s/%s Black Duck I/O Export", projectName, projectVersion);
    }
    billOfMaterials.bdioSpecificationVersion = "1.1.0";

    billOfMaterials.creationInfo = new BdioCreationInfo();
    billOfMaterials.creationInfo.created = Instant.now().atOffset(ZoneOffset.UTC)
            .format(DateTimeFormatter.ISO_INSTANT);
    String version = "UnknownVersion";
    try (InputStream inputStream = getClass().getClassLoader()
            .getResourceAsStream("com/blackducksoftware/integration/hub/bdio/version.txt")) {
        version = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    } catch (final IOException e) {
    }
    billOfMaterials.creationInfo.addSpdxCreator(SpdxCreator.createToolSpdxCreator("IntegrationBdio", version));

    return billOfMaterials;
}

From source file:nl.xs4all.home.freekdb.b52reader.general.Utilities.java

/**
 * Create a zoned date(/time). The time part is empty.
 *
 * @param year       year.// w  ww.  ja v a2 s  .c  o m
 * @param month      month.
 * @param dayOfMonth day of the month.
 * @return <code>ZonedDateTime</code> object.
 */
public static ZonedDateTime createDate(final int year, final Month month, final int dayOfMonth) {
    return ZonedDateTime.of(year, month.getValue(), dayOfMonth, 0, 0, 0, 0, ZoneOffset.UTC);
}

From source file:br.ufac.sion.service.AuditoriaService.java

public Set<AuditoriaDTO> findAllRevisions(FiltroAuditoria filtro) throws NegocioException {
    if (filtro.getDataInicio() != null && filtro.getDataFim() != null) {
        if (!filtro.getDataFim().isAfter(filtro.getDataInicio())) {
            throw new NegocioException("A data de termino deve ser maior que a data de incio!");
        }/* w w  w . j  a  v a 2 s  . c o m*/
    }
    Set<AuditoriaDTO> dtos = new HashSet<>();

    AuditReader reader = AuditReaderFactory.get(em);

    AuditQuery query = reader.createQuery().forRevisionsOfEntity(filtro.getClasse(), false, true);

    if (filtro.getDataInicio() != null) {
        query.add(AuditEntity.revisionProperty("timestamp")
                .gt(Timestamp.from(filtro.getDataInicio().toInstant(ZoneOffset.UTC)).getTime()));
    }
    if (filtro.getDataFim() != null) {
        query.add(AuditEntity.revisionProperty("timestamp")
                .lt(Timestamp.from(filtro.getDataFim().toInstant(ZoneOffset.UTC)).getTime()));
    }

    if (StringUtils.isNotEmpty(filtro.getLogin())) {
        query.add(AuditEntity.revisionProperty("username").ilike(filtro.getLogin(), MatchMode.EXACT));
    }

    if (filtro.getTiposRevisao().length > 0) {
        System.out.println("entra id tipo revisao");
        query.add(AuditEntity.property("REVTYPE").in(filtro.getTiposRevisao()));
    }

    List<Object[]> result = query.getResultList();

    for (Object[] o : result) {
        try {
            //                Object instancia = filtro.getClass().cast(o[0]);
            Object instancia = Class.forName(filtro.getClasse().getName()).cast(o[0]);
            //                Method metodo;
            //                metodo = instancia.getClass().getMethod("getId");
            //                Long id = (Long) metodo.invoke(instancia);

            CustomRevisionEntity revision = (CustomRevisionEntity) o[1];
            RevisionType revisionType = (RevisionType) o[2];

            Instant instant = Instant.ofEpochMilli(revision.getTimestamp());

            AuditoriaDTO dto = new AuditoriaDTO(instancia, revisionType, filtro.getEntidade(), revision);

            dtos.add(dto);
        } catch (Exception ex) {
            throw new NegocioException(ex.getMessage());
        }
    }
    return dtos;
}

From source file:ws.salient.session.SessionModule.java

@Provides
public ZoneId provideZoneId() {
    if (properties.containsKey("zone.offsetId")) {
        return ZoneOffset.of(properties.getProperty("zone.offsetId"));
    } else {//  w  ww .  ja v a2  s  . com
        return ZoneOffset.UTC;
    }
}

From source file:org.apache.hadoop.hive.metastore.HiveProtoEventsCleanerTask.java

/**
 * Compute the expired date partition, using the underlying clock in UTC time.
 *///from  w  w  w  .j a v  a 2s.com
private static void computeExpiredDatePtn(long ttl) {
    // Use UTC date to ensure reader date is same on all timezones.
    LocalDate expiredDate = LocalDateTime.ofEpochSecond((clock.getTime() - ttl) / 1000, 0, ZoneOffset.UTC)
            .toLocalDate();
    expiredDatePtn = "date=" + DateTimeFormatter.ISO_LOCAL_DATE.format(expiredDate);
}

From source file:com.github.akiraly.db4j.uow.UowNotPersistedIfNotNeededTest.java

@Test(timeout = 5000)
public void testUowNotPersistedIfNotNeeded() {
    final String uow1User = "u300";
    Uow uow1 = new Uow(uow1User);

    final Foo foo = new Foo("bar", LocalDateTime.now(ZoneOffset.UTC));

    EntityWithLongId<Foo> fooWithId = transactionTemplate.execute(s -> {
        FooDao fooDao = fooDaoFactory.newDao();
        UowDao uowDao = uowDaoFactory.newDao();
        assertEquals(0, fooDao.count());
        assertEquals(0, uowDao.count());
        EntityWithLongId<Foo> result = fooDao.lazyPersist(foo);
        assertEquals(1, result.getId());
        assertEquals(1, fooDao.count());
        assertEquals(0, uowDao.count());
        return result;
    });// ww  w.  j av  a2s.c o  m

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            FooDao fooDao = fooDaoFactory.newDao();
            assertEquals(1, fooDao.count());
            assertEquals("bar", fooDao.lazyFind(fooWithId.getId()).getEntity().getBar());
            assertEquals(1, fooDao.deleteAll());
        }
    });

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            UowDao uowDao = uowDaoFactory.newDao();
            AuditedFooDao auditedFooDao = auditedFooDaoFactory.newDao(uowDao);
            assertEquals(0, uowDao.count());
            EntityWithLongId<Uow> uowWithId1 = uowDao.lazyPersist(uow1);
            AuditedFoo auditedFoo = new AuditedFoo("bar", uowWithId1);
            EntityWithLongId<AuditedFoo> fooWithId = auditedFooDao.lazyPersist(auditedFoo);
            assertEquals("bar", fooWithId.getEntity().getBar());
            assertEquals(0, uowDao.count());
        }
    });

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            UowDao uowDao = uowDaoFactory.newDao();
            AuditedFooUuidDao auditedFooUuidDao = auditedFooUuidDaoFactory.newDao(uowDao);
            assertEquals(0, uowDao.count());
            EntityWithLongId<Uow> uowWithId1 = uowDao.lazyPersist(uow1);
            AuditedFoo auditedFoo = new AuditedFoo("bar", uowWithId1);
            EntityWithUuid<AuditedFoo> fooWithId = auditedFooUuidDao.lazyPersist(auditedFoo);
            assertEquals("bar", fooWithId.getEntity().getBar());
            assertEquals(0, uowDao.count());
        }
    });
}

From source file:org.opendatakit.briefcase.export.SubmissionParser.java

/**
 * Returns an sorted {@link List} of {@link Path} instances pointing to all the
 * submissions of a form that belong to the given {@link DateRange}.
 * <p>/*from   w w  w  . j a v  a  2  s .c om*/
 * Each file gets briefly parsed to obtain their submission date and use it as
 * the sorting criteria and for filtering.
 */
static List<Path> getListOfSubmissionFiles(FormDefinition formDef, DateRange dateRange,
        SubmissionExportErrorCallback onParsingError) {
    Path instancesDir = formDef.getFormDir().resolve("instances");
    if (!Files.exists(instancesDir) || !Files.isReadable(instancesDir))
        return Collections.emptyList();
    // TODO Migrate this code to Try<Pair<Path, Option<OffsetDate>>> to be able to filter failed parsing attempts
    List<Pair<Path, OffsetDateTime>> paths = new ArrayList<>();
    list(instancesDir).filter(UncheckedFiles::isInstanceDir).forEach(instanceDir -> {
        Path submissionFile = instanceDir.resolve("submission.xml");
        try {
            Optional<OffsetDateTime> submissionDate = readSubmissionDate(submissionFile, onParsingError);
            paths.add(Pair.of(submissionFile,
                    submissionDate.orElse(OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC))));
        } catch (Throwable t) {
            log.error("Can't read submission date", t);
            EventBus.publish(ExportEvent.failureSubmission(formDef, instanceDir.getFileName().toString(), t));
        }
    });
    return paths.parallelStream()
            // Filter out submissions outside the given date range
            .filter(pair -> dateRange.contains(pair.getRight())).map(Pair::getLeft).collect(toList());
}