Example usage for java.time ZoneId systemDefault

List of usage examples for java.time ZoneId systemDefault

Introduction

In this page you can find the example usage for java.time ZoneId systemDefault.

Prototype

public static ZoneId systemDefault() 

Source Link

Document

Gets the system default time-zone.

Usage

From source file:it.tidalwave.northernwind.core.impl.model.DefaultRequestLocaleManager.java

/*******************************************************************************************************************
 *
 * {@inheritDoc}/*from  w  ww  . ja  va  2s . c  o m*/
 *
 ******************************************************************************************************************/
@Override
@Nonnull
public DateTimeFormatter getDateTimeFormatter() {
    return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(getLocales().get(0))
            .withZone(ZoneId.systemDefault());
}

From source file:com.gigglinggnus.controllers.CheckinController.java

private JSONArray getAppointments(User user, Term term, Clock clk) {
    Instant now = Instant.now(clk);
    //return a list of appointments in this term
    List<Appointment> appts = user.getAppointments().stream().filter(appt -> appt.getTerm().equals(term))
            .filter(appt -> !appt.isStudentCheckedIn()).collect(Collectors.toList());
    //sorted by distance to current time
    Collections.sort(appts,// w w  w  .  ja  v  a 2 s. c  o m
            (Appointment a1, Appointment a2) -> Duration.between(now, a1.getInterval().getStart()).abs()
                    .compareTo(Duration.between(now, a1.getInterval().getStart()).abs()));

    JSONArray json = new JSONArray();

    for (Appointment appt : appts) {
        String examId = appt.getExam().getExamId();
        String startTime = LocalDateTime.from(appt.getInterval().getStart().atZone(ZoneId.systemDefault()))
                .toString();
        String seatNum = appt.prettySeat();
        //write JSON
        JSONObject elem = new JSONObject();
        elem.put("exam", examId);
        elem.put("start", startTime);
        elem.put("seat", seatNum);
        json.put(elem);
    }
    return json;
}

From source file:me.adaptive.che.infrastructure.api.MetricsModule.java

/**
 * Returns the number of user's builds per platform or the total number of builds
 *
 * @param platform Platform: ios, android or total
 * @return Return the number of builds/*from w w w.ja  v a  2  s .  c o  m*/
 * @throws NotFoundException When the platform is not found
 */
