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:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java

/**
 * Revocation check function 1. use ocsp first if it is enabled 2. fail if
 * the cert is revoked 3. Fall back to CRL if ocsp fails for reason other
 * then revoked 4. CRL validation using provided URL and in-cert URL
 *
 * Note:OCSP nonce extension appears not currently controllable in Java's
 * default OCSPChecker./*from www  .  j  ava 2 s  . co m*/
 *
 * @param certs
 *            Client cert chain. It could be a leaf certificate, a partial or a
 *            full chain including root CA.
 * Current implementation only relies on leaf certificate and use it to build certificate path then validate it.
 * @param authStatExt
 *            AuthStat extensions for profiling the detailed steps.
 * @throws CertificateRevocationCheckException unable to validate revocation status.
 * @throws IdmCertificateRevokedException  certificate revoked
 * @throws InvalidArgumentException
 * @throws CertificatePathBuildingException  cert path building error of any reasons: such as expired cert, etc.
 */
public void validate(X509Certificate cert, Map<String, String> authStatExt)
        throws CertificateRevocationCheckException, IdmCertificateRevokedException, InvalidArgumentException,
        CertificatePathBuildingException {

    if (null == cert) {
        throw new InvalidArgumentException("No certs to validate.");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Certificate policy: " + this.certPolicy.toString());
        logger.debug("Checking revocation for certificate: " + cert.getSubjectDN());
    }

    // Build the certpath
    long startTime = System.nanoTime();

    CertPath certPath = buildCertPath(cert);

    authStatExt.put("buildCertPath",
            String.format("%d Ms", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)));
    startTime = System.nanoTime();

    // Validate certpath
    validateCertPath(certPath);
    authStatExt.put("validateCertPath",
            String.format("%d Ms", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)));
    logger.info("Successfully validated client certificate : " + cert.getSubjectDN());

}

From source file:codeswarm.code_swarm.java

/**
 * Initialisation/*from  w  w w  .  j a  v a2 s. c o  m*/
 */
