Example usage for java.util.concurrent TimeUnit NANOSECONDS

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

Introduction

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

Prototype

TimeUnit NANOSECONDS

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

Click Source Link

Document

Time unit representing one thousandth of a microsecond.

Usage

From source file:fr.xebia.monitoring.demo.payment.CreditCardServiceMonitoringImpl.java

@ManagedAttribute
public void setSlowRequestThresholdInMillis(long slowRequestThresholdInMillis) {
    this.slowRequestThresholdInNanos
            .set(TimeUnit.NANOSECONDS.convert(slowRequestThresholdInMillis, TimeUnit.MILLISECONDS));
}

From source file:com.spotify.heroic.metric.astyanax.AstyanaxBackend.java

private AsyncFuture<FetchData> fetchDataPoints(final Series series, DateRange range,
        final FetchQuotaWatcher watcher) {
    return context.doto(ctx -> {
        return async.resolved(prepareQueries(series, range)).lazyTransform(result -> {
            final List<AsyncFuture<FetchData>> queries = new ArrayList<>();

            for (final PreparedQuery q : result) {
                queries.add(async.call(new Callable<FetchData>() {
                    @Override//from   w ww  .j  av  a  2  s .  co  m
                    public FetchData call() throws Exception {
                        final Stopwatch w = Stopwatch.createStarted();

                        final RowQuery<MetricsRowKey, Integer> query = ctx.client.prepareQuery(METRICS_CF)
                                .getRow(q.rowKey).autoPaginate(true).withColumnRange(q.columnRange);

                        final List<Point> data = q.rowKey.buildPoints(query.execute().getResult());

                        if (!watcher.readData(data.size())) {
                            throw new IllegalArgumentException("data limit quota violated");
                        }

                        final QueryTrace trace = new QueryTrace(FETCH_SEGMENT, w.elapsed(TimeUnit.NANOSECONDS));
                        final List<Long> times = ImmutableList.of(trace.getElapsed());
                        final List<MetricCollection> groups = ImmutableList.of(MetricCollection.points(data));
                        return new FetchData(series, times, groups, trace);
                    }
                }, pools.read()).onDone(reporter.reportFetch()));
            }

            return async.collect(queries, FetchData.collect(FETCH, series));
        });
    });
}

From source file:io.netty.handler.timeout.IdleStateHandler.java

/**
 * Return the allIdleTime that was given when instance this class in milliseconds.
 *
 *//*from  ww w  .j  ava  2s .c o  m*/
public long getAllIdleTimeInMillis() {
    return TimeUnit.NANOSECONDS.toMillis(allIdleTimeNanos);
}

From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateRemoteTokenServicesUnitTests.java

/**
 * Make sure we can validate a token./*from w  w  w  .  j  a  va 2 s  .  com*/
 */
