Example usage for java.util.concurrent TimeUnit MINUTES

List of usage examples for java.util.concurrent TimeUnit MINUTES

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit MINUTES.

Prototype

TimeUnit MINUTES

To view the source code for java.util.concurrent TimeUnit MINUTES.

Click Source Link

Document

Time unit representing sixty seconds.

Usage

From source file:io.fabric8.apiman.rest.BearerTokenFilter.java

/**
 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
 *///from ww w  .  j a  v a  2s  .c  om
@Override
public void init(FilterConfig config) throws ServletException {
    // maximum 10000 tokens in the cache
    Number bearerTokenCacheMaxsize = getSystemPropertyOrEnvVar(BEARER_TOKEN_CACHE_MAXSIZE, 10000);
    // cache for 10  min
    Number bearerTokenTTL = getSystemPropertyOrEnvVar(BEARER_TOKEN_TTL, 10);

    bearerTokenCache = CacheBuilder.newBuilder().concurrencyLevel(4) // allowed concurrency among update operations
            .maximumSize(bearerTokenCacheMaxsize.longValue())
            .expireAfterWrite(bearerTokenTTL.longValue(), TimeUnit.MINUTES)
            .build(new CacheLoader<String, UserInfo>() {
                public UserInfo load(String authToken) throws Exception {
                    return getUserInfoFromK8s(authToken);
                }
            });
}

From source file:org.apache.cmueller.camel.apachecon.na2013.SqlBatchTest.java

private void warmUp(List<Object> paylaod) throws InterruptedException {
    getMockEndpoint("mock:end").expectedMessageCount(repeatCounter / batchSite);
    getMockEndpoint("mock:end").setRetainFirst(0);
    getMockEndpoint("mock:end").setRetainLast(0);
    for (int i = 0; i < repeatCounter; i++) {
        template.sendBodyAndHeader(paylaod, "AGG_KEY", "BATCH");
    }/*  w w  w  . j av  a2 s.  c o  m*/
    assertMockEndpointsSatisfied(5, TimeUnit.MINUTES);
    getMockEndpoint("mock:end").reset();
}

From source file:com.datatorrent.demos.dimensions.generic.DimensionStoreOperatorTest.java

@Test
public void testQueryFromHDS() throws Exception {
    File file = new File(testInfo.getDir());
    FileUtils.deleteDirectory(file);/*from  w  ww  .j  a v a 2  s . c  om*/

    DimensionStoreOperator hdsOut = new DimensionStoreOperator() {
        @Override
        public void setup(OperatorContext arg0) {
            super.setup(arg0);
            super.writeExecutor = super.queryExecutor = MoreExecutors.sameThreadExecutor(); // synchronous processing
        }
    };
    TFileImpl hdsFile = new TFileImpl.DefaultTFileImpl();
    hdsOut.setFileStore(hdsFile);
    hdsFile.setBasePath(testInfo.getDir());
    EventSchema eventSchema = GenericAggregateSerializerTest.getEventSchema();
    GenericAggregator aggregator = new GenericAggregator(eventSchema);
    aggregator.init("time=MINUTES:pubId:adId:adUnit");
    hdsOut.setEventSchemaJSON(GenericAggregateSerializerTest.TEST_SCHEMA_JSON);
    hdsOut.setAggregator(aggregator);
    hdsOut.setMaxCacheSize(1);
    hdsOut.setFlushIntervalCount(0);
    hdsOut.setup(null);

    CollectorTestSink<DimensionStoreOperator.HDSRangeQueryResult> queryResults = new CollectorTestSink<DimensionStoreOperator.HDSRangeQueryResult>();
    @SuppressWarnings({ "unchecked", "rawtypes" })
    CollectorTestSink<Object> tmp = (CollectorTestSink) queryResults;
    hdsOut.queryResult.setSink(tmp);

    hdsOut.beginWindow(1);

    long baseTime = System.currentTimeMillis();
    long baseMinute = TimeUnit.MILLISECONDS.convert(TimeUnit.MINUTES.convert(baseTime, TimeUnit.MILLISECONDS),
            TimeUnit.MINUTES);

    // Events ae1 and ae2 fall into same aggregation as they have same key
    Map<String, Object> eventMap = Maps.newHashMap();
    eventMap.put("timestamp", baseMinute);
    eventMap.put("pubId", 1);
    eventMap.put("adId", 2);
    eventMap.put("adUnit", 3);
    eventMap.put("clicks", 10L);

    GenericAggregate ae1 = new GenericAggregate(eventSchema.convertMapToGenericEvent(eventMap));
    hdsOut.input.process(ae1);

    // Modify click count and create new event
    eventMap.put("clicks", 20L);
    GenericAggregate ae2 = new GenericAggregate(eventSchema.convertMapToGenericEvent(eventMap));
    hdsOut.input.process(ae2);

    // Modify clicks to 10 and time by 1 minute and create new event
    eventMap.put("clicks", 10L);
    eventMap.put("timestamp", baseMinute + TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES));
    GenericAggregate ae3 = new GenericAggregate(eventSchema.convertMapToGenericEvent(eventMap));
    hdsOut.input.process(ae3);

    hdsOut.endWindow();

    hdsOut.beginWindow(2);

    JSONObject keys = new JSONObject();
    keys.put("pubId", 1);
    keys.put("adId", 2);
    keys.put("adUnit", 3);

    JSONObject query = new JSONObject();
    query.put("numResults", "20");
    query.put("keys", keys);
    query.put("id", "query1");
    query.put("startTime", baseMinute);
    query.put("endTime", baseMinute + TimeUnit.MILLISECONDS.convert(20, TimeUnit.MINUTES));

    hdsOut.query.process(query.toString());

    Assert.assertEquals("timeSeriesQueries " + hdsOut.rangeQueries, 1, hdsOut.rangeQueries.size());
    DimensionStoreOperator.HDSRangeQuery aq = hdsOut.rangeQueries.values().iterator().next();
    Assert.assertEquals("numTimeUnits " + hdsOut.rangeQueries, baseMinute, aq.startTime);

    hdsOut.endWindow();

    Assert.assertEquals("queryResults " + queryResults.collectedTuples, 1, queryResults.collectedTuples.size());
    HDSRangeQueryResult r = queryResults.collectedTuples.iterator().next();
    Assert.assertEquals("result points " + r, 2, r.data.size());

    // ae1 object is stored as referenced in cache, and when new tuple is aggregated,
    // the new values are updated in ae1 itself, causing following check to fail.
    //Assert.assertEquals("clicks", ae1.clicks + ae2.clicks, r.data.get(0).clicks);
    Assert.assertEquals("clicks", 30L, r.data.get(0).get("clicks"));
    Assert.assertEquals("clicks", eventSchema.getValue(ae3, "clicks"), r.data.get(1).get("clicks"));
}