public void setup() {
    width = cfg.getIntProperty(CodeSwarmConfig.WIDTH_KEY, 640);
    if (width <= 0) {
        width = 640;
    }

    height = cfg.getIntProperty(CodeSwarmConfig.HEIGHT_KEY, 480);
    if (height <= 0) {
        height = 480;
    }

    maxBackgroundThreads = cfg.getIntProperty(CodeSwarmConfig.MAX_THREADS_KEY, 4);
    if (maxBackgroundThreads <= 0) {
        maxBackgroundThreads = 4;
    }
    backgroundExecutor = new ThreadPoolExecutor(1, maxBackgroundThreads, Long.MAX_VALUE, TimeUnit.NANOSECONDS,
            new ArrayBlockingQueue<Runnable>(4 * maxBackgroundThreads),
            new ThreadPoolExecutor.CallerRunsPolicy());

    if (cfg.getBooleanProperty(CodeSwarmConfig.USE_OPEN_GL, false)) {
        size(width, height, OPENGL);
    } else {
        size(width, height);
    }

    showLegend = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_LEGEND, false);
    showHistogram = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_HISTORY, false);
    showDate = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_DATE, false);
    showEdges = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_EDGES, false);
    showDebug = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_DEBUG, false);
    takeSnapshots = cfg.getBooleanProperty(CodeSwarmConfig.TAKE_SNAPSHOTS_KEY, false);
    drawNamesSharp = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_NAMES_SHARP, true);
    drawNamesHalos = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_NAMES_HALOS, false);
    drawFilesSharp = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_SHARP, false);
    drawFilesFuzzy = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_FUZZY, true);
    drawFilesJelly = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_JELLY, false);
    background = cfg.getBackground().getRGB();

    UPDATE_DELTA = cfg.getIntProperty(CodeSwarmConfig.MSEC_PER_FRAME_KEY, -1);
    if (UPDATE_DELTA == -1) {
        int framesperday = cfg.getIntProperty(CodeSwarmConfig.FRAMES_PER_DAY_KEY, 4);
        if (framesperday > 0) {
            UPDATE_DELTA = (86400000 / framesperday);
        }
    }
    if (UPDATE_DELTA <= 0) {
        // Default to 4 frames per day.
        UPDATE_DELTA = 21600000;
    }

    isInputSorted = cfg.getBooleanProperty(CodeSwarmConfig.IS_INPUT_SORTED_KEY, false);

    /**
     * This section loads config files and calls the setup method for all physics engines.
     */

    physicsEngineConfigDir = cfg.getStringProperty(CodeSwarmConfig.PHYSICS_ENGINE_CONF_DIR, "physics_engine");
    File f = new File(physicsEngineConfigDir);
    String[] configFiles = null;
    if (f.exists() && f.isDirectory()) {
        configFiles = f.list();
    }
    for (int i = 0; configFiles != null && i < configFiles.length; i++) {
        if (configFiles[i].endsWith(".config")) {
            Properties p = new Properties();
            String ConfigPath = physicsEngineConfigDir + System.getProperty("file.separator") + configFiles[i];
            try {
                p.load(new FileInputStream(ConfigPath));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.exit(1);
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
            String ClassName = p.getProperty("name", "__DEFAULT__");
            if (!ClassName.equals("__DEFAULT__")) {
                PhysicsEngine pe = getPhysicsEngine(ClassName);
                pe.setup(p);
                mPhysicsEngineChoices.add(pe);
            } else {
                logger.error("Skipping config file '" + ConfigPath
                        + "'.  Must specify class name via the 'name' parameter.");
                System.exit(1);
            }
        }
    }

    if (mPhysicsEngineChoices.size() == 0) {
        logger.error("No physics engine config files found in '" + physicsEngineConfigDir + "'.");
        System.exit(1);
    }

    // Physics engine configuration and instantiation
    physicsEngineSelection = cfg.getStringProperty(CodeSwarmConfig.PHYSICS_ENGINE_SELECTION,
            PHYSICS_ENGINE_LEGACY);

    for (PhysicsEngine p : mPhysicsEngineChoices) {
        if (physicsEngineSelection.equals(p.getClass().getName())) {
            mPhysicsEngine = p;
        }
    }

    if (mPhysicsEngine == null) {
        logger.error("No physics engine matches your choice of '" + physicsEngineSelection + "'. Check '"
                + physicsEngineConfigDir + "' for options.");
        System.exit(1);
    }

    smooth();
    frameRate(FRAME_RATE);

    // init data structures
    nodes = new CopyOnWriteArrayList<FileNode>();
    edges = new CopyOnWriteArrayList<Edge>();
    people = new CopyOnWriteArrayList<PersonNode>();
    history = new LinkedList<ColorBins>();

    if (isInputSorted) {
        //If the input is sorted, we only need to store the next few events
        eventsQueue = new ArrayBlockingQueue<FileEvent>(5000);
    } else {
        //Otherwise we need to store them all at once in a data structure that will sort them
        eventsQueue = new PriorityBlockingQueue<FileEvent>();
    }

    // Init color map
    initColors();

    loadRepEvents(cfg.getStringProperty(CodeSwarmConfig.INPUT_FILE_KEY)); // event formatted (this is the standard)
    synchronized (this) {
        while (!finishedLoading && eventsQueue.isEmpty()) {
            try {
                wait();
            } catch (InterruptedException e) {
                logger.error("The ready-check thread was interrupted", e);
            }
        }
    }
    prevDate = eventsQueue.peek().getDate();

    SCREENSHOT_FILE = cfg.getStringProperty(CodeSwarmConfig.SNAPSHOT_LOCATION_KEY);

    maxFramesSaved = (int) Math.pow(10, SCREENSHOT_FILE.replaceAll("[^#]", "").length());

    // Create fonts
    String fontName = cfg.getStringProperty(CodeSwarmConfig.FONT_KEY, "SansSerif");
    String fontNameBold = cfg.getStringProperty(CodeSwarmConfig.FONT_KEY_BOLD, "SansSerif");
    Integer fontSize = cfg.getIntProperty(CodeSwarmConfig.FONT_SIZE, 10);
    Integer fontSizeBold = cfg.getIntProperty(CodeSwarmConfig.FONT_SIZE_BOLD, 14);
    font = createFont(fontName, fontSize);
    boldFont = createFont(fontNameBold, fontSizeBold);

    textFont(font);

    // Create the file particle image
    sprite = loadImage(cfg.getStringProperty(CodeSwarmConfig.SPRITE_FILE_KEY, "particle.png"));
    // Add translucency (using itself in this case)
    sprite.mask(sprite);
}

From source file:org.apache.solr.handler.TestSolrConfigHandlerConcurrent.java