@Test
public void canLoadAuthentication() {
    final AccessTokenConverter converter = Mockito.mock(AccessTokenConverter.class);
    final RestTemplate restTemplate = Mockito.mock(RestTemplate.class);
    final PingFederateRemoteTokenServices services = new PingFederateRemoteTokenServices(
            this.resourceServerProperties, converter, this.registry);
    services.setRestTemplate(restTemplate);
    final String accessToken = UUID.randomUUID().toString();

    final String clientId = UUID.randomUUID().toString();
    final String scope1 = UUID.randomUUID().toString();
    final String scope2 = UUID.randomUUID().toString();

    final Map<String, Object> map = Maps.newHashMap();
    map.put(PingFederateRemoteTokenServices.CLIENT_ID_KEY, clientId);
    map.put(PingFederateRemoteTokenServices.SCOPE_KEY, scope1 + " " + scope2);

    @SuppressWarnings("unchecked")
    final ResponseEntity<Map> response = Mockito.mock(ResponseEntity.class);

    Mockito.when(restTemplate.exchange(Mockito.eq(CHECK_TOKEN_ENDPOINT_URL), Mockito.eq(HttpMethod.POST),
            Mockito.any(HttpEntity.class), Mockito.eq(Map.class))).thenReturn(response);

    Mockito.when(response.getBody()).thenReturn(map);

    final SimpleGrantedAuthority scope1Authority = new SimpleGrantedAuthority(scope1);
    final SimpleGrantedAuthority scope2Authority = new SimpleGrantedAuthority(scope2);
    final Set<GrantedAuthority> authorities = Sets.newHashSet(scope1Authority, scope2Authority);

    final Authentication authentication = new UsernamePasswordAuthenticationToken(clientId, "NA", authorities);

    final OAuth2Authentication oauth2Authentication = new OAuth2Authentication(
            Mockito.mock(OAuth2Request.class), authentication);

    Mockito.when(converter.extractAuthentication(Mockito.eq(map))).thenReturn(oauth2Authentication);

    final OAuth2Authentication result = services.loadAuthentication(accessToken);
    Assert.assertThat(result, Matchers.is(oauth2Authentication));
    Assert.assertThat(result.getPrincipal(), Matchers.is(clientId));
    Assert.assertThat(result.getAuthorities().size(), Matchers.is(2));
    Assert.assertTrue(result.getAuthorities().contains(scope1Authority));
    Assert.assertTrue(result.getAuthorities().contains(scope2Authority));
    Mockito.verify(this.authenticationTimer, Mockito.times(1)).record(Mockito.anyLong(),
            Mockito.eq(TimeUnit.NANOSECONDS));
}

From source file:com.clickha.nifi.processors.FetchFileTransferV2.java

/**
 * Close connections that are idle or optionally close all connections.
 * Connections are considered "idle" if they have not been used in 10 seconds.
 *
 * @param closeNonIdleConnections if <code>true</code> will close all connection; if <code>false</code> will close only idle connections
 *///ww w . ja  v  a  2 s.  c  om
private void closeConnections(final boolean closeNonIdleConnections) {
    for (final Map.Entry<Tuple<String, Integer>, BlockingQueue<FileTransferIdleWrapper>> entry : fileTransferMap
            .entrySet()) {
        final BlockingQueue<FileTransferIdleWrapper> wrapperQueue = entry.getValue();

        final List<FileTransferIdleWrapper> putBack = new ArrayList<>();
        FileTransferIdleWrapper wrapper;
        while ((wrapper = wrapperQueue.poll()) != null) {
            final long lastUsed = wrapper.getLastUsed();
            final long nanosSinceLastUse = System.nanoTime() - lastUsed;
            if (!closeNonIdleConnections
                    && TimeUnit.NANOSECONDS.toMillis(nanosSinceLastUse) < IDLE_CONNECTION_MILLIS) {
                putBack.add(wrapper);
            } else {
                try {
                    wrapper.getFileTransfer().close();
                } catch (final IOException ioe) {
                    getLogger().warn("Failed to close Idle Connection due to {}", new Object[] { ioe }, ioe);
                }
            }
        }

        for (final FileTransferIdleWrapper toPutBack : putBack) {
            wrapperQueue.offer(toPutBack);
        }
    }
}

From source file:io.restassured.builder.ResponseSpecBuilderExpectationsTest.java

