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:cf.randers.scd.CommandLineInterface.java

private void run() {
    if (params == null)
        return;/*from   w ww.  ja va 2 s  . c  om*/
    LOGGER.info("Making temp dir...");
    File tmpDir = new File("tmp/");
    File outDir = new File(outputDirectory);
    //noinspection ResultOfMethodCallIgnored
    tmpDir.mkdirs();
    //noinspection ResultOfMethodCallIgnored
    outDir.mkdirs();
    BlockingQueue<Runnable> tasks = new ArrayBlockingQueue<>(params.size());
    maximumConcurrentConnections = Math.min(params.size(),
            maximumConcurrentConnections > params.size() ? params.size() : maximumConcurrentConnections);
    ThreadPoolExecutor executor = new ThreadPoolExecutor(maximumConcurrentConnections,
            maximumConcurrentConnections, 0, TimeUnit.NANOSECONDS, tasks);
    LOGGER.info("Starting to execute " + params.size() + " thread(s)...");
    for (String param : params) {
        executor.execute(() -> {
            LOGGER.info("Started thread for " + param);
            Map json;
            byte[] artworkBytes = new byte[0];
            List<Track> toProcess = new ArrayList<>();
            LOGGER.info("Resolving and querying track info...");
            try (CloseableHttpClient client = HttpClients.createDefault();
                    CloseableHttpResponse response = client.execute(new HttpGet(new URIBuilder()
                            .setScheme("https").setHost("api.soundcloud.com").setPath("/resolve")
                            .addParameter("url", param).addParameter("client_id", clientID).build()));
                    InputStreamReader inputStreamReader = new InputStreamReader(
                            response.getEntity().getContent())) {

                final int bufferSize = 1024;
                final char[] buffer = new char[bufferSize];
                final StringBuilder out = new StringBuilder();
                for (;;) {
                    int rsz = inputStreamReader.read(buffer, 0, buffer.length);
                    if (rsz < 0)
                        break;
                    out.append(buffer, 0, rsz);
                }
                String rawJson = out.toString();
                Album a = new Gson().fromJson(rawJson, Album.class);

                if (a.getTrackCount() == null) {
                    Track tr = new Gson().fromJson(rawJson, Track.class);
                    toProcess.add(tr);
                }
                toProcess.addAll(a.getTracks());
                EntityUtils.consumeQuietly(response.getEntity());
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            for (Track track : toProcess) {
                System.out.println(track.getId());
                System.out.println(track.getTitle());
            }
            for (Track track : toProcess) {
                LOGGER.info("Downloading mp3 to file...");
                File tmpFile = new File("tmp/" + String.format("%d", track.getId()) + ".mp3");

                try (CloseableHttpClient client = HttpClients.createDefault();
                        CloseableHttpResponse response = client
                                .execute(new HttpGet(track.getStreamUrl() + "?client_id=" + clientID))) {
                    IOUtils.copy(response.getEntity().getContent(), new FileOutputStream(tmpFile));
                    EntityUtils.consumeQuietly(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }

                boolean hasArtwork = track.getArtworkUrl() != null;

                if (hasArtwork) {
                    LOGGER.info("Downloading artwork jpg into memory...");
                    try (CloseableHttpClient client = HttpClients.createDefault();
                            CloseableHttpResponse response = client.execute(
                                    new HttpGet(track.getArtworkUrl().replace("-large.jpg", "-t500x500.jpg")
                                            + "?client_id=" + clientID))) {
                        artworkBytes = IOUtils.toByteArray(response.getEntity().getContent());
                        EntityUtils.consumeQuietly(response.getEntity());
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                }

                try {
                    LOGGER.info("Reading temp file into AudioFile object...");
                    // Read audio file from tmp directory
                    AudioFile audioFile = AudioFileIO.read(tmpFile);

                    // Set Artwork
                    Tag tag = audioFile.getTagAndConvertOrCreateAndSetDefault();
                    if (hasArtwork) {
                        StandardArtwork artwork = new StandardArtwork();
                        artwork.setBinaryData(artworkBytes);
                        artwork.setImageFromData();
                        tag.addField(artwork);
                    }
                    tag.addField(FieldKey.TITLE, track.getTitle());
                    tag.addField(FieldKey.ARTIST, track.getUser().getUsername());
                    LOGGER.info("Saving audio file...");
                    System.out.println(
                            outDir.getAbsolutePath() + "/" + String.format(outputformat, track.getId()));
                    new AudioFileIO().writeFile(audioFile,
                            outDir.getAbsolutePath() + "/" + String.format(outputformat, track.getId()));
                    tmpFile.deleteOnExit();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            File[] listFiles = tmpDir.listFiles();
            if (listFiles == null) {
                return;
            }
            for (File file : listFiles) {
                file.delete();
            }
        });
    }
    executor.shutdown();
}

From source file:com.oneops.opamp.ws.OpampWsController.java

/**
* Get the current WatchedByAttributeCache  status. Returns the cumulative status of
* <ul>/*from ww w  . ja v a 2  s.c  om*/
* <li>hitCount
* <li>missCount;
* <li>loadSuccessCount;
* <li>loadExceptionCount;
* <li>totalLoadTime;
* <li>evictionCount;
* </ul>
*
* @return cache status map.
*/
@RequestMapping(value = "/cache/stats", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> getCacheStats() {
    Map<String, Object> stat = new LinkedHashMap<>(5);
    stat.put("status", "ok");
    stat.put("maxSize", cache.getMaxSize());
    stat.put("currentSize", cache.instance().size());
    stat.put("timeout", cache.getTimeout());
    CacheStats cs = cache.instance().stats();
    stat.put("hitCount", cs.hitCount());
    stat.put("missCount", cs.missCount());
    stat.put("loadSuccessCount", cs.loadSuccessCount());
    stat.put("totalLoadTime", TimeUnit.SECONDS.convert(cs.totalLoadTime(), TimeUnit.NANOSECONDS));
    stat.put("loadExceptionCount", cs.loadExceptionCount());
    stat.put("evictionCount", cs.evictionCount());
    return stat;
}

From source file:org.wso2.carbon.metrics.impl.JDBCCleanupTest.java

@Before
public void setUp() throws Exception {
    when(clock.getTime()).thenReturn(System.currentTimeMillis());

    this.reporter = JDBCReporter.forRegistry(registry).convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.NANOSECONDS).withClock(clock).filter(MetricFilter.ALL)
            .build(SOURCE, dataSource);//from   w w  w . j  ava  2 s  .co m

    template.execute("DELETE FROM METRIC_GAUGE;");
    template.execute("DELETE FROM METRIC_TIMER;");
    template.execute("DELETE FROM METRIC_METER;");
    template.execute("DELETE FROM METRIC_HISTOGRAM;");
    template.execute("DELETE FROM METRIC_COUNTER;");
}

From source file:AIR.Common.Threading.BoundedThreadPool.java

public BoundedThreadPool(int threadCount, String threadPoolName, int highWaterMark, int lowWaterMark,
        IThreadPoolStatsRecorder statsRecorder) {
    if (threadCount <= 0) {
        threadCount = Math.max(_numberOfProcessors, 2);
    }//  w  w  w.j  a v  a  2 s . c  om
    _name = StringUtils.defaultString(threadPoolName);
    _taskQHighWaterMark = highWaterMark <= 0 ? Integer.MAX_VALUE : highWaterMark;
    _taskQLowWaterMark = lowWaterMark <= 0 ? highWaterMark : lowWaterMark;
    if (lowWaterMark > highWaterMark) {
        throw new IllegalArgumentException("The low watermark cannot be larger than the high watermark");
    }

    if (statsRecorder != null) {
        statsRecorder.setThreadPool(this);
    }
    _statsRecorder = statsRecorder;
    _taskQueue = new ArrayBlockingQueue<>(_taskQHighWaterMark, true);
    ThreadFactory threadFactory = new NamedThreadFactory();
    _workerThreadPool = new ThreadPoolExecutor(threadCount, threadCount, 0, TimeUnit.NANOSECONDS, _taskQueue,
            threadFactory);
    synchronized (_statusLock) {
        _workerThreadPool.prestartAllCoreThreads();
        _status = ThreadPoolStatus.Active;
    }
}

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

@Override
public PaymentTransaction purchase(MonetaryAmount total, Order order, String requestId) {
    StringBuilder auditMessage = new StringBuilder("creditcardservice.purchase(" + requestId + ", "
            + order.getAccount().getEmail() + ", " + total + ") by ");
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        auditMessage.append("anonymous");
    } else {//from  ww w.  jav  a  2 s  . com
        auditMessage.append(authentication.getName());
        if (authentication.getDetails() instanceof WebAuthenticationDetails) {
            WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
            auditMessage.append(" coming from " + details.getRemoteAddress());
        }
    }

    long nanosBefore = System.nanoTime();
    try {
        PaymentTransaction paymentTransaction = creditCardService.purchase(total, order, requestId);

        auditMessage.append(" SUCCESS ").append(paymentTransaction.getTransactionId());
        auditMessage.append(" in ")
                .append(TimeUnit.MILLISECONDS.convert(System.nanoTime() - nanosBefore, TimeUnit.NANOSECONDS))
                .append(" ms");
        auditLogger.info(auditMessage.toString());
        return paymentTransaction;
    } catch (RuntimeException e) {
        auditMessage.append(" FAILURE ").append(Joiner.on(", ").join(Throwables.getCausalChain(e)));
        auditMessage.append(" in ")
                .append(TimeUnit.MILLISECONDS.convert(System.nanoTime() - nanosBefore, TimeUnit.NANOSECONDS))
                .append(" ms");
        auditLogger.warn(auditMessage.toString());
        throw e;
    }

}

From source file:com.netflix.genie.web.security.saml.SAMLUserDetailsServiceImplUnitTests.java

/**
 * Test to make sure a null credential throws exception.
 *//*  w w  w .ja  v  a  2  s  .  c om*/
@Test(expected = UsernameNotFoundException.class)
public void doesThrowErrorOnNullCredential() {
    this.service.loadUserBySAML(null);
    Mockito.verify(this.loadAuthenticationTimer, Mockito.times(1)).record(Mockito.anyLong(),
            Mockito.eq(TimeUnit.NANOSECONDS));
}

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

/**
 * Test method for {@link SimpleTimer#startStopwatch(int, TimeUnit)}.
 *//*from w ww . j av  a 2 s  .  c o m*/
@Test
public final void testStartStopwatch() {
    assertNotNull(this.timer.startStopwatch(1, TimeUnit.NANOSECONDS));
}

From source file:me.oriley.crate.CrateGenerator.java

public void buildCrate() {
    long startNanos = System.nanoTime();
    File variantDir = new File(mVariantAssetDir);
    if (!variantDir.exists() || !variantDir.isDirectory()) {
        log("Asset directory does not exist, aborting");
        return;//  w ww. j a v a2s  . c o  m
    }

    try {
        brewJava(variantDir, mVariantAssetDir, PACKAGE_NAME).writeTo(new File(mBaseOutputDir));
    } catch (IOException e) {
        logError("Failed to generate java", e, true);
    }

    long lengthMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
    log("Time to build was " + lengthMillis + "ms");
}

From source file:com.hpcloud.util.Duration.java

public static Duration nanos(long count) {
    return new Duration(count, TimeUnit.NANOSECONDS);
}

From source file:at.alladin.rmbt.client.v2.task.TracerouteTask.java

/**
 * /*from   w ww  .ja  v a  2 s. c  om*/
 */
public QoSTestResult call() throws Exception {
    final QoSTestResult testResult = initQoSTestResult(QoSTestResultEnum.TRACEROUTE);

    testResult.getResultMap().put(RESULT_HOST, host);
    testResult.getResultMap().put(RESULT_TIMEOUT, timeout);
    testResult.getResultMap().put(RESULT_MAX_HOPS, maxHops);

    try {
        onStart(testResult);
        final TracerouteService pingTool = getQoSTest().getTestSettings().getTracerouteServiceClazz()
                .newInstance();
        pingTool.setHost(host);
        pingTool.setMaxHops(maxHops);

        final Future<List<HopDetail>> traceFuture = RMBTClient.getCommonThreadPool().submit(pingTool);
        try {
            final List<HopDetail> pingDetailList = traceFuture.get(timeout, TimeUnit.NANOSECONDS);
            if (!pingTool.hasMaxHopsExceeded()) {
                testResult.getResultMap().put(RESULT_STATUS, "OK");
                testResult.getResultMap().put(RESULT_HOPS, pingDetailList.size());
            } else {
                testResult.getResultMap().put(RESULT_STATUS, "MAX_HOPS_EXCEEDED");
                testResult.getResultMap().put(RESULT_HOPS, maxHops);
            }
            JSONArray resultArray = new JSONArray();
            for (final HopDetail p : pingDetailList) {
                JSONObject json = p.toJson();
                if (json != null) {
                    resultArray.put(json);
                }
            }
            testResult.getResultMap().put(RESULT_DETAILS, resultArray);
        } catch (TimeoutException e) {
            testResult.getResultMap().put(RESULT_STATUS, "TIMEOUT");
        }
    } catch (Exception e) {
        e.printStackTrace();
        testResult.getResultMap().put(RESULT_STATUS, "ERROR");
    } finally {
        onEnd(testResult);
    }

    return testResult;
}