List of usage examples for com.google.common.base Stopwatch elapsed
@CheckReturnValue public long elapsed(TimeUnit desiredUnit)
From source file:com.google.devtools.build.android.RClassGeneratorAction.java
public static void main(String[] args) throws Exception { final Stopwatch timer = Stopwatch.createStarted(); OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class); if (args.length == 1 && args[0].startsWith("@")) { args = Files.readAllLines(Paths.get(args[0].substring(1)), StandardCharsets.UTF_8) .toArray(new String[0]); }// w w w. j a v a 2 s.co m optionsParser.parseAndExitUponError(args); Options options = optionsParser.getOptions(Options.class); Preconditions.checkNotNull(options.classJarOutput); final AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(STD_LOGGER); try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_res_compile_tmp")) { Path tmp = scopedTmp.getPath(); Path classOutPath = tmp.resolve("compiled_classes"); LOGGER.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); List<SymbolFileProvider> libraries = new ArrayList<>(); for (DependencySymbolFileProvider library : options.libraries) { libraries.add(library); } // Note that we need to write the R class for the main binary (so proceed even if there // are no libraries). if (options.primaryRTxt != null) { String appPackageName = options.packageForR; if (appPackageName == null) { appPackageName = VariantConfiguration.getManifestPackage(options.primaryManifest.toFile()); } Multimap<String, SymbolLoader> libSymbolMap = ArrayListMultimap.create(); SymbolLoader fullSymbolValues = resourceProcessor.loadResourceSymbolTable(libraries, appPackageName, options.primaryRTxt, libSymbolMap); LOGGER.fine(String.format("Load symbols finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); // For now, assuming not used for libraries and setting final access for fields. if (fullSymbolValues != null) { resourceProcessor.writePackageRClasses(libSymbolMap, fullSymbolValues, appPackageName, classOutPath, true /* finalFields */); LOGGER.fine(String.format("Finished R.class at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); } } else { Files.createDirectories(classOutPath); } // We write .class files to temp, then jar them up after (we create a dummy jar, even if // there are no class files). resourceProcessor.createClassJar(classOutPath, options.classJarOutput); LOGGER.fine(String.format("createClassJar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); } finally { resourceProcessor.shutdown(); } LOGGER.fine(String.format("Compile action done in %sms", timer.elapsed(TimeUnit.MILLISECONDS))); }
From source file:org.opendaylight.controller.netconf.test.tool.client.http.perf.RestPerfClient.java
public static void main(String[] args) throws IOException { Parameters parameters = parseArgs(args, Parameters.getParser()); parameters.validate();//from ww w.j a v a 2 s . co m throttle = parameters.throttle / parameters.threadAmount; if (parameters.async && parameters.threadAmount > 1) { LOG.info("Throttling per thread: {}", throttle); } final String editContentString; try { editContentString = Files.toString(parameters.editContent, Charsets.UTF_8); } catch (final IOException e) { throw new IllegalArgumentException("Cannot read content of " + parameters.editContent); } final int threadAmount = parameters.threadAmount; LOG.info("thread amount: {}", threadAmount); final int requestsPerThread = parameters.editCount / parameters.threadAmount; LOG.info("requestsPerThread: {}", requestsPerThread); final int leftoverRequests = parameters.editCount % parameters.threadAmount; LOG.info("leftoverRequests: {}", leftoverRequests); final ArrayList<ArrayList<DestToPayload>> allThreadsPayloads = new ArrayList<>(); for (int i = 0; i < threadAmount; i++) { final ArrayList<DestToPayload> payloads = new ArrayList<>(); for (int j = 0; j < requestsPerThread; j++) { final int devicePort = parameters.sameDevice ? parameters.devicePortRangeStart : parameters.devicePortRangeStart + i; final StringBuilder destBuilder = new StringBuilder(dest); destBuilder.replace(destBuilder.indexOf(HOST_KEY), destBuilder.indexOf(HOST_KEY) + HOST_KEY.length(), parameters.ip) .replace(destBuilder.indexOf(PORT_KEY), destBuilder.indexOf(PORT_KEY) + PORT_KEY.length(), parameters.port + ""); final StringBuilder suffixBuilder = new StringBuilder(parameters.destination); if (suffixBuilder.indexOf(DEVICE_PORT_KEY) != -1) { suffixBuilder.replace(suffixBuilder.indexOf(DEVICE_PORT_KEY), suffixBuilder.indexOf(DEVICE_PORT_KEY) + DEVICE_PORT_KEY.length(), devicePort + ""); } destBuilder.append(suffixBuilder); payloads.add(new DestToPayload(destBuilder.toString(), prepareMessage(i, j, editContentString))); } allThreadsPayloads.add(payloads); } for (int i = 0; i < leftoverRequests; i++) { ArrayList<DestToPayload> payloads = allThreadsPayloads.get(allThreadsPayloads.size() - 1); final int devicePort = parameters.sameDevice ? parameters.devicePortRangeStart : parameters.devicePortRangeStart + threadAmount - 1; final StringBuilder destBuilder = new StringBuilder(dest); destBuilder.replace(destBuilder.indexOf(HOST_KEY), destBuilder.indexOf(HOST_KEY) + HOST_KEY.length(), parameters.ip).replace(destBuilder.indexOf(PORT_KEY), destBuilder.indexOf(PORT_KEY) + PORT_KEY.length(), parameters.port + ""); final StringBuilder suffixBuilder = new StringBuilder(parameters.destination); if (suffixBuilder.indexOf(DEVICE_PORT_KEY) != -1) { suffixBuilder.replace(suffixBuilder.indexOf(DEVICE_PORT_KEY), suffixBuilder.indexOf(DEVICE_PORT_KEY) + DEVICE_PORT_KEY.length(), devicePort + ""); } destBuilder.append(suffixBuilder); payloads.add(new DestToPayload(destBuilder.toString(), prepareMessage(threadAmount - 1, requestsPerThread + i, editContentString))); } final ArrayList<PerfClientCallable> callables = new ArrayList<>(); for (ArrayList<DestToPayload> payloads : allThreadsPayloads) { callables.add(new PerfClientCallable(parameters, payloads)); } final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount); LOG.info("Starting performance test"); final Stopwatch started = Stopwatch.createStarted(); try { final List<Future<Void>> futures = executorService.invokeAll(callables, 5, TimeUnit.MINUTES); for (final Future<Void> future : futures) { try { future.get(4L, TimeUnit.MINUTES); } catch (ExecutionException | TimeoutException e) { throw new RuntimeException(e); } } executorService.shutdownNow(); } catch (final InterruptedException e) { throw new RuntimeException("Unable to execute requests", e); } started.stop(); LOG.info("FINISHED. Execution time: {}", started); LOG.info("Requests per second: {}", (parameters.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS))); System.exit(0); }
From source file:com.google.devtools.build.android.AarGeneratorAction.java
public static void main(String[] args) { Stopwatch timer = Stopwatch.createStarted(); OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class); optionsParser.parseAndExitUponError(args); Options options = optionsParser.getOptions(Options.class); checkFlags(options);// w w w. ja va 2s .c o m AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor( new StdLogger(com.android.utils.StdLogger.Level.VERBOSE)); try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("aar_gen_tmp")) { Path tmp = scopedTmp.getPath(); Path resourcesOut = tmp.resolve("merged_resources"); Files.createDirectories(resourcesOut); Path assetsOut = tmp.resolve("merged_assets"); Files.createDirectories(assetsOut); logger.fine(String.format("Setup finished at %dms", timer.elapsed(TimeUnit.MILLISECONDS))); // There aren't any dependencies, but we merge to combine primary resources from different // res/assets directories into a single res and single assets directory. MergedAndroidData mergedData = resourceProcessor.mergeData(options.mainData, ImmutableList.<DependencyAndroidData>of(), ImmutableList.<DependencyAndroidData>of(), resourcesOut, assetsOut, null, VariantType.LIBRARY, null); logger.fine(String.format("Merging finished at %dms", timer.elapsed(TimeUnit.MILLISECONDS))); writeAar(options.aarOutput, mergedData, options.manifest, options.rtxt, options.classes); logger.fine(String.format("Packaging finished at %dms", timer.elapsed(TimeUnit.MILLISECONDS))); } catch (IOException | MergingException e) { logger.log(Level.SEVERE, "Error during merging resources", e); System.exit(1); } System.exit(0); }
From source file:org.opendaylight.netconf.test.tool.client.stress.StressClient.java
public static void main(final String[] args) { params = parseArgs(args, Parameters.getParser()); params.validate();/*w ww .ja v a 2 s .c o m*/ final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(Logger.ROOT_LOGGER_NAME); root.setLevel(params.debug ? Level.DEBUG : Level.INFO); final int threadAmount = params.threadAmount; LOG.info("thread amount: " + threadAmount); final int requestsPerThread = params.editCount / params.threadAmount; LOG.info("requestsPerThread: " + requestsPerThread); final int leftoverRequests = params.editCount % params.threadAmount; LOG.info("leftoverRequests: " + leftoverRequests); LOG.info("Preparing messages"); // Prepare all msgs up front final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount); for (int i = 0; i < threadAmount; i++) { if (i != threadAmount - 1) { allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread)); } else { allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread + leftoverRequests)); } } final String editContentString; try { editContentString = Files.toString(params.editContent, Charsets.UTF_8); } catch (final IOException e) { throw new IllegalArgumentException("Cannot read content of " + params.editContent); } for (int i = 0; i < threadAmount; i++) { final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i); int padding = 0; if (i == threadAmount - 1) { padding = leftoverRequests; } for (int j = 0; j < requestsPerThread + padding; j++) { LOG.debug("id: " + (i * requestsPerThread + j)); preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString)); } } final NioEventLoopGroup nioGroup = new NioEventLoopGroup(); final Timer timer = new HashedWheelTimer(); final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup, timer); final List<StressClientCallable> callables = new ArrayList<>(threadAmount); for (final List<NetconfMessage> messages : allPreparedMessages) { callables.add(new StressClientCallable(params, netconfClientDispatcher, messages)); } final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount); LOG.info("Starting stress test"); final Stopwatch started = Stopwatch.createStarted(); try { final List<Future<Boolean>> futures = executorService.invokeAll(callables); for (final Future<Boolean> future : futures) { try { future.get(4L, TimeUnit.MINUTES); } catch (ExecutionException | TimeoutException e) { throw new RuntimeException(e); } } executorService.shutdownNow(); } catch (final InterruptedException e) { throw new RuntimeException("Unable to execute requests", e); } started.stop(); LOG.info("FINISHED. Execution time: {}", started); LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS))); // Cleanup timer.stop(); try { nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { LOG.warn("Unable to close executor properly", e); } //stop the underlying ssh thread that gets spawned if we use ssh if (params.ssh) { AsyncSshHandler.DEFAULT_CLIENT.stop(); } }
From source file:org.opendaylight.controller.netconf.test.tool.client.stress.StressClient.java
public static void main(final String[] args) { final Parameters params = parseArgs(args, Parameters.getParser()); params.validate();//w ww .j ava 2 s . com final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(Logger.ROOT_LOGGER_NAME); root.setLevel(params.debug ? Level.DEBUG : Level.INFO); final int threadAmount = params.threadAmount; LOG.info("thread amount: " + threadAmount); final int requestsPerThread = params.editCount / params.threadAmount; LOG.info("requestsPerThread: " + requestsPerThread); final int leftoverRequests = params.editCount % params.threadAmount; LOG.info("leftoverRequests: " + leftoverRequests); LOG.info("Preparing messages"); // Prepare all msgs up front final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount); for (int i = 0; i < threadAmount; i++) { if (i != threadAmount - 1) { allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread)); } else { allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread + leftoverRequests)); } } final String editContentString; try { editContentString = Files.toString(params.editContent, Charsets.UTF_8); } catch (final IOException e) { throw new IllegalArgumentException("Cannot read content of " + params.editContent); } for (int i = 0; i < threadAmount; i++) { final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i); int padding = 0; if (i == threadAmount - 1) { padding = leftoverRequests; } for (int j = 0; j < requestsPerThread + padding; j++) { LOG.debug("id: " + (i * requestsPerThread + j)); preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString)); } } final NioEventLoopGroup nioGroup = new NioEventLoopGroup(); final Timer timer = new HashedWheelTimer(); final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup, timer); final List<StressClientCallable> callables = new ArrayList<>(threadAmount); for (final List<NetconfMessage> messages : allPreparedMessages) { callables.add(new StressClientCallable(params, netconfClientDispatcher, messages)); } final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount); LOG.info("Starting stress test"); final Stopwatch started = Stopwatch.createStarted(); try { final List<Future<Boolean>> futures = executorService.invokeAll(callables); for (final Future<Boolean> future : futures) { try { future.get(4L, TimeUnit.MINUTES); } catch (ExecutionException | TimeoutException e) { throw new RuntimeException(e); } } executorService.shutdownNow(); } catch (final InterruptedException e) { throw new RuntimeException("Unable to execute requests", e); } started.stop(); LOG.info("FINISHED. Execution time: {}", started); LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS))); // Cleanup timer.stop(); try { nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { LOG.warn("Unable to close executor properly", e); } //stop the underlying ssh thread that gets spawned if we use ssh if (params.ssh) { AsyncSshHandler.DEFAULT_CLIENT.stop(); } }
From source file:qa.qcri.nadeef.console.Console.java
/** * Start of Console./* ww w .j a v a2s.c o m*/ * @param args user input. */ public static void main(String[] args) { try { // bootstrap Nadeef. Stopwatch stopwatch = Stopwatch.createStarted(); Bootstrap.start(); console = new ConsoleReader(); Tracer.setConsole(new ConsoleReaderAdaptor(console)); List<Completer> loadCompleter = Arrays.asList(new StringsCompleter(commands), new FileNameCompleter(), new NullCompleter()); console.addCompleter(new ArgumentCompleter(loadCompleter)); console.clearScreen(); console.println(logo); console.println(); console.println(helpInfo); console.println(); console.drawLine(); console.setPrompt(prompt); console.println("Your NADEEF started in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms."); String line; while ((line = console.readLine()) != null) { line = line.trim(); String[] tokens = line.split(" "); if (tokens.length == 0) { continue; } // clear the statistics for every run. PerfReport.clear(); try { if (tokens[0].equalsIgnoreCase("exit")) { break; } else if (tokens[0].equalsIgnoreCase("load")) { load(line); } else if (tokens[0].equalsIgnoreCase("list")) { list(); } else if (tokens[0].equalsIgnoreCase("help")) { printHelp(); } else if (tokens[0].equalsIgnoreCase("detect")) { detect(line); } else if (tokens[0].equalsIgnoreCase("repair")) { repair(line); } else if (tokens[0].equalsIgnoreCase("run")) { run(line); } else if (tokens[0].equalsIgnoreCase("append")) { append(line); } else if (tokens[0].equalsIgnoreCase("set")) { set(line); } else if (!Strings.isNullOrEmpty(tokens[0])) { console.println("I don't know this command."); } } catch (Exception ex) { console.println("Oops, something is wrong. Please check the log in the output dir."); tracer.err("", ex); } } } catch (Exception ex) { try { tracer.err("Bootstrap failed", ex); } catch (Exception ignore) { } } finally { Bootstrap.shutdown(); } System.exit(0); }
From source file:com.google.devtools.build.android.AndroidCompiledResourceMergingAction.java
public static void main(String[] args) throws Exception { final Stopwatch timer = Stopwatch.createStarted(); OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class); optionsParser.enableParamsFileSupport(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault())); optionsParser.parseAndExitUponError(args); AaptConfigOptions aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class); Options options = optionsParser.getOptions(Options.class); Preconditions.checkNotNull(options.primaryData); Preconditions.checkNotNull(options.primaryManifest); Preconditions.checkNotNull(options.manifestOutput); Preconditions.checkNotNull(options.classJarOutput); try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_resource_merge_tmp"); ExecutorServiceCloser executorService = ExecutorServiceCloser.createWithFixedPoolOf(15)) { Path tmp = scopedTmp.getPath(); Path generatedSources = tmp.resolve("generated_resources"); Path processedManifest = tmp.resolve("manifest-processed/AndroidManifest.xml"); logger.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); String packageForR = options.packageForR; if (packageForR == null) { packageForR = Strings/* w w w .j a v a 2 s. c o m*/ .nullToEmpty(VariantConfiguration.getManifestPackage(options.primaryManifest.toFile())); } AndroidResourceClassWriter resourceClassWriter = AndroidResourceClassWriter .createWith(aaptConfigOptions.androidJar, generatedSources, packageForR); resourceClassWriter.setIncludeClassFile(true); resourceClassWriter.setIncludeJavaFile(false); AndroidResourceMerger.mergeCompiledData(options.primaryData, options.primaryManifest, options.directData, options.transitiveData, resourceClassWriter, options.throwOnResourceConflict, executorService); logger.fine(String.format("Merging finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); AndroidResourceOutputs.createClassJar(generatedSources, options.classJarOutput, options.targetLabel, options.injectingRuleKind); logger.fine(String.format("Create classJar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); // Until enough users with manifest placeholders migrate to the new manifest merger, // we need to replace ${applicationId} and ${packageName} with options.packageForR to make // the manifests compatible with the old manifest merger. processedManifest = AndroidManifestProcessor.with(stdLogger).processLibraryManifest(options.packageForR, options.primaryManifest, processedManifest); Files.createDirectories(options.manifestOutput.getParent()); Files.copy(processedManifest, options.manifestOutput); } catch (MergeConflictException e) { logger.log(Level.SEVERE, e.getMessage()); System.exit(1); } catch (MergingException e) { logger.log(Level.SEVERE, "Error during merging resources", e); throw e; } catch (AndroidManifestProcessor.ManifestProcessingException e) { System.exit(1); } catch (Exception e) { logger.log(Level.SEVERE, "Unexpected", e); throw e; } logger.fine(String.format("Resources merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS))); }
From source file:com.google.devtools.build.android.AndroidResourceMergingAction.java
public static void main(String[] args) throws Exception { final Stopwatch timer = Stopwatch.createStarted(); OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class); optionsParser.parseAndExitUponError(args); AaptConfigOptions aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class); Options options = optionsParser.getOptions(Options.class); final AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(stdLogger); Preconditions.checkNotNull(options.primaryData); Preconditions.checkNotNull(options.primaryManifest); Preconditions.checkNotNull(options.classJarOutput); try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_resource_merge_tmp")) { Path tmp = scopedTmp.getPath(); Path mergedAssets = tmp.resolve("merged_assets"); Path mergedResources = tmp.resolve("merged_resources"); Path generatedSources = tmp.resolve("generated_resources"); Path processedManifest = tmp.resolve("manifest-processed/AndroidManifest.xml"); logger.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); VariantType packageType = VariantType.LIBRARY; AndroidResourceClassWriter resourceClassWriter = AndroidResourceClassWriter.createWith( aaptConfigOptions.androidJar, generatedSources, Strings.nullToEmpty(options.packageForR)); resourceClassWriter.setIncludeClassFile(true); resourceClassWriter.setIncludeJavaFile(false); final MergedAndroidData mergedData = resourceProcessor.mergeData(options.primaryData, options.primaryManifest, options.directData, options.transitiveData, mergedResources, mergedAssets, new StubPngCruncher(), packageType, options.symbolsBinOut, resourceClassWriter); logger.fine(String.format("Merging finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); // Until enough users with manifest placeholders migrate to the new manifest merger, // we need to replace ${applicationId} and ${packageName} with options.packageForR to make // the manifests compatible with the old manifest merger. if (options.manifestOutput != null) { MergedAndroidData processedData = resourceProcessor.processManifest(packageType, options.packageForR, null, /* applicationId */ -1, /* versionCode */ null, /* versionName */ mergedData, processedManifest); resourceProcessor.copyManifestToOutput(processedData, options.manifestOutput); }//from w ww. j a va 2s.co m resourceProcessor.createClassJar(generatedSources, options.classJarOutput); logger.fine(String.format("Create classJar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); if (options.resourcesOutput != null) { // For now, try compressing the library resources that we pass to the validator. This takes // extra CPU resources to pack and unpack (~2x), but can reduce the zip size (~4x). resourceProcessor.createResourcesZip(mergedData.getResourceDir(), mergedData.getAssetDir(), options.resourcesOutput, true /* compress */); logger.fine(String.format("Create resources.zip finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); } } catch (MergingException e) { logger.log(Level.SEVERE, "Error during merging resources", e); throw e; } catch (Exception e) { logger.log(Level.SEVERE, "Unexpected", e); throw e; } finally { resourceProcessor.shutdown(); } logger.fine(String.format("Resources merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS))); }
From source file:com.google.devtools.build.android.AndroidResourceValidatorAction.java
public static void main(String[] args) throws Exception { final Stopwatch timer = Stopwatch.createStarted(); OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class); optionsParser.parseAndExitUponError(args); AaptConfigOptions aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class); Options options = optionsParser.getOptions(Options.class); final AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(stdLogger); VariantType packageType = VariantType.LIBRARY; Preconditions.checkNotNull(options.rOutput); Preconditions.checkNotNull(options.srcJarOutput); try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("resource_validator_tmp")) { Path tmp = scopedTmp.getPath(); Path expandedOut = tmp.resolve("tmp-expanded"); Path resources = expandedOut.resolve("res"); Path assets = expandedOut.resolve("assets"); Path generatedSources = tmp.resolve("generated_resources"); Path dummyManifest = tmp.resolve("manifest-aapt-dummy/AndroidManifest.xml"); unpackZip(options.mergedResources, expandedOut); logger.fine(String.format("unpacked zip at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); // We need to make the manifest aapt safe (w.r.t., placeholders). For now, just stub it out. resourceProcessor.writeDummyManifestForAapt(dummyManifest, options.packageForR); resourceProcessor.runAapt(aaptConfigOptions.aapt, aaptConfigOptions.androidJar, aaptConfigOptions.buildToolsVersion, packageType, aaptConfigOptions.debug, options.packageForR, new FlagAaptOptions(aaptConfigOptions), aaptConfigOptions.resourceConfigs, ImmutableList.<String>of(), dummyManifest, resources, assets, generatedSources, null, /* packageOut */ null, /* proguardOut */ null, /* mainDexProguardOut */ null /* publicResourcesOut */); logger.fine(String.format("aapt finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS))); resourceProcessor.copyRToOutput(generatedSources, options.rOutput, VariantType.LIBRARY == packageType); resourceProcessor.createSrcJar(generatedSources, options.srcJarOutput, VariantType.LIBRARY == packageType); } catch (Exception e) { logger.log(java.util.logging.Level.SEVERE, "Unexpected", e); throw e;//w w w .j a v a 2s .com } finally { resourceProcessor.shutdown(); } logger.fine(String.format("Resources merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS))); }
From source file:org.opendaylight.netconf.test.tool.client.http.perf.RestPerfClient.java
public static void main(String[] args) throws IOException { Parameters parameters = parseArgs(args, Parameters.getParser()); parameters.validate();/*ww w .ja va2 s . co m*/ throttle = parameters.throttle / parameters.threadAmount; if (parameters.async && parameters.threadAmount > 1) { LOG.info("Throttling per thread: {}", throttle); } final String editContentString; try { editContentString = Files.toString(parameters.editContent, Charsets.UTF_8); } catch (final IOException e) { throw new IllegalArgumentException("Cannot read content of " + parameters.editContent); } final int threadAmount = parameters.threadAmount; LOG.info("thread amount: {}", threadAmount); final int requestsPerThread = parameters.editCount / parameters.threadAmount; LOG.info("requestsPerThread: {}", requestsPerThread); final int leftoverRequests = parameters.editCount % parameters.threadAmount; LOG.info("leftoverRequests: {}", leftoverRequests); final ArrayList<ArrayList<DestToPayload>> allThreadsPayloads = new ArrayList<>(); for (int i = 0; i < threadAmount; i++) { final ArrayList<DestToPayload> payloads = new ArrayList<>(); for (int j = 0; j < requestsPerThread; j++) { final int devicePort = parameters.sameDevice ? parameters.devicePortRangeStart : parameters.devicePortRangeStart + i; final StringBuilder destBuilder = new StringBuilder(dest); destBuilder.replace(destBuilder.indexOf(HOST_KEY), destBuilder.indexOf(HOST_KEY) + HOST_KEY.length(), parameters.ip) .replace(destBuilder.indexOf(PORT_KEY), destBuilder.indexOf(PORT_KEY) + PORT_KEY.length(), parameters.port + ""); final StringBuilder suffixBuilder = new StringBuilder(parameters.destination); if (suffixBuilder.indexOf(DEVICE_PORT_KEY) != -1) { suffixBuilder.replace(suffixBuilder.indexOf(DEVICE_PORT_KEY), suffixBuilder.indexOf(DEVICE_PORT_KEY) + DEVICE_PORT_KEY.length(), devicePort + ""); } destBuilder.append(suffixBuilder); payloads.add(new DestToPayload(destBuilder.toString(), prepareMessage(i, j, editContentString, devicePort))); } allThreadsPayloads.add(payloads); } for (int i = 0; i < leftoverRequests; i++) { ArrayList<DestToPayload> payloads = allThreadsPayloads.get(allThreadsPayloads.size() - 1); final int devicePort = parameters.sameDevice ? parameters.devicePortRangeStart : parameters.devicePortRangeStart + threadAmount - 1; final StringBuilder destBuilder = new StringBuilder(dest); destBuilder.replace(destBuilder.indexOf(HOST_KEY), destBuilder.indexOf(HOST_KEY) + HOST_KEY.length(), parameters.ip).replace(destBuilder.indexOf(PORT_KEY), destBuilder.indexOf(PORT_KEY) + PORT_KEY.length(), parameters.port + ""); final StringBuilder suffixBuilder = new StringBuilder(parameters.destination); if (suffixBuilder.indexOf(DEVICE_PORT_KEY) != -1) { suffixBuilder.replace(suffixBuilder.indexOf(DEVICE_PORT_KEY), suffixBuilder.indexOf(DEVICE_PORT_KEY) + DEVICE_PORT_KEY.length(), devicePort + ""); } destBuilder.append(suffixBuilder); payloads.add(new DestToPayload(destBuilder.toString(), prepareMessage(threadAmount - 1, requestsPerThread + i, editContentString, devicePort))); } final ArrayList<PerfClientCallable> callables = new ArrayList<>(); for (ArrayList<DestToPayload> payloads : allThreadsPayloads) { callables.add(new PerfClientCallable(parameters, payloads)); } final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount); LOG.info("Starting performance test"); boolean allThreadsCompleted = true; final Stopwatch started = Stopwatch.createStarted(); try { final List<Future<Void>> futures = executorService.invokeAll(callables, parameters.timeout, TimeUnit.MINUTES); for (int i = 0; i < futures.size(); i++) { Future<Void> future = futures.get(i); if (future.isCancelled()) { allThreadsCompleted = false; LOG.info("{}. thread timed out.", i + 1); } else { try { future.get(); } catch (final ExecutionException e) { allThreadsCompleted = false; LOG.info("{}. thread failed.", i + 1, e); } } } } catch (final InterruptedException e) { allThreadsCompleted = false; LOG.warn("Unable to execute requests", e); } executorService.shutdownNow(); started.stop(); LOG.info("FINISHED. Execution time: {}", started); // If some threads failed or timed out, skip calculation of requests per second value // and do not log it if (allThreadsCompleted) { LOG.info("Requests per second: {}", (parameters.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS))); } System.exit(0); }