@Parameters(name = "{0}")
@SuppressWarnings("deprecation")
public static Iterable<Object[]> data() {
    return Arrays.asList(new Object[][] {
            { "Content matcher", when(responseMock().asString()).thenReturn("goodBody").getMock(),
                    when(responseMock().asString()).thenReturn("badBody").getMock(),
                    new ResponseSpecBuilder().expectContent(startsWith("good")), },
            { "Content matcher with path", responseMockInJson("{\"name\": \"goodValue\"}"),
                    responseMockInJson("{\"name\": \"badValue\"}"),
                    new ResponseSpecBuilder().expectContent("name", startsWith("good")), },
            { "Content matcher with parametrized path",
                    responseMockInJson("{\"name\": [\"value1\", \"value2\"]}"),
                    responseMockInJson("{\"name\": [\"value3\", \"value4\"]}"),
                    new ResponseSpecBuilder().expectContent("name[%d]", withArgs(1), endsWith("2")), },
            { "Status code matcher", when(responseMock().getStatusCode()).thenReturn(567).getMock(),
                    when(responseMock().getStatusCode()).thenReturn(765).getMock(),
                    new ResponseSpecBuilder().expectStatusCode(lessThan(600)) },
            { "Status code value", when(responseMock().getStatusCode()).thenReturn(567).getMock(),
                    when(responseMock().getStatusCode()).thenReturn(765).getMock(),
                    new ResponseSpecBuilder().expectStatusCode(567) },
            { "Status line matcher",
                    when(responseMock().getStatusLine()).thenReturn("HTTP/5.6 567 GOOD").getMock(),
                    when(responseMock().getStatusLine()).thenReturn("FTP/4.3 765 BAD").getMock(),
                    new ResponseSpecBuilder().expectStatusLine(containsString("GOOD")) },
            { "Status line value",
                    when(responseMock().getStatusLine()).thenReturn("HTTP/5.6 567 GOOD").getMock(),
                    when(responseMock().getStatusLine()).thenReturn("FTP/4.3 765 BAD").getMock(),
                    new ResponseSpecBuilder().expectStatusLine("HTTP/5.6 567 GOOD") },
            { "Headers map", when(responseMock().getHeaders()).thenReturn(
                    new Headers(new Header("header1", "header1Value"), new Header("header2", "header2Value")))
                    .getMock(),//from ww w  . ja  v  a  2 s . co  m
                    when(responseMock().getHeaders())
                            .thenReturn(new Headers(new Header("header3", "header3Value"))).getMock(),
                    new ResponseSpecBuilder().expectHeaders(new HashMap<String, Object>() {
                        {
                            put("header1", "header1Value");
                        }
                    }) },
            { "Header matcher",
                    when(responseMock().getHeaders())
                            .thenReturn(new Headers(new Header("header1", "goodHeaderValue"))).getMock(),
                    when(responseMock().getHeaders())
                            .thenReturn(new Headers(new Header("header1", "badHeaderValue"))).getMock(),
                    new ResponseSpecBuilder().expectHeader("header1", equalTo("goodHeaderValue")) },
            { "Header value",
                    when(responseMock().getHeaders())
                            .thenReturn(new Headers(new Header("header1", "goodHeaderValue"))).getMock(),
                    when(responseMock().getHeaders())
                            .thenReturn(new Headers(new Header("header1", "badHeaderValue"))).getMock(),
                    new ResponseSpecBuilder().expectHeader("header1", "goodHeaderValue") },
            { "Cookies map",
                    when(responseMock().getHeaders())
                            .thenReturn(new Headers(new Header("Set-Cookie", "cookie1=cookie1Val"))).getMock(),
                    when(responseMock().getHeaders())
                            .thenReturn(new Headers(new Header("Set-Cookie", "cookie1=cookie1BadVal")))
                            .getMock(),
                    new ResponseSpecBuilder().expectCookies(new HashMap<String, Object>() {
                        {
                            put("cookie1", "cookie1Val");
                        }
                    }) },
            { "Cookie matcher", when(responseMock().getHeaders())
                    .thenReturn(new Headers(new Header("Set-Cookie", "cookie1=cookie1GoodVal"))).getMock(),
                    when(responseMock().getHeaders())
                            .thenReturn(new Headers(new Header("Set-Cookie", "cookie1=cookie1BadVal")))
                            .getMock(),
                    new ResponseSpecBuilder().expectCookie("cookie1", containsString("GoodVal")) },
            { "Cookie value",
                    when(responseMock().getHeaders())
                            .thenReturn(new Headers(new Header("Set-Cookie", "cookie1=cookie1Val"))).getMock(),
                    when(responseMock().getHeaders())
                            .thenReturn(new Headers(new Header("Set-Cookie", "cookie1=cookie1BadVal")))
                            .getMock(),
                    new ResponseSpecBuilder().expectCookie("cookie1", "cookie1Val") },
            { "Cookie presence",
                    when(responseMock().getHeaders())
                            .thenReturn(new Headers(new Header("Set-Cookie", "cookie1=cookie1Val"))).getMock(),
                    when(responseMock().getHeaders())
                            .thenReturn(new Headers(new Header("Set-Cookie", "cookie2=cookie2Val"))).getMock(),
                    new ResponseSpecBuilder().expectCookie("cookie1") },
            { "Response time matcher",
                    when(responseMock().getTimeIn(TimeUnit.MILLISECONDS)).thenReturn(4000L).getMock(),
                    when(responseMock().getTimeIn(TimeUnit.MILLISECONDS)).thenReturn(8000L).getMock(),
                    new ResponseSpecBuilder().expectResponseTime(lessThan(5000L)) },
            { "Response time matcher with time unit",
                    when(responseMock().getTimeIn(TimeUnit.NANOSECONDS)).thenReturn(4000L).getMock(),
                    when(responseMock().getTimeIn(TimeUnit.NANOSECONDS)).thenReturn(8000L).getMock(),
                    new ResponseSpecBuilder().expectResponseTime(lessThan(5000L), TimeUnit.NANOSECONDS) },
            { "Content type object", when(responseMock().getContentType()).thenReturn("text/xml").getMock(),
                    when(responseMock().getContentType()).thenReturn("application/json").getMock(),
                    new ResponseSpecBuilder().expectContentType(ContentType.XML) },
            { "Content type string", when(responseMock().getContentType()).thenReturn("text/xml").getMock(),
                    when(responseMock().getContentType()).thenReturn("application/json").getMock(),
                    new ResponseSpecBuilder().expectContentType("text/xml") },
            { "Body matcher", when(responseMock().asString()).thenReturn("goodBody").getMock(),
                    when(responseMock().asString()).thenReturn("badBody").getMock(),
                    new ResponseSpecBuilder().expectBody(containsString("good")), },
            { "Body matcher with path", responseMockInJson("{\"name\": \"goodValue\"}"),
                    responseMockInJson("{\"name\": \"badValue\"}"),
                    new ResponseSpecBuilder().expectBody("name", startsWith("good")), },
            { "Body matcher with parametrized path", responseMockInJson("{\"name\": [\"value1\", \"value2\"]}"),
                    responseMockInJson("{\"name\": [\"value3\", \"value4\"]}"),
                    new ResponseSpecBuilder().expectBody("name[%d]", withArgs(1), endsWith("2")), } });
}

