Example usage for java.time.temporal ChronoUnit DAYS

List of usage examples for java.time.temporal ChronoUnit DAYS

Introduction

In this page you can find the example usage for java.time.temporal ChronoUnit DAYS.

Prototype

ChronoUnit DAYS

To view the source code for java.time.temporal ChronoUnit DAYS.

Click Source Link

Document

Unit that represents the concept of a day.

Usage

From source file:com.orange.cepheus.broker.controller.NgsiControllerTest.java

@Test
public void postNewSubscribeContext() throws Exception {

    SubscribeContext subscribeContext = createSubscribeContextTemperature();
    Subscription subscription = new Subscription("12345678", Instant.now().plus(1, ChronoUnit.DAYS),
            subscribeContext);// ww  w  .  j  av a  2 s.c  o  m
    when(subscriptions.addSubscription(any())).thenReturn("12345678");
    when(subscriptions.getSubscription("12345678")).thenReturn(subscription);

    mockMvc.perform(post("/v1/subscribeContext").content(json(mapper, subscribeContext))
            .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.subscribeResponse.subscriptionId").value("12345678"))
            .andExpect(MockMvcResultMatchers.jsonPath("$.subscribeResponse.duration").value("P1M"));

    verify(subscriptions, atLeastOnce()).addSubscription(any());
    verify(subscriptions, atLeastOnce()).getSubscription("12345678");
}

From source file:com.orange.cepheus.broker.controller.NgsiControllerTest.java

@Test
public void postNewSubscribeContextWithNoDuration() throws Exception {

    SubscribeContext subscribeContext = createSubscribeContextTemperature();
    subscribeContext.setDuration(null);/*from   w ww . ja v  a2  s  .c om*/

    SubscribeContext subscribeContextInSubscription = createSubscribeContextTemperature();
    Subscription subscription = new Subscription("12345678", Instant.now().plus(1, ChronoUnit.DAYS),
            subscribeContextInSubscription);
    when(subscriptions.addSubscription(any())).thenReturn("12345678");
    when(subscriptions.getSubscription("12345678")).thenReturn(subscription);

    mockMvc.perform(post("/v1/subscribeContext").content(json(mapper, subscribeContext))
            .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.subscribeResponse.subscriptionId").value("12345678"))
            .andExpect(MockMvcResultMatchers.jsonPath("$.subscribeResponse.duration").value("P1M"));

    verify(subscriptions, atLeastOnce()).addSubscription(any());
    verify(subscriptions, atLeastOnce()).getSubscription("12345678");
}

From source file:alfio.manager.TicketReservationManager.java

void sendReminderForOfflinePaymentsToEventManagers() {
    eventRepository.findAllActives(ZonedDateTime.now(Clock.systemUTC())).stream().filter(event -> {
        ZonedDateTime dateTimeForEvent = ZonedDateTime.now(event.getZoneId());
        return dateTimeForEvent.truncatedTo(ChronoUnit.HOURS).getHour() == 5; //only for the events at 5:00 local time
    }).forEachOrdered(event -> {/*w w w  .j  a v a2  s  . c  o  m*/
        ZonedDateTime dateTimeForEvent = ZonedDateTime.now(event.getZoneId()).truncatedTo(ChronoUnit.DAYS)
                .plusDays(1);
        List<TicketReservationInfo> reservations = ticketReservationRepository
                .findAllOfflinePaymentReservationWithExpirationBefore(dateTimeForEvent, event.getId());
        log.info("for event {} there are {} pending offline payments to handle", event.getId(),
                reservations.size());
        if (!reservations.isEmpty()) {
            Organization organization = organizationRepository.getById(event.getOrganizationId());
            List<String> cc = notificationManager.getCCForEventOrganizer(event);
            String subject = String.format(
                    "There are %d pending offline payments that will expire in event: %s", reservations.size(),
                    event.getDisplayName());
            String baseUrl = configurationManager
                    .getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), BASE_URL));
            Map<String, Object> model = TemplateResource
                    .prepareModelForOfflineReservationExpiringEmailForOrganizer(event, reservations, baseUrl);
            notificationManager.sendSimpleEmail(event, organization.getEmail(), cc, subject,
                    () -> templateManager.renderTemplate(event,
                            TemplateResource.OFFLINE_RESERVATION_EXPIRING_EMAIL_FOR_ORGANIZER, model,
                            Locale.ENGLISH));
            extensionManager.handleOfflineReservationsWillExpire(event, reservations);
        }
    });
}