private void invokeBulkCall(String cacheName, List<String> errs, Map val) throws Exception {

    String payload = "{" + "'set-property' : {'query.CACHENAME.size':'CACHEVAL1',"
            + "                  'query.CACHENAME.initialSize':'CACHEVAL2'},"
            + "'set-property': {'query.CACHENAME.autowarmCount' : 'CACHEVAL3'}" + "}";

    Set<String> errmessages = new HashSet<>();
    for (int i = 1; i < 2; i++) {//make it  ahigher number
        RestTestHarness publisher = restTestHarnesses.get(r.nextInt(restTestHarnesses.size()));
        String response;/*from w  w  w. j  a va  2s .  c o m*/
        String val1;
        String val2;
        String val3;
        try {
            payload = payload.replaceAll("CACHENAME", cacheName);
            val1 = String.valueOf(10 * i + 1);
            payload = payload.replace("CACHEVAL1", val1);
            val2 = String.valueOf(10 * i + 2);
            payload = payload.replace("CACHEVAL2", val2);
            val3 = String.valueOf(10 * i + 3);
            payload = payload.replace("CACHEVAL3", val3);

            response = publisher.post("/config?wt=json", SolrTestCaseJ4.json(payload));
        } finally {
            publisher.close();
        }

        Map map = (Map) getVal(new JSONParser(new StringReader(response)));
        Object errors = map.get("errors");
        if (errors != null) {
            errs.add(new String(Utils.toJSON(errors), StandardCharsets.UTF_8));
            return;
        }

        DocCollection coll = cloudClient.getZkStateReader().getClusterState().getCollection("collection1");
        List<String> urls = new ArrayList<>();
        for (Slice slice : coll.getSlices()) {
            for (Replica replica : slice.getReplicas())
                urls.add("" + replica.get(ZkStateReader.BASE_URL_PROP) + "/"
                        + replica.get(ZkStateReader.CORE_NAME_PROP));
        }

        //get another node
        String url = urls.get(urls.size());

        long startTime = System.nanoTime();
        long maxTimeoutSeconds = 20;
        while (TimeUnit.SECONDS.convert(System.nanoTime() - startTime,
                TimeUnit.NANOSECONDS) < maxTimeoutSeconds) {
            Thread.sleep(100);
            errmessages.clear();
            Map respMap = getAsMap(url + "/config/overlay?wt=json", cloudClient);
            Map m = (Map) respMap.get("overlay");
            if (m != null)
                m = (Map) m.get("props");
            if (m == null) {
                errmessages.add(StrUtils.formatString(
                        "overlay does not exist for cache: {0} , iteration: {1} response {2} ", cacheName, i,
                        respMap.toString()));
                continue;
            }

            Object o = getObjectByPath(m, true, asList("query", cacheName, "size"));
            if (!val1.equals(o))
                errmessages.add(
                        StrUtils.formatString("'size' property not set, expected = {0}, actual {1}", val1, o));

            o = getObjectByPath(m, true, asList("query", cacheName, "initialSize"));
            if (!val2.equals(o))
                errmessages.add(StrUtils
                        .formatString("'initialSize' property not set, expected = {0}, actual {1}", val2, o));

            o = getObjectByPath(m, true, asList("query", cacheName, "autowarmCount"));
            if (!val3.equals(o))
                errmessages.add(StrUtils
                        .formatString("'autowarmCount' property not set, expected = {0}, actual {1}", val3, o));
            if (errmessages.isEmpty())
                break;
        }
        if (!errmessages.isEmpty()) {
            errs.addAll(errmessages);
            return;
        }
    }

}

From source file:org.apache.flink.yarn.YARNSessionFIFOITCase.java

/**
 * Test regular operation, including command line parameter parsing.
 *///from ww w  .j a  v  a 2s  . c  o  m