From source file:org.agatom.springatom.webmvc.controllers.wizard.SVWizardController.java

/**
 * <b>onWizardSubmit</b> is the last method called for a single {@link WizardProcessor}. Its job is to pick
 * up {@link WizardProcessor} out of {@link #processorMap} and call {@link WizardProcessor#onWizardSubmit(java.util.Map, java.util.Locale)}
 * in order to finalize the processing job
 *
 * @param wizard   unique id of the {@link WizardProcessor}
 * @param formData form data/*from   w ww .  ja  v  a 2  s  .com*/
 *
 * @return {@link WizardSubmission} the submission
 */
@Override
public WizardSubmission onWizardSubmit(final String wizard, final ModelMap formData, final Locale locale)
        throws Exception {
    LOGGER.debug(String.format("onWizardSubmit(wizard=%s,formData=%s)", wizard, formData));

    final long startTime = System.nanoTime();

    WizardSubmission submission = null;
    WizardResult result;

    try {

        final WizardProcessor wizardProcessor = this.processorMap.get(wizard);
        result = wizardProcessor.onWizardSubmit(formData, locale);

    } catch (Exception exp) {
        LOGGER.debug(String.format("onWizardSubmit(wizard=%s) failed", wizard), exp);
        throw exp;
    }
    final long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);

    if (result != null) {
        submission = (WizardSubmission) new WizardSubmission(result, Submission.SUBMIT).setSize(1)
                .setSuccess(true).setTime(endTime);
    }

    LOGGER.trace(String.format("onWizardSubmit(wizard=%s) completed in %d ms", wizard, endTime));

    return submission;
}

