Example usage for java.time Duration ofHours

List of usage examples for java.time Duration ofHours

Introduction

In this page you can find the example usage for java.time Duration ofHours.

Prototype

public static Duration ofHours(long hours) 

Source Link

Document

Obtains a Duration representing a number of standard hours.

Usage

From source file:io.gravitee.management.service.impl.ApiKeyServiceImpl.java

@Override
public ApiKeyEntity generateOrRenew(String applicationName, String apiName) {
    try {/*  www . j a va  2s.  c  o m*/
        LOGGER.debug("Generate a new key for {} - {}", applicationName, apiName);
        ApiKey apiKey = new ApiKey();

        apiKey.setApplication(applicationName);
        apiKey.setApi(apiName);
        apiKey.setCreatedAt(new Date());
        apiKey.setKey(apiKeyGenerator.generate());
        apiKey.setRevoked(false);

        Instant expirationInst = apiKey.getCreatedAt().toInstant().plus(Duration.ofHours(1));
        Date expirationDate = Date.from(expirationInst);

        // Previously generated keys should be set as revoked
        Set<ApiKey> oldKeys = apiKeyRepository.findByApplicationAndApi(applicationName, apiName);
        for (ApiKey oldKey : oldKeys) {
            setExpiration(expirationDate, oldKey);
        }

        apiKey = apiKeyRepository.create(applicationName, apiName, apiKey);
        return convert(apiKey);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to generate a key for {} - {}", applicationName, apiName,
                ex);
        throw new TechnicalManagementException(
                "An error occurs while trying to generate a key for " + applicationName + " - " + apiName, ex);
    }
}

From source file:azkaban.utils.Emailer.java

@Override
public void alertOnError(final ExecutableFlow flow, final String... extraReasons) {
    final EmailMessage message = this.messageCreator.createMessage();
    final MailCreator mailCreator = getMailCreator(flow);
    List<ExecutableFlow> last72hoursExecutions = new ArrayList<>();

    if (flow.getStartTime() > 0) {
        final long startTime = flow.getStartTime() - Duration.ofHours(72).toMillis();
        try {//from ww w  .  j  a va2  s  .c om
            last72hoursExecutions = this.executorLoader.fetchFlowHistory(flow.getProjectId(), flow.getFlowId(),
                    startTime);
        } catch (final ExecutorManagerException e) {
            logger.error("unable to fetch past executions", e);
        }
    }

    final boolean mailCreated = mailCreator.createErrorEmail(flow, last72hoursExecutions, message,
            this.azkabanName, this.scheme, this.clientHostname, this.clientPortNumber, extraReasons);
    sendEmail(message, mailCreated, "error email message for execution " + flow.getExecutionId());
}

From source file:org.rakam.analysis.eventexplorer.EventExplorerHttpService.java