From source file:com.magnet.mmx.util.AlertEventsManagerTest.java

public void testInterEmailTime() {
    setupMocks();/*w  ww  . jav  a 2s.c  om*/
    long testDurationMinutes = 5;
    MMXConfiguration.getConfiguration().setValue(MMXConfigKeys.ALERT_EMAIL_ENABLED, "true");
    MMXConfiguration.getConfiguration().setValue(MMXConfigKeys.ALERT_INTER_EMAIL_TIME_MINUTES, "1");
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
    ScheduledFuture<?> future = executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            AlertEventsManager.post(getRandomEvent());
        }
    }, 0L, 500, TimeUnit.MILLISECONDS);
    List<ScheduledFuture<?>> list = new ArrayList<ScheduledFuture<?>>();
    list.add(future);
    executorService.schedule(new StopTestTask(list), testDurationMinutes, TimeUnit.MINUTES);
    while (!future.isDone())
        ;
    LOGGER.trace("testInterEmailTime : average inter email time = {}", getAvg(elapsedTimes));
}

From source file:com.jbrisbin.vpc.jobsched.batch.BatchMessageHandler.java

public BatchMessage handleMessage(BatchMessage batch) throws Exception {
    log.debug("handling message: " + batch.toString());

    final BatchMessage results = new BatchMessage();
    results.setId(batch.getId());//from  ww w  .j  a va  2  s  .c  o m

    // For waiting till our results are all back
    final CountDownLatch latch = new CountDownLatch(batch.getMessages().size());

    Queue resultsQueue = rabbitAdmin.declareQueue();
    SimpleMessageListenerContainer listener = new SimpleMessageListenerContainer(connectionFactory);
    listener.setAutoAck(true);
    listener.setQueues(resultsQueue);
    listener.setMessageListener(new MessageListener() {
        public void onMessage(Message message) {
            String messageId = new String(message.getMessageProperties().getCorrelationId());
            String body = new String(message.getBody());
            results.getMessages().put(messageId, body);
            latch.countDown();
        }
    });
    listener.start();

    for (Map.Entry<String, String> msg : batch.getMessages().entrySet()) {
        final String[] parts = msg.getKey().split(":");
        template.send(parts[0], parts[1],
                new MessageCreator(parts[2], parts[3], resultsQueue.getName(), msg.getValue().getBytes()));
    }

    // Wait the timeout value per message for all results to be collected
    latch.await((batch.getTimeout() * batch.getMessages().size()), TimeUnit.MINUTES);

    return results;
}

From source file:com.netflix.spinnaker.orca.pipelinetemplate.tasks.v2.CreateV2PipelineTemplateTask.java