From source file:alfio.manager.TicketReservationManager.java

Stream<Event> getNotifiableEventsStream() {
    return eventRepository.findAll().stream().filter(e -> {
        int daysBeforeStart = configurationManager.getIntConfigValue(Configuration.from(e.getOrganizationId(),
                e.getId(), ConfigurationKeys.ASSIGNMENT_REMINDER_START), 10);
        //we don't want to define events SO far away, don't we?
        int days = (int) ChronoUnit.DAYS.between(ZonedDateTime.now(e.getZoneId()).toLocalDate(),
                e.getBegin().toLocalDate());
        return days > 0 && days <= daysBeforeStart;
    });/* ww  w .  ja v  a  2 s.c o  m*/
}

From source file:org.apache.nifi.avro.AvroTypeUtil.java

@SuppressWarnings("unchecked")
private static Object convertToAvroObject(final Object rawValue, final Schema fieldSchema,
        final String fieldName, final Charset charset) {
    if (rawValue == null) {
        return null;
    }//from   w  w  w.j  a  v  a2 s .  com

    switch (fieldSchema.getType()) {
    case INT: {
        final LogicalType logicalType = fieldSchema.getLogicalType();
        if (logicalType == null) {
            return DataTypeUtils.toInteger(rawValue, fieldName);
        }

        if (LOGICAL_TYPE_DATE.equals(logicalType.getName())) {
            final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat();
            final Date date = DataTypeUtils.toDate(rawValue, () -> DataTypeUtils.getDateFormat(format),
                    fieldName);
            final Duration duration = Duration.between(new Date(0L).toInstant(),
                    new Date(date.getTime()).toInstant());
            final long days = duration.toDays();
            return (int) days;
        } else if (LOGICAL_TYPE_TIME_MILLIS.equals(logicalType.getName())) {
            final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat();
            final Time time = DataTypeUtils.toTime(rawValue, () -> DataTypeUtils.getDateFormat(format),
                    fieldName);
            final Date date = new Date(time.getTime());
            final Duration duration = Duration.between(date.toInstant().truncatedTo(ChronoUnit.DAYS),
                    date.toInstant());
            final long millisSinceMidnight = duration.toMillis();
            return (int) millisSinceMidnight;
        }

        return DataTypeUtils.toInteger(rawValue, fieldName);
    }
    case LONG: {
        final LogicalType logicalType = fieldSchema.getLogicalType();
        if (logicalType == null) {
            return DataTypeUtils.toLong(rawValue, fieldName);
        }

        if (LOGICAL_TYPE_TIME_MICROS.equals(logicalType.getName())) {
            final long longValue = getLongFromTimestamp(rawValue, fieldSchema, fieldName);
            final Date date = new Date(longValue);
            final Duration duration = Duration.between(date.toInstant().truncatedTo(ChronoUnit.DAYS),
                    date.toInstant());
            return duration.toMillis() * 1000L;
        } else if (LOGICAL_TYPE_TIMESTAMP_MILLIS.equals(logicalType.getName())) {
            final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat();
            Timestamp t = DataTypeUtils.toTimestamp(rawValue, () -> DataTypeUtils.getDateFormat(format),
                    fieldName);
            return getLongFromTimestamp(rawValue, fieldSchema, fieldName);
        } else if (LOGICAL_TYPE_TIMESTAMP_MICROS.equals(logicalType.getName())) {
            return getLongFromTimestamp(rawValue, fieldSchema, fieldName) * 1000L;
        }

        return DataTypeUtils.toLong(rawValue, fieldName);
    }
    case BYTES:
    case FIXED:
        final LogicalType logicalType = fieldSchema.getLogicalType();
        if (logicalType != null && LOGICAL_TYPE_DECIMAL.equals(logicalType.getName())) {
            final LogicalTypes.Decimal decimalType = (LogicalTypes.Decimal) logicalType;
            final BigDecimal rawDecimal;
            if (rawValue instanceof BigDecimal) {
                rawDecimal = (BigDecimal) rawValue;

            } else if (rawValue instanceof Double) {
                rawDecimal = BigDecimal.valueOf((Double) rawValue);

            } else if (rawValue instanceof String) {
                rawDecimal = new BigDecimal((String) rawValue);

            } else if (rawValue instanceof Integer) {
                rawDecimal = new BigDecimal((Integer) rawValue);

            } else if (rawValue instanceof Long) {
                rawDecimal = new BigDecimal((Long) rawValue);

            } else {
                throw new IllegalTypeConversionException("Cannot convert value " + rawValue + " of type "
                        + rawValue.getClass() + " to a logical decimal");
            }
            // If the desired scale is different than this value's coerce scale.
            final int desiredScale = decimalType.getScale();
            final BigDecimal decimal = rawDecimal.scale() == desiredScale ? rawDecimal
                    : rawDecimal.setScale(desiredScale, BigDecimal.ROUND_HALF_UP);
            return new Conversions.DecimalConversion().toBytes(decimal, fieldSchema, logicalType);
        }
        if (rawValue instanceof byte[]) {
            return ByteBuffer.wrap((byte[]) rawValue);
        }
        if (rawValue instanceof String) {
            return ByteBuffer.wrap(((String) rawValue).getBytes(charset));
        }
        if (rawValue instanceof Object[]) {
            return AvroTypeUtil.convertByteArray((Object[]) rawValue);
        } else {
            throw new IllegalTypeConversionException("Cannot convert value " + rawValue + " of type "
                    + rawValue.getClass() + " to a ByteBuffer");
        }
    case MAP:
        if (rawValue instanceof Record) {
            final Record recordValue = (Record) rawValue;
            final Map<String, Object> map = new HashMap<>();
            for (final RecordField recordField : recordValue.getSchema().getFields()) {
                final Object v = recordValue.getValue(recordField);
                if (v != null) {
                    map.put(recordField.getFieldName(), v);
                }
            }

            return map;
        } else if (rawValue instanceof Map) {
            final Map<String, Object> objectMap = (Map<String, Object>) rawValue;
            final Map<String, Object> map = new HashMap<>(objectMap.size());
            for (final String s : objectMap.keySet()) {
                final Object converted = convertToAvroObject(objectMap.get(s), fieldSchema.getValueType(),
                        fieldName + "[" + s + "]", charset);
                map.put(s, converted);
            }
            return map;
        } else {
            throw new IllegalTypeConversionException(
                    "Cannot convert value " + rawValue + " of type " + rawValue.getClass() + " to a Map");
        }
    case RECORD:
        final GenericData.Record avroRecord = new GenericData.Record(fieldSchema);

        final Record record = (Record) rawValue;
        for (final RecordField recordField : record.getSchema().getFields()) {
            final Object recordFieldValue = record.getValue(recordField);
            final String recordFieldName = recordField.getFieldName();

            final Field field = fieldSchema.getField(recordFieldName);
            if (field == null) {
                continue;
            }

            final Object converted = convertToAvroObject(recordFieldValue, field.schema(),
                    fieldName + "/" + recordFieldName, charset);
            avroRecord.put(recordFieldName, converted);
        }
        return avroRecord;
    case UNION:
        return convertUnionFieldValue(rawValue, fieldSchema,
                schema -> convertToAvroObject(rawValue, schema, fieldName, charset), fieldName);
    case ARRAY:
        final Object[] objectArray = (Object[]) rawValue;
        final List<Object> list = new ArrayList<>(objectArray.length);
        int i = 0;
        for (final Object o : objectArray) {
            final Object converted = convertToAvroObject(o, fieldSchema.getElementType(),
                    fieldName + "[" + i + "]", charset);
            list.add(converted);
            i++;
        }
        return list;
    case BOOLEAN:
        return DataTypeUtils.toBoolean(rawValue, fieldName);
    case DOUBLE:
        return DataTypeUtils.toDouble(rawValue, fieldName);
    case FLOAT:
        return DataTypeUtils.toFloat(rawValue, fieldName);
    case NULL:
        return null;
    case ENUM:
        return new GenericData.EnumSymbol(fieldSchema, rawValue);
    case STRING:
        return DataTypeUtils.toString(rawValue, (String) null, charset);
    }

    return rawValue;
}

