List of usage examples for org.apache.commons.lang.time StopWatch StopWatch
public StopWatch()
Constructor.
From source file:org.caleydo.neo4j.plugins.kshortestpaths.KShortestPathsAlgo.java
public List<WeightedPath> run(Node sourceNode, Node targetNode, int k, IPathReadyListener onPathReady) { StopWatch w = new StopWatch(); w.start();//from ww w . j a va 2 s.com // Calculate shortest path first List<WeightedPath> paths = new ArrayList<>(k); profile("start", w); WeightedPath shortestPath = shortestPathFinder.findSinglePath(sourceNode, targetNode); if (shortestPath == null) return paths; profile("initial disjkra", w); PriorityQueue<WeightedPath> pathCandidates = new PriorityQueue<WeightedPath>(20, new Comparator<WeightedPath>() { @Override public int compare(WeightedPath o1, WeightedPath o2) { return Double.compare(o1.weight(), o2.weight()); } }); Set<Integer> pathCandidateHashes = new HashSet<>(); if (onPathReady != null) { onPathReady.onPathReady(shortestPath); } paths.add(shortestPath); pathCandidateHashes.add(generatePathHash(shortestPath)); for (int i = 1; i < k; i++) { WeightedPath prevPath = paths.get(i - 1); for (Node spurNode : prevPath.nodes()) { if (spurNode.getId() == prevPath.endNode().getId()) break; WeightedPath rootPath = getSubPathTo(prevPath, spurNode); for (Path path : paths) { Iterator<Relationship> pathIterator = path.relationships().iterator(); boolean containsRootPath = true; // Test if the existing shortest path starts with the root path for (Relationship relationship : rootPath.relationships()) { if (!pathIterator.hasNext()) { containsRootPath = false; break; } Relationship pathRelationship = pathIterator.next(); if (relationship.getId() != pathRelationship.getId()) { containsRootPath = false; break; } } // If so, set edge weight of following edge in that path to infinity if (containsRootPath) { if (pathIterator.hasNext()) { Relationship r = pathIterator.next(); costEvaluator.addInvalidRelationship(r); //profile("invalid: "+r,w); } } } // Simulate removal of root path nodes (except spur node) by setting all their edge weights to // infinity Set<Long> badIds = new HashSet<Long>(); for (Node rootPathNode : rootPath.nodes()) { if (rootPathNode.getId() != spurNode.getId()) { badIds.add(rootPathNode.getId()); //for (Relationship relationship : getRelationships(rootPathNode)) { // costEvaluator.addInvalidRelationship(relationship); //} //profile("invalids: "+rootPathNode.getRelationships(),w); } } expander.setExtraIgnoreNodes(badIds); profile("Find next path", w); WeightedPath spurPath = shortestPathFinder.findSinglePath(spurNode, targetNode); profile("Found next path", w); if (spurPath != null && !Double.isInfinite(spurPath.weight())) { WeightedPath pathCandidate = concatenate(rootPath, spurPath); Integer pathHash = generatePathHash(pathCandidate); if (!pathCandidateHashes.contains(pathHash)) { pathCandidates.add(pathCandidate); pathCandidateHashes.add(pathHash); } } // Restore edges costEvaluator.clearInvalidRelationships(); expander.setExtraIgnoreNodes(null); } if (pathCandidates.isEmpty()) break; WeightedPath nextBest = pathCandidates.poll(); profile("flush path", w); if (onPathReady != null) { onPathReady.onPathReady(nextBest); } paths.add(nextBest); } profile("done", w); return paths; }
From source file:org.cesecore.audit.log.InternalSecurityEventsLoggerSessionBean.java
@Override public void log(final TrustedTime trustedTime, final EventType eventType, final EventStatus eventStatus, final ModuleType module, final ServiceType service, final String authToken, final String customId, final String searchDetail1, final String searchDetail2, final Map<String, Object> additionalDetails) throws AuditRecordStorageException { if (LogServiceState.INSTANCE.isDisabled()) { throw new AuditRecordStorageException("Security audit logging is currently disabled."); }// w w w . j a v a 2s . com final Map<Class<?>, Object> ejbs = getEjbs(); boolean anyFailures = false; for (final String loggerId : AuditDevicesConfig.getAllDeviceIds()) { try { StopWatch sw = null; if (LOG.isDebugEnabled()) { sw = new StopWatch(); sw.start(); } AuditDevicesConfig.getDevice(ejbs, loggerId).log(trustedTime, eventType, eventStatus, module, service, authToken, customId, searchDetail1, searchDetail2, additionalDetails, AuditDevicesConfig.getProperties(loggerId)); if (LOG.isDebugEnabled()) { sw.stop(); LOG.debug("LogDevice: " + loggerId + " Proc: " + sw.getTime()); } } catch (Exception e) { // AuditRecordStorageException anyFailures = true; LOG.error("AuditDevice " + loggerId + " failed. An event was not logged to this device!", e); } } if (anyFailures) { // CESeCore.FAU_STG.4.1: The TSF shall prevent audited events, except those taken by the Auditable and no other actions if the audit trail is full. // So even if we failed to produce a proper audit trail for these events, we swallow the exception here to allow the operation to continue. if (!eventType.equals(EventTypes.LOG_VERIFY) && !eventType.equals(EventTypes.LOG_EXPORT) && !eventType.equals(EventTypes.LOG_DELETE) && !eventType.equals(EventTypes.LOG_SIGN) && !eventType.equals(EventTypes.LOG_MANAGEMENT_CHANGE)) { throw new AuditRecordStorageException("Failed to write audit log to at least one device."); } } }
From source file:org.cesecore.audit.log.SecurityEventsLoggerSessionBeanTest.java
@Test public void test04SecureMultipleLog() throws Exception { log.trace(">test03SecureMultipleLog"); final int THREADS = 50; final int WORKERS = 400; final int TIMEOUT_MS = 30000; final ThreadPoolExecutor workers = (ThreadPoolExecutor) Executors.newFixedThreadPool(THREADS); final StopWatch time = new StopWatch(); time.start();/*from ww w . ja v a 2 s. co m*/ for (int i = 0; i < WORKERS; i++) { workers.execute(new Runnable() { // NOPMD: this is a test, not a JEE application @Override public void run() { try { securityEventsLogger.log(roleMgmgToken, EventTypes.AUTHENTICATION, EventStatus.SUCCESS, ModuleTypes.SECURITY_AUDIT, ServiceTypes.CORE); } catch (AuthorizationDeniedException e) { fail("should be authorized"); } } }); } while (workers.getCompletedTaskCount() < WORKERS && time.getTime() < TIMEOUT_MS) { Thread.sleep(250); } time.stop(); final long completedTaskCount = workers.getCompletedTaskCount(); log.info("securityEventsLogger.log: " + completedTaskCount + " completed in " + time.toString() + " using " + THREADS + " threads."); workers.shutdown(); for (final String logDeviceId : securityEventsAuditor.getQuerySupportingLogDevices()) { final AuditLogValidationReport report = securityEventsAuditor.verifyLogsIntegrity(roleMgmgToken, new Date(), logDeviceId); assertNotNull(report); final StringBuilder strBuilder = new StringBuilder(); for (final AuditLogReportElem error : report.errors()) { strBuilder.append(String.format("invalid sequence: %d %d\n", error.getFirst(), error.getSecond())); for (final String reason : error.getReasons()) { strBuilder.append(String.format("Reason: %s\n", reason)); } } assertTrue("validation report: " + strBuilder.toString(), (report.warnings().size() == 1 || report.warnings().size() == 0) && report.errors().size() == 0); } log.trace("<test03SecureMultipleLog"); }
From source file:org.codehaus.gmaven.runtime.loader.DefaultProviderManager.java
public Provider select(final String selection) { assert selection != null; Provider provider = (Provider) cachedSelection.get(selection); if (provider != null) { log.debug("Using cached provider '{}' for selection: {}", provider, selection); } else {// w ww. ja v a 2 s . c o m log.debug("Selecting provider; selection: {}", selection); StopWatch watch = new StopWatch(); watch.start(); try { provider = getSelector().select(getRegistry(), selection); } catch (Exception e) { throw new ProviderException("Selection of provider failed; selection: " + selection, e); } if (provider == null) { throw new ProviderException("No providers found matching selection: " + selection); } cachedSelection.put(selection, provider); watch.stop(); log.debug("Selected provider: {} ({})", provider, watch); } return provider; }
From source file:org.codehaus.grepo.procedure.repository.GenericProcedureMethodInterceptor.java
/** * {@inheritDoc}/*from w ww. java 2s . co m*/ */ public Object invoke(MethodInvocation invocation) throws Throwable { StopWatch watch = null; Object result = null; GenericProcedureRepository repo = (GenericProcedureRepository) invocation.getThis(); ProcedureMethodParameterInfo pmpi = new ProcedureMethodParameterInfoImpl(invocation.getMethod(), invocation.getArguments()); if (logger.isDebugEnabled()) { watch = new StopWatch(); watch.start(); logger.debug("Invoking method '{}'", pmpi.getMethodName()); } try { GenericProcedure annotation = pmpi.getMethodAnnotation(GenericProcedure.class); if (annotation == null) { // no GenericProcedure annotation present, so do not invoke via aop... logger.debug( "Method '{}' is not annotated with @GenericProcedure - " + "invocation will proceed to implementation '{}'", pmpi.getMethodName(), repo.getClass().getName()); result = invocation.proceed(); } else { result = repo.executeGenericProcedure(pmpi, annotation); } } finally { if (logger.isDebugEnabled()) { watch.stop(); logger.debug("Invocation of method '{}' took '{}'", pmpi.getMethodName(), watch); } } return result; }
From source file:org.codehaus.grepo.query.commons.repository.GenericQueryMethodInterceptor.java
/** * {@inheritDoc}//from w w w . j a v a 2 s .c o m * * @param invocation Invokes methods dynamically. * @return Returns the result of the method invocation. * @throws Throwable in case of errors. */ public Object invoke(MethodInvocation invocation) throws Throwable { StopWatch watch = null; Object result = null; if (logger.isDebugEnabled()) { watch = new StopWatch(); watch.start(); } GenericQueryRepository<?> repo = (GenericQueryRepository<?>) invocation.getThis(); QueryMethodParameterInfo qmpi = new QueryMethodParameterInfoImpl(invocation.getMethod(), invocation.getArguments(), repo.getEntityClass()); logger.debug("Invoking method '{}'", qmpi.getMethodName()); try { GenericQuery annotation = qmpi.getMethodAnnotation(GenericQuery.class); if (annotation == null) { // no GenericQuery annotation present, so do not invoke via aop... logger.debug( "Method '{}' is not annotated with @GenericQuery - " + "invocation will proceed to implementation '{}'", qmpi.getMethodName(), repo.getClass().getName()); result = invocation.proceed(); } else { result = repo.executeGenericQuery(qmpi, annotation); } } finally { if (logger.isDebugEnabled()) { watch.stop(); logger.debug("Invocation of method '{}' took '{}'", qmpi.getMethodName(), watch); } } return result; }
From source file:org.codehaus.mojo.jspc.CompilationMojoSupport.java
public void execute() throws MojoExecutionException, MojoFailureException { if (skip) {/*from w w w .ja va 2 s . c o m*/ return; } final Log log = this.getLog(); final boolean isWar = "war".equals(project.getPackaging()); if (!isWar) { log.warn("Compiled JSPs will not be added to the project and web.xml will " + "not be modified because the project's packaging is not 'war'."); } if (!includeInProject) { log.warn("Compiled JSPs will not be added to the project and web.xml will " + "not be modified because includeInProject is set to false."); } final JspCompiler jspCompiler = this.jspCompilerFactory.createJspCompiler(); // Setup defaults (complex, can"t init from expression) if (sources == null) { sources = new FileSet(); sources.setDirectory(this.defaultSourcesDirectory.getAbsolutePath()); sources.setExcludes(Arrays.asList("WEB-INF/web.xml", "META-INF/**")); } jspCompiler.setWebappDirectory(sources.getDirectory()); log.debug("Source directory: " + this.sources.getDirectory()); jspCompiler.setOutputDirectory(this.workingDirectory); log.debug("Output directory: " + this.workingDirectory); jspCompiler.setEncoding(this.javaEncoding); log.debug("Encoding: " + this.javaEncoding); jspCompiler.setShowSuccess(this.showSuccess); jspCompiler.setListErrors(this.listErrors); jspCompiler.setWebFragmentFile(webFragmentFile); log.debug("Web Fragment: " + this.webFragmentFile); jspCompiler.setPackageName(packageName); log.debug("Package Name: " + this.packageName); final List<String> classpathElements = getClasspathElements(); jspCompiler.setClasspath(classpathElements); log.debug("Classpath: " + classpathElements); final List<File> jspFiles; if (sources.getIncludes() != null) { //Always need to get a full list of JSP files as incremental builds would result in an invalid web.xml final Scanner scanner = this.buildContext.newScanner(new File(sources.getDirectory()), true); scanner.setIncludes(sources.getIncludesArray()); scanner.setExcludes(sources.getExcludesArray()); scanner.addDefaultExcludes(); scanner.scan(); final String[] includes = scanner.getIncludedFiles(); jspFiles = new ArrayList<File>(includes.length); for (final String it : includes) { jspFiles.add(new File(sources.getDirectory(), it)); } } else { jspFiles = Collections.emptyList(); } jspCompiler.setSmapDumped(smapDumped); jspCompiler.setSmapSuppressed(smapSuppressed); jspCompiler.setCompile(compile); jspCompiler.setValidateXml(validateXml); jspCompiler.setTrimSpaces(trimSpaces); jspCompiler.setVerbose(verbose); jspCompiler.setErrorOnUseBeanInvalidClassAttribute(errorOnUseBeanInvalidClassAttribute); jspCompiler.setCompilerSourceVM(source); jspCompiler.setCompilerTargetVM(target); jspCompiler.setCaching(caching); jspCompiler.setGenStringAsCharArray(genStringAsCharArray); jspCompiler.setPoolingEnabled(poolingEnabled); jspCompiler.setClassDebugInfo(classDebugInfo); jspCompiler.setCompileThreads(compileThreads); jspCompiler.setCompileTimeout(TimeUnit.MINUTES.toMillis(compilationTimeout)); // Make directories if needed workingDirectory.mkdirs(); webFragmentFile.getParentFile().mkdirs(); outputWebXml.getParentFile().mkdirs(); // JspC needs URLClassLoader, with tools.jar final ClassLoader parent = Thread.currentThread().getContextClassLoader(); final JspcMojoClassLoader cl = new JspcMojoClassLoader(parent); cl.addURL(findToolsJar()); Thread.currentThread().setContextClassLoader(cl); try { // Show a nice message when we know how many files are included if (!jspFiles.isEmpty()) { log.info("Compiling " + jspFiles.size() + " JSP source file" + (jspFiles.size() > 1 ? "s" : "") + " to " + workingDirectory); } else { log.info("Compiling JSP source files to " + workingDirectory); } final StopWatch watch = new StopWatch(); watch.start(); jspCompiler.compile(jspFiles); log.info("Compilation completed in " + watch); } catch (Exception e) { throw new MojoFailureException("Failed to compile JSPS", e); } finally { // Set back the old classloader Thread.currentThread().setContextClassLoader(parent); } //Notify the build context that the jspFiles have been modified by the jsp compiler for (final File jspFile : jspFiles) { this.buildContext.refresh(jspFile); } // Maybe install the generated classes into the default output directory if (compile && isWar && includeInProject) { final Scanner scanner = buildContext.newScanner(this.workingDirectory); scanner.addDefaultExcludes(); scanner.setIncludes(new String[] { "**/*.class" }); scanner.scan(); for (final String includedFile : scanner.getIncludedFiles()) { final File s = new File(this.workingDirectory, includedFile); final File d = new File(this.project.getBuild().getOutputDirectory(), includedFile); d.getParentFile().mkdirs(); OutputStream fos = null; try { fos = this.buildContext.newFileOutputStream(d); org.apache.commons.io.FileUtils.copyFile(s, fos); } catch (IOException e) { throw new MojoFailureException("Failed to copy '" + s + "' to '" + d + "'", e); } finally { IOUtils.closeQuietly(fos); } } } if (isWar && includeInProject) { writeWebXml(); project.addCompileSourceRoot(workingDirectory.toString()); } }
From source file:org.construct_infrastructure.io.MessageReader.java
/** * Creates a new message reader that will operate over the given InputStream. * // w w w. ja va 2 s. co m * @param an_inputStream * the InputStream on which to read messages. */ public MessageReader(final InputStream an_inputStream, ExecutorService an_executorService) { my_errorOccured = false; my_logger = Logger.getLogger(getClass().getName()); my_logger.setLevel(Level.WARNING); my_inputStream = new BufferedInputStream(an_inputStream); my_messageList = new LinkedList(); my_keepReading = true; an_executorService.execute(this); my_service_scheduler = Executors.newScheduledThreadPool(1); my_service_scheduler.scheduleWithFixedDelay(my_listenerMonitor, 0, FIVE_HUNDRED, TimeUnit.MILLISECONDS); my_timeout = TWO_MINS_IN_MS; my_stopwatch = new StopWatch(); my_stopwatch.start(); }
From source file:org.deeplearning4j.iterativereduce.runtime.yarn.client.Client.java
/** * TODO: consider the scenarios where we dont get enough containers * - we need to re-submit the job till we get the containers alloc'd * //ww w . ja va 2 s. c om */ @Override public int run(String[] args) throws Exception { //System.out.println("IR: Client.run() [start]"); if (args.length < 1) LOG.info("No configuration file specified, using default (" + ConfigFields.DEFAULT_CONFIG_FILE + ")"); long startTime = System.currentTimeMillis(); String configFile = (args.length < 1) ? ConfigFields.DEFAULT_CONFIG_FILE : args[0]; Properties props = new Properties(); Configuration conf = getConf(); try { FileInputStream fis = new FileInputStream(configFile); props.load(fis); } catch (FileNotFoundException ex) { throw ex; // TODO: be nice } catch (IOException ex) { throw ex; // TODO: be nice } // Make sure we have some bare minimums ConfigFields.validateConfig(props); if (LOG.isDebugEnabled()) { LOG.debug("Loaded configuration: "); for (Map.Entry<Object, Object> entry : props.entrySet()) { LOG.debug(entry.getKey() + "=" + entry.getValue()); } } // TODO: make sure input file(s), libs, etc. actually exist! // Ensure our input path exists Path p = new Path(props.getProperty(ConfigFields.APP_INPUT_PATH)); FileSystem fs = FileSystem.get(conf); if (!fs.exists(p)) throw new FileNotFoundException("Input path not found: " + p.toString() + " (in " + fs.getUri() + ")"); LOG.info("Using input path: " + p.toString()); // Connect ResourceManagerHandler rmHandler = new ResourceManagerHandler(conf, null); rmHandler.getClientResourceManager(); // Create an Application request/ID ApplicationId appId = rmHandler.getApplicationId(); // Our AppId String appName = props.getProperty(ConfigFields.APP_NAME, ConfigFields.DEFAULT_APP_NAME).replace(' ', '_'); LOG.info("Got an application, id=" + appId + ", appName=" + appName); // Copy resources to [HD]FS LOG.debug("Copying resources to filesystem"); Utils.copyLocalResourcesToFs(props, conf, appId, appName); // Local resources Utils.copyLocalResourceToFs(configFile, ConfigFields.APP_CONFIG_FILE, conf, appId, appName); // Config file try { Utils.copyLocalResourceToFs("log4j.properties", "log4j.properties", conf, appId, appName); // Log4j } catch (FileNotFoundException ex) { LOG.warn("log4j.properties file not found"); } // Create our context List<String> commands = Utils.getMasterCommand(conf, props); Map<String, LocalResource> localResources = Utils.getLocalResourcesForApplication(conf, appId, appName, props, LocalResourceVisibility.APPLICATION); // Submit app rmHandler.submitApplication(appId, appName, Utils.getEnvironment(conf, props), localResources, commands, Integer.parseInt(props.getProperty(ConfigFields.YARN_MEMORY, "512"))); /* * TODO: * - look at updating this code region to make sure job is submitted! * */ StopWatch watch = new StopWatch(); watch.start(); // Wait for app to complete while (true) { Thread.sleep(2000); ApplicationReport report = rmHandler.getApplicationReport(appId); LOG.info("IterativeReduce report: " + " appId=" + appId.getId() + ", state: " + report.getYarnApplicationState().toString() + ", Running Time: " + watch.toString()); //report.getDiagnostics() if (YarnApplicationState.FINISHED == report.getYarnApplicationState()) { LOG.info("Application finished in " + (System.currentTimeMillis() - startTime) + "ms"); if (FinalApplicationStatus.SUCCEEDED == report.getFinalApplicationStatus()) { LOG.info("Application completed succesfully."); return 0; } else { LOG.info("Application completed with en error: " + report.getDiagnostics()); return -1; } } else if (YarnApplicationState.FAILED == report.getYarnApplicationState() || YarnApplicationState.KILLED == report.getYarnApplicationState()) { LOG.info("Application completed with a failed or killed state: " + report.getDiagnostics()); return -1; } } }
From source file:org.ensembl.gti.seqstore.TestSeqStore.java
public static void main(String[] args) throws Exception { TestSeqStoreOpts opts = new TestSeqStoreOpts(); new JCommander(opts, args); Logger log = LoggerFactory.getLogger(TestSeqStore.class); log.info("Building store " + opts.getImplementation()); SeqStore store = buildSeqStore(opts); log.info("Built store of type " + store.getClass().getSimpleName() + ": starting session"); long sessionId = store.startSession("testseqstore"); StopWatch watch = new StopWatch(); Map<String, Long> times = new HashMap<>(); for (String file : opts.getFiles()) { log.info("Processing " + file); long time = 0; int n = 0; BufferedReader reader = null; if (file.endsWith(".gz")) { reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(file)))); } else {// w w w. j a v a 2 s. co m reader = new BufferedReader(new FileReader(file)); } String line; StringBuilder seq = null; while ((line = reader.readLine()) != null) { if (line.charAt(0) == '>') { n++; time += processSeq(watch, seq, store, sessionId); seq = new StringBuilder(); } else if (seq != null) { seq.append(line.trim()); } } n++; time += processSeq(watch, seq, store, sessionId); reader.close(); times.put(file, time); double secs = 1.0 * time / 1000; log.info(String.format("Completed processing %s: %d sequences in %.3f s (%.3f seq/s) ", file, n, secs, n / secs)); } log.info("Completed test"); }