@ApiOperation(value = "Create Pre-computed table", authorizations = @Authorization(value = "master_key"))
@JsonRequest//from  w  w w. j  a v a  2 s  .  c  o  m
@Path("/pre_calculate")
public CompletableFuture<PrecalculatedTable> createPrecomputedTable(@Named("project") String project,
        @BodyParam OLAPTable table) {
    String metrics = table.measures.stream().map(column -> table.aggregations.stream()
            .map(agg -> getAggregationColumn(agg, table.aggregations)
                    .map(e -> String.format(e, column) + " as " + column + "_" + agg.name().toLowerCase()))
            .filter(Optional::isPresent).map(Optional::get).collect(Collectors.joining(", ")))
            .collect(Collectors.joining(", "));

    String subQuery;
    String dimensions = table.dimensions.stream().collect(Collectors.joining(", "));
    if (table.collections.size() == 1) {
        subQuery = table.collections.iterator().next();
    } else if (table.collections.size() > 1) {
        subQuery = table.collections.stream()
                .map(collection -> String.format("SELECT '%s' as collection, _time %s %s FROM %s", collection,
                        dimensions.isEmpty() ? "" : ", " + dimensions,
                        table.measures.isEmpty() ? ""
                                : ", " + table.measures.stream().collect(Collectors.joining(", ")),
                        collection))
                .collect(Collectors.joining(" UNION ALL "));
    } else {
        throw new RakamException("collections is empty", HttpResponseStatus.BAD_REQUEST);
    }

    String name = "Dimensions";

    String dimensionColumns = !dimensions.isEmpty() ? (dimensions + ",") : "";
    String collectionColumn = table.collections.size() != 1 ? ("collection,") : "";
    String query = String.format(
            "SELECT %s _time, %s %s FROM (SELECT %s CAST(_time AS DATE) as _time, %s %s FROM (%s)) GROUP BY CUBE (_time %s %s) ORDER BY 1 ASC",
            collectionColumn, dimensionColumns, metrics, collectionColumn, dimensionColumns,
            table.measures.stream().collect(Collectors.joining(", ")),

            subQuery, table.collections.size() == 1 ? "" : ", collection",
            dimensions.isEmpty() ? "" : "," + dimensions);

    return materializedViewService
            .create(project,
                    new MaterializedView(table.tableName, "Olap table", query, Duration.ofHours(1), null,
                            ImmutableMap.of("olap_table", table)))
            .thenApply(v -> new PrecalculatedTable(name, table.tableName));
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedURIWithEncodedCharacters() throws IOException {
    final String path = testPathPrefix + " quack ";

    mantaClient.put(path, TEST_DATA, UTF_8);
    Assert.assertEquals(mantaClient.getAsString(path), TEST_DATA);

    final URI uri = mantaClient.getAsSignedURI(path, "GET", Instant.now().plus(Duration.ofHours(1)));
    final HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();

    try (final InputStream is = conn.getInputStream()) {
        conn.setReadTimeout(3000);/*from  ww  w .j  av a2s.  c  o  m*/
        conn.connect();

        Assert.assertEquals(conn.getResponseCode(), HttpStatus.SC_OK);
        Assert.assertEquals(IOUtils.toString(is, UTF_8), TEST_DATA);
    } finally {
        conn.disconnect();
    }
}

From source file:org.ulyssis.ipp.ui.widgets.TeamPanel.java

private void updateCharts() {
    Instant now = Instant.now();
    Instant anHourAgo = now.minus(Duration.ofHours(1L));
    try (Connection connection = Database.createConnection(EnumSet.of(Database.ConnectionFlags.READ_ONLY))) {
        List<Event> events = Event.loadFrom(connection, anHourAgo);
        if (events.size() == 0) {
            LOG.warn("No events");
            return;
        }/* ww  w .  ja  v a2  s .  c o m*/
        Snapshot snapshot = Snapshot.loadForEvent(connection, events.get(0)).get(); // If it's not there, this is a fatal error
        List<Optional<Instant>> eventTimes = new ArrayList<>();
        List<List<TagSeenEvent>> eventLists = new ArrayList<>();
        for (int i = 0; i < config.getNbReaders(); i++) {
            eventTimes.add(Optional.empty());
            eventLists.add(new ArrayList<>());
        }
        for (int i = 1; i < events.size(); ++i) {
            Event event = events.get(i);
            snapshot = event.apply(snapshot);
            if (event instanceof TagSeenEvent && !event.isRemoved()) { // TODO(Roel): Well, we can't actually remove it, right?
                final TagSeenEvent tagSeenEvent = (TagSeenEvent) event;
                Optional<Integer> teamNb = snapshot.getTeamTagMap().tagToTeam(tagSeenEvent.getTag());
                if (teamNb.isPresent() && teamNb.get().equals(team.getTeamNb())) {
                    // TODO(Roel): This hack is kind of dirty. In fact, all of this
                    //             code is kind of dirty.
                    if (eventTimes.get(tagSeenEvent.getReaderId()).isPresent()) {
                        if (Duration.between(eventTimes.get(tagSeenEvent.getReaderId()).get(), event.getTime())
                                .toMillis() <= 30_000) {
                            continue;
                        }
                    }
                    eventTimes.get(tagSeenEvent.getReaderId()).ifPresent(lastTime -> {
                        try {
                            eventLists.get(tagSeenEvent.getReaderId()).add(tagSeenEvent);
                        } catch (Exception e) {
                            LOG.error("Exception", e);
                        }
                    });
                    eventTimes.set(tagSeenEvent.getReaderId(), Optional.of(event.getTime()));
                }
            }
        }
        for (int i = 0; i < config.getNbReaders(); i++) {
            List<TagSeenEvent> eventList = eventLists.get(i);
            List<TagSeenEvent> shortenedEventList = new ArrayList<>();
            if (eventList.size() > 40) {
                for (int j = eventList.size() - 40; j < eventList.size(); j++) {
                    shortenedEventList.add(eventList.get(j));
                }
            } else {
                shortenedEventList = eventList;
            }
            itemModels.get(i).setEvents(anHourAgo, shortenedEventList);
        }
    } catch (SQLException e) {
        LOG.error("Couldn't fetch events", e);
    } catch (IOException e) {
        LOG.error("Error processing events", e);
    }
}

From source file:io.gravitee.gateway.services.sync.SyncManagerTest.java

@Test
public void test_twiceWithTwoApis_apiToUpdate() throws Exception {
    io.gravitee.repository.management.model.Api api = new RepositoryApiBuilder().id("api-test")
            .updatedAt(new Date()).definition("test").build();

    Instant updateDateInst = api.getUpdatedAt().toInstant().plus(Duration.ofHours(1));
    io.gravitee.repository.management.model.Api api2 = new RepositoryApiBuilder().id("api-test")
            .updatedAt(Date.from(updateDateInst)).definition("test2").build();

    final Api mockApi = mockApi(api);
    mockApi(api2);/*w w  w  .  ja v a  2  s. com*/

    final Event mockEvent = mockEvent(api, EventType.PUBLISH_API);
    final Event mockEvent2 = mockEvent(api2, EventType.PUBLISH_API);

    List<Event> events = new ArrayList<Event>();
    events.add(mockEvent);
    events.add(mockEvent2);

    when(eventRepository.search(new EventCriteria.Builder()
            .types(EventType.PUBLISH_API, EventType.UNPUBLISH_API, EventType.START_API, EventType.STOP_API)
            .build())).thenReturn(events);

    when(apiRepository.findAll()).thenReturn(Collections.singleton(api));

    syncManager.refresh();

    when(apiRepository.findAll()).thenReturn(Collections.singleton(api2));
    when(apiManager.get(api.getId())).thenReturn(mockApi);

    syncManager.refresh();

    verify(apiManager).deploy(mockApi);
    verify(apiManager).update(mockApi);
    verify(apiManager, never()).undeploy(any(String.class));
}

From source file:io.gravitee.gateway.services.sync.SyncManagerTest.java

@Test
public void test_shouldUpdateIfLastEventIsStartAPI() throws Exception {
    io.gravitee.repository.management.model.Api api = new RepositoryApiBuilder().id("api-test")
            .updatedAt(new Date()).definition("test").lifecycleState(LifecycleState.STOPPED).build();

    Instant updateDateInst = api.getUpdatedAt().toInstant().plus(Duration.ofHours(1));
    io.gravitee.repository.management.model.Api api2 = new RepositoryApiBuilder().id("api-test")
            .updatedAt(Date.from(updateDateInst)).definition("test").lifecycleState(LifecycleState.STARTED)
            .build();/*from w  w w .  j a  v a2  s . c o  m*/

    final Api mockApi = mockApi(api);
    mockApi(api2);
    final Event mockEvent = mockEvent(api, EventType.PUBLISH_API);
    final Event mockEvent2 = mockEvent(api2, EventType.START_API);

    List<Event> events = new ArrayList<Event>();
    events.add(mockEvent);
    events.add(mockEvent2);

    when(eventRepository.search(new EventCriteria.Builder()
            .types(EventType.PUBLISH_API, EventType.UNPUBLISH_API, EventType.START_API, EventType.STOP_API)
            .build())).thenReturn(Collections.singletonList(mockEvent));

    when(apiRepository.findAll()).thenReturn(Collections.singleton(api));

    syncManager.refresh();

    when(eventRepository.search(new EventCriteria.Builder()
            .types(EventType.PUBLISH_API, EventType.UNPUBLISH_API, EventType.START_API, EventType.STOP_API)
            .build())).thenReturn(events);

    when(apiRepository.findAll()).thenReturn(Collections.singleton(api2));
    when(apiManager.get(api.getId())).thenReturn(mockApi);

    syncManager.refresh();

    verify(apiManager).deploy(mockApi);
    verify(apiManager).update(mockApi);
    verify(apiManager, never()).undeploy(any(String.class));

}

From source file:io.gravitee.gateway.services.sync.SyncManagerTest.java

@Test
public void test_shouldUpdateIfLastEventIsStopAPI() throws Exception {
    io.gravitee.repository.management.model.Api api = new RepositoryApiBuilder().id("api-test")
            .updatedAt(new Date()).definition("test").lifecycleState(LifecycleState.STARTED).build();

    Instant updateDateInst = api.getUpdatedAt().toInstant().plus(Duration.ofHours(1));
    io.gravitee.repository.management.model.Api api2 = new RepositoryApiBuilder().id("api-test")
            .updatedAt(Date.from(updateDateInst)).definition("test").lifecycleState(LifecycleState.STOPPED)
            .build();//from   w  w  w. j  a va 2s .  c o  m

    final Api mockApi = mockApi(api);
    mockApi(api2);
    final Event mockEvent = mockEvent(api, EventType.PUBLISH_API);
    final Event mockEvent2 = mockEvent(api2, EventType.STOP_API);

    List<Event> events = new ArrayList<Event>();
    events.add(mockEvent);
    events.add(mockEvent2);

    when(eventRepository.search(new EventCriteria.Builder()
            .types(EventType.PUBLISH_API, EventType.UNPUBLISH_API, EventType.START_API, EventType.STOP_API)
            .build())).thenReturn(Collections.singletonList(mockEvent));

    when(apiRepository.findAll()).thenReturn(Collections.singleton(api));
    when(apiManager.apis()).thenReturn(Collections.singleton(mockApi));

    syncManager.refresh();

    when(eventRepository.search(new EventCriteria.Builder()
            .types(EventType.PUBLISH_API, EventType.UNPUBLISH_API, EventType.START_API, EventType.STOP_API)
            .build())).thenReturn(events);

    when(apiRepository.findAll()).thenReturn(Collections.singleton(api2));
    when(apiManager.get(api.getId())).thenReturn(mockApi);

    syncManager.refresh();

    verify(apiManager).deploy(mockApi);
    verify(apiManager).update(mockApi);
    verify(apiManager, never()).undeploy(any(String.class));

}

From source file:com.example.app.support.service.AppUtil.java

/**
 * Get an expire time for a new token based off the current date
 *
 * @return token expire time//w  w w  . jav  a 2  s  .c om
 */
public static Date getNewTokenExpireTime() {
    return new Date(Instant.now().plus(Duration.ofHours(80)).toEpochMilli());
}

From source file:org.apache.james.modules.mailbox.TikaConfigurationReaderTest.java

@Test
public void readTikaConfigurationShouldParseUnitForCacheEvictionPeriod() throws Exception {
    PropertiesConfiguration configuration = new PropertiesConfiguration();
    configuration.load(new StringReader("tika.enabled=true\n" + "tika.host=172.0.0.5\n" + "tika.port=889\n"
            + "tika.timeoutInMillis=500\n" + "tika.cache.eviction.period=2H"));

    assertThat(TikaConfigurationReader.readTikaConfiguration(configuration))
            .isEqualTo(TikaConfiguration.builder().enabled().host("172.0.0.5").port(889).timeoutInMillis(500)
                    .cacheEvictionPeriod(Duration.ofHours(2)).build());
}