From source file:org.codice.ddf.catalog.ui.query.monitor.impl.WorkspaceQueryService.java

private Date getOneDayBack() {
    return Date.from(Instant.now().minus(1, ChronoUnit.DAYS));
}

From source file:org.darkware.wpman.util.TimeWindow.java

/**
 * Calculates the next time when a given hour and minute occur, based from the given start time.
 *
 * @param after The time to start searching from.
 * @param hour The hour to search for./*from   w  w  w  .jav a 2 s.  c om*/
 * @param minute The minute to search for.
 * @return A {@code DateTime} corresponding to the hour and minute declared which is explicitly after
 * the start time.
 */
public static LocalDateTime nextTime(final LocalDateTime after, final int hour, final int minute) {
    LocalTime time = LocalTime.of(hour, minute);
    LocalDate afterDate = after.toLocalDate();
    if (!time.isAfter(after.toLocalTime()))
        afterDate = afterDate.plus(1, ChronoUnit.DAYS);
    return time.atDate(afterDate);
}

From source file:org.janusgraph.diskstorage.configuration.CommonConfigTest.java

@Test
public void testDateParsing() {
    BaseConfiguration base = new BaseConfiguration();
    CommonsConfiguration config = new CommonsConfiguration(base);

    for (ChronoUnit unit : Arrays.asList(ChronoUnit.NANOS, ChronoUnit.MICROS, ChronoUnit.MILLIS,
            ChronoUnit.SECONDS, ChronoUnit.MINUTES, ChronoUnit.HOURS, ChronoUnit.DAYS)) {
        base.setProperty("test", "100 " + unit.toString());
        Duration d = config.get("test", Duration.class);
        assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(unit)), d.toNanos());
    }/*from w w w . j  av  a  2s .  c o  m*/

    Map<ChronoUnit, String> mapping = ImmutableMap.of(ChronoUnit.MICROS, "us", ChronoUnit.DAYS, "d");
    for (Map.Entry<ChronoUnit, String> entry : mapping.entrySet()) {
        base.setProperty("test", "100 " + entry.getValue());
        Duration d = config.get("test", Duration.class);
        assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(entry.getKey())), d.toNanos());
    }

}