@Override
public long getTimeout() {
    return TimeUnit.MINUTES.toMillis(1);
}

From source file:com.pinterest.terrapin.server.TerrapinServerHandler.java

private void startThriftServer(int thriftPort) {
    TerrapinServerInternal.ServiceIface serviceImpl = new TerrapinServerInternalImpl(configuration,
            resourcePartitionMap);/*from   ww w  . j a v a 2  s  .  co  m*/
    TerrapinServerInternal.Service service = new TerrapinServerInternal.Service(serviceImpl,
            new TBinaryProtocol.Factory());

    this.server = ServerBuilder.safeBuild(service,
            ServerBuilder.get().name("TerrapinServer").codec(ThriftServerFramedCodec.get())
                    .hostConnectionMaxIdleTime(Duration.fromTimeUnit(
                            configuration.getInt(Constants.THRIFT_CONN_MAX_IDLE_TIME, 1), TimeUnit.MINUTES))
                    .maxConcurrentRequests(configuration.getInt(Constants.THRIFT_MAX_CONCURRENT_REQUESTS, 100))
                    .reportTo(new OstrichStatsReceiver(Stats.get("")))
                    .bindTo(new InetSocketAddress(thriftPort)));
    new OstrichAdminService(configuration.getInt(Constants.OSTRICH_METRICS_PORT, 9999)).start();
}

From source file:com.gdn.iam.spring.security.FortressDecisionVoter.java

public FortressDecisionVoter() {
    try {//  ww  w.  ja v a 2s .co m
        context = JAXBContext.newInstance(Session.class);
    } catch (JAXBException e) {
        LOG.error("can not creating jaxb context ", e);
    }
    sessionCache = CacheBuilder.newBuilder().expireAfterWrite(Long.valueOf(cacheDuration), TimeUnit.MINUTES)
            .maximumSize(MAXIMUM_CACHE_SIZE).build();
    accessCache = CacheBuilder.newBuilder().expireAfterWrite(Long.valueOf(cacheDuration), TimeUnit.MINUTES)
            .maximumSize(MAXIMUM_CACHE_SIZE).build();
    permissionModels = Arrays.asList(new String[] { CATALOG_URL, PROFILE_URL });
}

From source file:com.dcsquare.hivemq.plugin.fileauthentication.authentication.FileAuthenticator.java

/**
 * Method which checks username/password from credential file against the provided username/password
 *
 * @param clientCredentialsData holds all data about the connecting client
 * @return true, if the credentials are ok, false otherwise.
 * @throws AuthenticationException/*from w w  w  .  j  av a2s. c o  m*/
 */
@Override
@Cached(timeToLive = 5, timeUnit = TimeUnit.MINUTES)
public Boolean checkCredentials(ClientCredentialsData clientCredentialsData) throws AuthenticationException {

    final Optional<String> usernameOptional = clientCredentialsData.getUsername();
    final Optional<String> passwordOptional = clientCredentialsData.getPassword();

    if (usernameOptional.isPresent() && passwordOptional.isPresent()) {

        final String username = usernameOptional.get();
        final String password = passwordOptional.get();

        final Optional<String> hashedPasswordOptional = Optional
                .fromNullable(configurations.getString(username));

        if (!hashedPasswordOptional.isPresent()) {
            return false;
        }

        final String hashedPassword = hashedPasswordOptional.get();

        if (!isHashed) {
            return passwordComparator.validatePlaintextPassword(hashedPassword, password);
        }

        if (!isSalted) {
            return passwordComparator.validateHashedPassword(algorithm, password, hashedPassword, iterations);
        }

        final HashedSaltedPassword hashedSaltedPassword;
        try {
            hashedSaltedPassword = getHashAndSalt(hashedPassword);
        } catch (PasswordFormatException e) {
            return false;
        }

        return passwordComparator.validateHashedAndSaltedPassword(algorithm, password,
                hashedSaltedPassword.getHash(), iterations, hashedSaltedPassword.getSalt());
    } else {
        return false;
    }

}

From source file:rmblworx.tools.timey.AlarmTest.java

/**
 * Test method for {@link Alarm#isAlarmActivated(AlarmDescriptor)}.
 *///  ww w  .j  a  v a2s . co m
@Test
public final void testIsActivatedShouldReturnNullBecauseNoAlarmtimeWasSetBefore() {
    this.effectiveDelegate = new Alarm(this.service, 1, TimeUnit.MINUTES);
    final AlarmDescriptor expected = null;

    when(this.service.isActivated(expected)).thenReturn(null);
    this.effectiveDelegate.setAlarm(expected);

    assertNull(this.effectiveDelegate.isAlarmActivated(expected));
}