@Test(timeout = 60000) // timeout after a minute.
public void testDetachedMode() throws InterruptedException, IOException {
    LOG.info("Starting testDetachedMode()");
    addTestAppender(FlinkYarnSessionCli.class, Level.INFO);

    File exampleJarLocation = getTestJarPath("StreamingWordCount.jar");
    // get temporary file for reading input data for wordcount example
    File tmpInFile = tmp.newFile();
    FileUtils.writeStringToFile(tmpInFile, WordCountData.TEXT);

    ArrayList<String> args = new ArrayList<>();
    args.add("-j");
    args.add(flinkUberjar.getAbsolutePath());

    args.add("-t");
    args.add(flinkLibFolder.getAbsolutePath());

    args.add("-n");
    args.add("1");

    args.add("-jm");
    args.add("768m");

    args.add("-tm");
    args.add("1024m");

    if (SecureTestEnvironment.getTestKeytab() != null) {
        args.add("-D" + SecurityOptions.KERBEROS_LOGIN_KEYTAB.key() + "="
                + SecureTestEnvironment.getTestKeytab());
    }
    if (SecureTestEnvironment.getHadoopServicePrincipal() != null) {
        args.add("-D" + SecurityOptions.KERBEROS_LOGIN_PRINCIPAL.key() + "="
                + SecureTestEnvironment.getHadoopServicePrincipal());
    }
    args.add("--name");
    args.add("MyCustomName");

    args.add("--detached");

    Runner clusterRunner = startWithArgs(args.toArray(new String[args.size()]),
            "Flink JobManager is now running on", RunTypes.YARN_SESSION);

    // before checking any strings outputted by the CLI, first give it time to return
    clusterRunner.join();

    // actually run a program, otherwise we wouldn't necessarily see any TaskManagers
    // be brought up
    Runner jobRunner = startWithArgs(
            new String[] { "run", "--detached", exampleJarLocation.getAbsolutePath(), "--input",
                    tmpInFile.getAbsoluteFile().toString() },
            "Job has been submitted with JobID", RunTypes.CLI_FRONTEND);

    jobRunner.join();

    // in "new" mode we can only wait after the job is submitted, because TMs
    // are spun up lazily
    LOG.info("Waiting until two containers are running");
    // wait until two containers are running
    while (getRunningContainers() < 2) {
        sleep(500);
    }

    // make sure we have two TMs running in either mode
    long startTime = System.nanoTime();
    while (System.nanoTime() - startTime < TimeUnit.NANOSECONDS.convert(10, TimeUnit.SECONDS)
            && !(verifyStringsInNamedLogFiles(new String[] { "switched from state RUNNING to FINISHED" },
                    "jobmanager.log"))) {
        LOG.info("Still waiting for cluster to finish job...");
        sleep(500);
    }

    LOG.info("Two containers are running. Killing the application");

    // kill application "externally".
    try {
        YarnClient yc = YarnClient.createYarnClient();
        yc.init(YARN_CONFIGURATION);
        yc.start();
        List<ApplicationReport> apps = yc.getApplications(EnumSet.of(YarnApplicationState.RUNNING));
        Assert.assertEquals(1, apps.size()); // Only one running
        ApplicationReport app = apps.get(0);

        Assert.assertEquals("MyCustomName", app.getName());
        ApplicationId id = app.getApplicationId();
        yc.killApplication(id);

        while (yc.getApplications(EnumSet.of(YarnApplicationState.KILLED)).size() == 0
                && yc.getApplications(EnumSet.of(YarnApplicationState.FINISHED)).size() == 0) {
            sleep(500);
        }
    } catch (Throwable t) {
        LOG.warn("Killing failed", t);
        Assert.fail();
    } finally {

        //cleanup the yarn-properties file
        String confDirPath = System.getenv("FLINK_CONF_DIR");
        File configDirectory = new File(confDirPath);
        LOG.info("testDetachedPerJobYarnClusterInternal: Using configuration directory "
                + configDirectory.getAbsolutePath());

        // load the configuration
        LOG.info("testDetachedPerJobYarnClusterInternal: Trying to load configuration file");
        Configuration configuration = GlobalConfiguration.loadConfiguration(configDirectory.getAbsolutePath());

        try {
            File yarnPropertiesFile = FlinkYarnSessionCli.getYarnPropertiesLocation(
                    configuration.getString(YarnConfigOptions.PROPERTIES_FILE_LOCATION));
            if (yarnPropertiesFile.exists()) {
                LOG.info(
                        "testDetachedPerJobYarnClusterInternal: Cleaning up temporary Yarn address reference: {}",
                        yarnPropertiesFile.getAbsolutePath());
                yarnPropertiesFile.delete();
            }
        } catch (Exception e) {
            LOG.warn(
                    "testDetachedPerJobYarnClusterInternal: Exception while deleting the JobManager address file",
                    e);
        }
    }

    LOG.info("Finished testDetachedMode()");
}

From source file:org.apache.hadoop.hive.ql.exec.tez.TezSessionState.java