From source file:org.kie.server.integrationtests.prometheus.PrometheusIntegrationTest.java

@Test
@Category(JEEOnly.class) // Executor in kie-server-integ-tests-all is using JMS for execution. Skipping test for non JEE containers as they don't have JMS.
public void testPrometheusJobMetrics() throws Exception {
    int currentNumberOfCancelled = jobServicesClient
            .getRequestsByStatus(Collections.singletonList(STATUS.CANCELLED.toString()), 0, 1000).size();
    int currentNumberOfDone = jobServicesClient
            .getRequestsByStatus(Collections.singletonList(STATUS.DONE.toString()), 0, 1000).size();

    Instant tomorrow = Instant.now().plus(1, ChronoUnit.DAYS);

    JobRequestInstance jobRequestInstanceTomorrow = createJobRequestInstance();
    jobRequestInstanceTomorrow.setScheduledDate(Date.from(tomorrow));
    Long jobIdTomorrow = jobServicesClient.scheduleRequest(jobRequestInstanceTomorrow);
    jobServicesClient.cancelRequest(jobIdTomorrow);

    JobRequestInstance jobRequestInstanceNow = createJobRequestInstance();
    Long jobIdNow = jobServicesClient.scheduleRequest(jobRequestInstanceNow);
    KieServerSynchronization.waitForJobToFinish(jobServicesClient, jobIdNow);

    assertThat(getMetrics()).contains(/*  w  w w  .  java 2s .  c  om*/
            "kie_server_job_scheduled_total{container_id=\"\",command_name=\"" + PRINT_OUT_COMMAND + "\",}",
            "kie_server_job_cancelled_total{container_id=\"\",command_name=\"" + PRINT_OUT_COMMAND + "\",} "
                    + (currentNumberOfCancelled + 1)
    // Uncomment when JBPM-8452 is resolved.
    //              "kie_server_job_executed_total{container_id=\"\",failed=\"false\",command_name=\"" + PRINT_OUT_COMMAND + "\",} " + (currentNumberOfDone + 1),
    //              "kie_server_job_running_total{container_id=\"\",command_name=\"" + PRINT_OUT_COMMAND + "\",}",
    //              "kie_server_job_duration_seconds_count{container_id=\"\",command_name=\"" + PRINT_OUT_COMMAND + "\",}",
    //              "kie_server_job_duration_seconds_sum{container_id=\"\",command_name=\"" + PRINT_OUT_COMMAND + "\",}"
    );
}