@ApiOperation(value = "Build metrics", notes = "Returns the build metrics information requested", response = Map.class, position = 2)
@ApiResponses({ @ApiResponse(code = 404, message = "Platform Not Found") })
@GET
@Path("/build/{metric}/{aggregation}/{startDate}/{endDate}")
@GenerateLink(rel = "build metrics")
@Produces(APPLICATION_JSON)
public Map<String, Double> buildMetrics(
        @ApiParam(value = "platform", required = false) @QueryParam("platform") String platform,
        @ApiParam(value = "user_id", required = false) @QueryParam("user_id") String user_id,
        @ApiParam(value = "metric", required = true) @PathParam("metric") String metric,
        @ApiParam(value = "aggregation", required = true) @PathParam("aggregation") String aggregation,
        @ApiParam(value = "startDate", required = true) @PathParam("startDate") long startDate,
        @ApiParam(value = "endDate", required = true) @PathParam("endDate") long endDate)
        throws NotFoundException {

    Map<String, Double> map = new TreeMap<>();
    Map<String, Double> dayOccurrences = new TreeMap<>();

    LocalDate start = new Date(startDate).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    LocalDate end = new Date(endDate).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

    // Fill the map with the values of the x-axis
    switch (aggregation) {
    case "sum":
        map.put("sum", 0.0);
        break;
    case "day":
        for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
            map.put(date.toString(), 0.0);
            dayOccurrences.put(date.toString(), 0.0);
        }
        break;
    default:
        throw new NotFoundException(
                "The aggregation {" + aggregation + "} is not found in the system. " + "Should be: [sum,day]");
    }

    Set<BuildRequestEntity> values;

    if (user_id != null && platform != null) {
        Optional<UserEntity> user = userRepository.findByUserId(user_id);
        values = buildRequestRepository.findByPlatformAndRequesterAndStartTimeBetween(platform, user.get(),
                new Date(startDate), new Date(endDate));
    } else if (user_id == null && platform != null) {
        values = buildRequestRepository.findByPlatformAndStartTimeBetween(platform, new Date(startDate),
                new Date(endDate));
    } else if (user_id != null && platform == null) {
        Optional<UserEntity> user = userRepository.findByUserId(user_id);
        values = buildRequestRepository.findByRequesterAndStartTimeBetween(user.get(), new Date(startDate),
                new Date(endDate));
    } else {
        values = buildRequestRepository.findByStartTimeBetween(new Date(startDate), new Date(endDate));
    }

    // Depending on the metric
    switch (metric) {
    case "total":

        switch (aggregation) {
        case "sum":
            map.put("sum", (double) values.size());
            break;
        case "day":
            for (BuildRequestEntity event : values) {
                String eventDate = event.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()
                        .toString();
                map.put(eventDate, map.get(eventDate) + 1);
            }
            break;
        default:
            throw new NotFoundException("The aggregation {" + aggregation + "} is not found in the system. "
                    + "Should be: [sum,day]");
        }
        break;
    case "time":

        switch (aggregation) {
        case "sum":
            double sum = 0;
            for (BuildRequestEntity event : values) {
                System.out.println(event.getEndTime().getTime() - event.getStartTime().getTime() + "ms");
                sum += (event.getEndTime().getTime() - event.getStartTime().getTime());
            }
            if (values.size() > 0) {
                map.put("sum", sum / values.size());
            }
            break;
        case "day":
            for (BuildRequestEntity event : values) {
                String eventDate = event.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()
                        .toString();
                map.put(eventDate,
                        map.get(eventDate) + (event.getEndTime().getTime() - event.getStartTime().getTime()));
                dayOccurrences.put(eventDate, dayOccurrences.get(eventDate) + 1);
            }

            for (Map.Entry<String, Double> entry : map.entrySet()) {
                if (dayOccurrences.get(entry.getKey()) > 0) {
                    map.put(entry.getKey(), (entry.getValue() / dayOccurrences.get(entry.getKey())));
                }
            }

            break;
        default:
            throw new NotFoundException("The aggregation {" + aggregation + "} is not found in the system. "
                    + "Should be: [sum,day]");
        }
        break;
    default:
        throw new NotFoundException(
                "The metric {" + metric + "} is not found in the system. Should be: [total,time]");
    }

    return map;
}

From source file:alfio.model.modification.EventWithStatistics.java

@Override
public int compareTo(EventWithStatistics o) {
    CompareToBuilder builder = new CompareToBuilder();
    return builder.append(isExpired(), o.isExpired())
            .append(getBegin().withZoneSameInstant(ZoneId.systemDefault()),
                    o.getBegin().withZoneSameInstant(ZoneId.systemDefault()))
            .build();//from  w ww . j  ava 2s . c om
}

From source file:edu.zipcloud.cloudstreetmarket.core.entities.Chart.java

public boolean isExpired(int ttlInMinutes) {
    Instant now = new Date().toInstant();
    LocalDateTime localNow = now.atZone(ZoneId.systemDefault()).toLocalDateTime();
    LocalDateTime localLastUpdate = DateUtils.addMinutes(lastUpdate, ttlInMinutes).toInstant()
            .atZone(ZoneId.systemDefault()).toLocalDateTime();
    return localLastUpdate.isBefore(localNow);
}

From source file:org.nuxeo.ecm.blob.azure.TestAzureBinaryManager.java

@Test
public void testSigning() throws IOException, URISyntaxException, StorageException, InvalidKeyException {
    CloudBlobContainer container = binaryManager.container;
    Binary binary = binaryManager.getBinary(Blobs.createBlob(CONTENT));
    assertNotNull(binary);//from  w ww  .j a v  a  2 s. c o m

    CloudBlockBlob blockBlobReference = container.getBlockBlobReference(CONTENT_MD5);
    SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
    policy.setPermissionsFromString("r");

    // rscd content-dispositoon
    // rsct content-type

    Instant endDateTime = LocalDateTime.now().plusHours(1).atZone(ZoneId.systemDefault()).toInstant();
    policy.setSharedAccessExpiryTime(Date.from(endDateTime));

    SharedAccessBlobHeaders headers = new SharedAccessBlobHeaders();
    headers.setContentDisposition("attachment; filename=\"blabla.txt\"");
    headers.setContentType("text/plain");

    String something = blockBlobReference.generateSharedAccessSignature(policy, headers, null);
    System.out.println(something);

    CloudBlockBlob blob = new CloudBlockBlob(blockBlobReference.getUri(),
            new StorageCredentialsSharedAccessSignature(something));

    System.out.println(blob.getQualifiedUri());
}