public boolean isOpening() {
    if (session != null || sessionFuture == null)
        return false;
    try {/*  w  w w  .  j  av  a  2 s  .  c  o  m*/
        session = sessionFuture.get(0, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return false;
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    } catch (CancellationException e) {
        return false;
    } catch (TimeoutException e) {
        return true;
    }
    return false;
}

From source file:fathom.Boot.java

/**
 * Starts Fathom synchronously./*  w w w .j a  va2 s .  co m*/
 */
@Override
public synchronized void start() {
    Preconditions.checkNotNull(getServer());

    String osName = System.getProperty("os.name");
    String osVersion = System.getProperty("os.version");
    log.info("Bootstrapping {} ({})", settings.getApplicationName(), settings.getApplicationVersion());
    Util.logSetting(log, "Fathom", Constants.getVersion());
    Util.logSetting(log, "Mode", settings.getMode().toString());
    Util.logSetting(log, "Operating System", String.format("%s (%s)", osName, osVersion));
    Util.logSetting(log, "Available processors", Runtime.getRuntime().availableProcessors());
    Util.logSetting(log, "Available heap", (Runtime.getRuntime().maxMemory() / (1024 * 1024)) + " MB");

    SimpleDateFormat df = new SimpleDateFormat("z Z");
    df.setTimeZone(TimeZone.getDefault());
    String offset = df.format(new Date());
    Util.logSetting(log, "JVM timezone", String.format("%s (%s)", TimeZone.getDefault().getID(), offset));
    Util.logSetting(log, "JVM locale", Locale.getDefault());

    long startTime = System.nanoTime();
    getServer().start();

    String contextPath = settings.getContextPath();

    if (settings.getHttpsPort() > 0) {
        log.info("https://{}:{}{}", settings.getHttpsListenAddress(), settings.getHttpsPort(), contextPath);
    }
    if (settings.getHttpPort() > 0) {
        log.info("http://{}:{}{}", settings.getHttpListenAddress(), settings.getHttpPort(), contextPath);
    }
    if (settings.getAjpPort() > 0) {
        log.info("ajp://{}:{}{}", settings.getAjpListenAddress(), settings.getAjpPort(), contextPath);
    }

    long delta = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
    String duration;
    if (delta < 1000L) {
        duration = String.format("%s ms", delta);
    } else {
        duration = String.format("%.1f seconds", (delta / 1000f));
    }
    log.info("Fathom bootstrapped {} mode in {}", settings.getMode().toString(), duration);
    log.info("READY.");

}

From source file:com.vmware.identity.saml.idm.IdmPrincipalAttributesExtractor.java

@Override
public boolean isActive(PrincipalId principalId) throws InvalidPrincipalException, SystemException {
    try {//from w  w  w .  j  a  v a2s  .co m
        final long start = System.nanoTime();
        final boolean result = idmClient.isActive(tenantName, principalId);
        perfLog.trace("'idmClient.isActive' took {} ms.",
                TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start));
        return result;
    } catch (com.vmware.identity.idm.InvalidPrincipalException | NoSuchIdpException e) {
        throw new InvalidPrincipalException(e);
    } catch (Exception e) {
        throw new SystemException(e);
    }
}

From source file:com.continuuity.weave.kafka.client.KafkaTest.java

private long secondsPassed(long startTime, TimeUnit startUnit) {
    return TimeUnit.SECONDS.convert(System.nanoTime() - TimeUnit.NANOSECONDS.convert(startTime, startUnit),
            TimeUnit.NANOSECONDS);
}

From source file:com.netflix.genie.core.services.impl.S3FileTransferImpl.java

/**
 * {@inheritDoc}/*from  w ww  . j a  va2  s.c o  m*/
 */
@Override
public void putFile(@NotBlank(message = "Source local path cannot be empty.") final String srcLocalPath,
        @NotBlank(message = "Destination remote path cannot be empty") final String dstRemotePath)
        throws GenieException {
    final long start = System.nanoTime();
    final Map<String, String> tags = MetricsUtils.newSuccessTagsMap();
    try {
        log.debug("Called with src path {} and destination path {}", srcLocalPath, dstRemotePath);

        final AmazonS3URI s3Uri = getS3Uri(dstRemotePath);
        try {
            this.s3Client.putObject(s3Uri.getBucket(), s3Uri.getKey(), new File(srcLocalPath));
        } catch (AmazonS3Exception ase) {
            log.error("Error posting file {} to s3 due to exception {}", dstRemotePath, ase);
            throw new GenieServerException("Error uploading file to s3. Filename: " + dstRemotePath);
        }
    } catch (Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        this.registry.timer(uploadTimerId.withTags(tags)).record(System.nanoTime() - start,
                TimeUnit.NANOSECONDS);

    }
}

From source file:com.amazonaws.util.TimingInfo.java

@Deprecated
public final long getStartTime() {
    return isStartEpochTimeMilliKnown() ? startEpochTimeMilli
            // best effort even though technically this is incorrect
            : TimeUnit.NANOSECONDS.toMillis(startTimeNano);
}