From source file:org.nuxeo.ecm.core.TestSQLRepositoryQuery.java

@Test
public void testQueryACL() throws Exception {
    createDocs();/* w ww .j  a va2  s  .  c o  m*/
    DocumentModel folder1 = session.getDocument(new PathRef("/testfolder1"));
    ACP acp = new ACPImpl();
    ACL acl = new ACLImpl();
    acl.add(new ACE("Administrator", "Everything", true));
    acl.add(new ACE("bob", "Browse", true));
    acl.add(new ACE("steve", "Read", true));
    Date now = new Date();
    Calendar begin = new GregorianCalendar();
    begin.setTimeInMillis(now.toInstant().minus(5, ChronoUnit.DAYS).toEpochMilli());
    Calendar end = new GregorianCalendar();
    end.setTimeInMillis(now.toInstant().plus(5, ChronoUnit.DAYS).toEpochMilli());
    acl.add(ACE.builder("leela", "Write").creator("Administrator").begin(begin).end(end).build());

    acl.add(ACE.BLOCK);
    acp.addACL(acl);
    folder1.setACP(acp, true);
    session.save();

    String queryBase = "SELECT * FROM Document WHERE ecm:isProxy = 0 AND ";

    // simple query
    checkQueryACL(1, queryBase + "ecm:acl/*/principal = 'bob'");

    // documents with both bob and steve
    checkQueryACL(1, queryBase + "ecm:acl/*/principal = 'bob' AND ecm:acl/*/principal = 'steve'");

    // bob cannot be steve, no match
    checkQueryACL(0, queryBase + "ecm:acl/*1/principal = 'bob' AND ecm:acl/*1/principal = 'steve'");

    // bob with Browse
    checkQueryACL(1, queryBase + "ecm:acl/*1/principal = 'bob' AND ecm:acl/*1/permission = 'Browse'");

    // bob with Browse granted
    checkQueryACL(1, queryBase
            + "ecm:acl/*1/principal = 'bob' AND ecm:acl/*1/permission = 'Browse' AND ecm:acl/*1/grant = 1");

    // bob with Browse denied, no match
    checkQueryACL(0, queryBase
            + "ecm:acl/*1/principal = 'bob' AND ecm:acl/*1/permission = 'Browse' AND ecm:acl/*1/grant = 0");

    // bob with Read, no match
    checkQueryACL(0, queryBase + "ecm:acl/*1/principal = 'bob' AND ecm:acl/*1/permission = 'Read'");

    // a bob and a Read
    checkQueryACL(1, queryBase + "ecm:acl/*/principal = 'bob' AND ecm:acl/*/permission = 'Read'");

    // creator is Administrator
    checkQueryACL(1, queryBase + "ecm:acl/*/creator = 'Administrator'");

    // document for leela with a begin date after 2007-01-01
    checkQueryACL(1, queryBase
            + "ecm:acl/*1/principal = 'leela' AND ecm:acl/*1/begin >= DATE '2007-01-01' AND ecm:acl/*1/end <= DATE '2020-01-01'");

    // document for leela with an end date after 2020-01-01, no match
    checkQueryACL(0, queryBase + "ecm:acl/*1/principal = 'leela' AND ecm:acl/*1/end >= DATE '2020-01-01'");

    // document with valid begin date but not end date, no match
    checkQueryACL(0,
            queryBase + "ecm:acl/*1/begin >= DATE '2007-01-01' AND ecm:acl/*1/end >= DATE '2020-01-01'");

    // document with effective acl
    checkQueryACL(1, queryBase + "ecm:acl/*1/status = 1");

    if (!notMatchesNull()) {
        // document with pending or archived acl, no match
        checkQueryACL(0, queryBase + "ecm:acl/*1/status <> 1");
    }

    // block
    checkQueryACL(1, queryBase
            + "ecm:acl/*1/principal = 'Everyone' AND ecm:acl/*1/permission = 'Everything' AND ecm:acl/*1/grant = 0");

    if (!isDBS()) {
        // explicit array index
        checkQueryACL(1, queryBase + "ecm:acl/1/principal = 'bob'");
    }
}