From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateRemoteTokenServices.java

/**
 * {@inheritDoc}/*from  w ww .  j av  a 2s .  c  o m*/
 */
@Override
public OAuth2Authentication loadAuthentication(final String accessToken)
        throws AuthenticationException, InvalidTokenException {
    final long start = System.nanoTime();
    try {
        final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add(TOKEN_NAME_KEY, accessToken);
        formData.add(CLIENT_ID_KEY, this.clientId);
        formData.add(CLIENT_SECRET_KEY, this.clientSecret);
        formData.add(GRANT_TYPE_KEY, GRANT_TYPE);

        final Map<String, Object> map = this.postForMap(this.checkTokenEndpointUrl, formData);

        if (map.containsKey(ERROR_KEY)) {
            final String error = map.get(ERROR_KEY).toString();
            log.debug("Validating the token produced an error: {}", error);
            throw new InvalidTokenException(error);
        }

        Assert.state(map.containsKey(CLIENT_ID_KEY), "Client id must be present in response from auth server");
        Assert.state(map.containsKey(SCOPE_KEY), "No scopes included in response from authentication server");
        this.convertScopes(map);
        final OAuth2Authentication authentication = this.converter.extractAuthentication(map);
        log.info("User {} authenticated with authorities {}", authentication.getPrincipal(),
                authentication.getAuthorities());
        return authentication;
    } finally {
        final long finished = System.nanoTime();
        this.authenticationTimer.record(finished - start, TimeUnit.NANOSECONDS);
    }
}

From source file:com.android.cts.verifier.sensors.SignificantMotionTestActivity.java

@SuppressWarnings("unused")
public String testAPWakeUpOnSMDTrigger() throws Throwable {
    SensorTestLogger logger = getTestLogger();
    logger.logInstructions(R.string.snsr_significant_motion_ap_suspend);
    waitForUserToBegin();/* w w  w  .j  a v a2 s .co m*/
    mVerifier = new TriggerVerifier();
    mSensorManager.requestTriggerSensor(mVerifier, mSensorSignificantMotion);
    long testStartTimeNs = SystemClock.elapsedRealtimeNanos();
    Handler handler = new Handler(Looper.getMainLooper());
    SuspendStateMonitor suspendStateMonitor = new SuspendStateMonitor();

    Intent intent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + ALARM_WAKE_TIME_DELAY_MS,
            pendingIntent);
    try {
        // Wait for the first event to trigger. Device is expected to go into suspend here.
        mVerifier.verifyEventTriggered();
        long eventTimeStampNs = mVerifier.getTimeStampForTriggerEvent();
        long endTimeNs = SystemClock.elapsedRealtimeNanos();
        long lastWakeupTimeNs = TimeUnit.MILLISECONDS.toNanos(suspendStateMonitor.getLastWakeUpTime());
        Assert.assertTrue(getString(R.string.snsr_device_did_not_go_into_suspend),
                testStartTimeNs < lastWakeupTimeNs && lastWakeupTimeNs < endTimeNs);
        long timestampDelta = Math.abs(lastWakeupTimeNs - eventTimeStampNs);
        Assert.assertTrue(
                String.format(getString(R.string.snsr_device_did_not_wake_up_at_trigger),
                        TimeUnit.NANOSECONDS.toMillis(lastWakeupTimeNs),
                        TimeUnit.NANOSECONDS.toMillis(eventTimeStampNs)),
                timestampDelta < MAX_ACCEPTABLE_DELAY_EVENT_AP_WAKE_UP_NS);
    } finally {
        am.cancel(pendingIntent);
        suspendStateMonitor.cancel();
        mScreenManipulator.turnScreenOn();
        playSound();
    }
    return null;
}