From source file:com.bdb.weather.display.day.DayWindPane.java

@Override
protected void loadDataSeries(List<HistoricalRecord> list) {
    super.loadDataSeries(list);
    speedSeries.clear();//from   w ww  .  j av  a2s .  c  o m
    gustSeries.clear();

    int n = 0;

    for (HistoricalRecord r : list) {
        Wind w = r.getAvgWind();

        if (w != null) {
            Minute period = new Minute(Date.from(r.getTime().atZone(ZoneId.systemDefault()).toInstant()));
            WindSeriesDataItem item = new WindSeriesDataItem(period, w.getSpeed().get(),
                    w.getDirection().get());

            speedSeries.add(item);

            w = r.getWindGust();

            if (w != null && w.getSpeed().get() > 0.0) {
                period = new Minute(TimeUtils.localDateTimeToDate(r.getTime()));
                gustSeries.add(period, w.getSpeed().get());
            }
        }
        n++;
    }

    dataset.removeAllSeries();
    dataset.addSeries(speedSeries);

    if (!gustSeries.isEmpty())
        dataset.addSeries(gustSeries);
}

From source file:org.wallride.service.PostService.java

@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void updatePostViews() {
    LocalDateTime now = LocalDateTime.now();
    Set<JobExecution> jobExecutions = jobExplorer.findRunningJobExecutions("updatePostViewsJob");
    for (JobExecution jobExecution : jobExecutions) {
        LocalDateTime startTime = LocalDateTime.ofInstant(jobExecution.getStartTime().toInstant(),
                ZoneId.systemDefault());
        Duration d = Duration.between(now, startTime);
        if (Math.abs(d.toMinutes()) == 0) {
            logger.info("Skip processing because the job is running.");
            return;
        }/*from   ww  w  . j ava  2 s.c o  m*/
    }

    JobParameters params = new JobParametersBuilder()
            .addDate("now", Date.from(now.atZone(ZoneId.systemDefault()).toInstant())).toJobParameters();
    try {
        jobLauncher.run(updatePostViewsJob, params);
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:org.openlmis.fulfillment.web.OrderControllerTest.java

@Before
public void setUp() {
    when(dateHelper.getCurrentDateTimeWithSystemZone())
            .thenReturn(ZonedDateTime.of(2015, 5, 7, 10, 5, 20, 500, ZoneId.systemDefault()));

    OrderNumberConfiguration orderNumberConfiguration = new OrderNumberConfiguration("prefix", false, false,
            false);//from  w w w . j  a va  2  s .  c o m

    when(orderService.createOrder(orderDto, lastUpdaterId)).thenReturn(order);
    when(programReferenceDataService.findOne(any())).thenReturn(programDto);
    when(authentication.isClientOnly()).thenReturn(true);
    when(orderNumberConfigurationRepository.findAll()).thenReturn(Lists.newArrayList(orderNumberConfiguration));
    when(extensionManager.getExtension(any(), any())).thenReturn(orderNumberGenerator);
    when(orderNumberGenerator.generate(any())).thenReturn(ORDER_NUMBER);
    when(proofOfDeliveryRepository.save(any(ProofOfDelivery.class))).thenReturn(proofOfDelivery);
    when(orderDtoBuilder.build(order)).thenReturn(orderDto);

    when(shipmentService.save(any(Shipment.class)))
            .thenAnswer(invocation -> invocation.getArgumentAt(0, Shipment.class));

    orderDto.setUpdaterId(lastUpdaterId);

    ReflectionTestUtils.setField(exporterBuilder, "serviceUrl", SERVICE_URL);
    ReflectionTestUtils.setField(exporterBuilder, "facilities", facilities);
    ReflectionTestUtils.setField(exporterBuilder, "programs", programs);
    ReflectionTestUtils.setField(exporterBuilder, "periods", periods);
    ReflectionTestUtils.setField(exporterBuilder, "users", users);
}

From source file:net.straylightlabs.archivo.net.MindCommandRecordingSearch.java

private LocalDateTime parseUTCDateTime(String utcDateTime) {
    ZonedDateTime utc = ZonedDateTime.parse(utcDateTime + " +0000",
            DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss ZZ"));
    return utc.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
}