List of usage examples for java.util List size
int size();
From source file:com.meidusa.venus.benchmark.FileLineData.java
public static void main(String[] args) throws Exception { final FileLineData mapping = new FileLineData(); mapping.setFile(new File("./role.txt")); mapping.init();/* w ww . j a v a 2 s. c o m*/ List<Thread> list = new ArrayList<Thread>(); long start = TimeUtil.currentTimeMillis(); for (int j = 0; j < 1; j++) { Thread thread = new Thread() { public void run() { for (int i = 0; i < 1000; i++) { System.out.println(mapping.nextData()); } } }; list.add(thread); thread.start(); } for (int i = 0; i < list.size(); i++) { list.get(i).join(); } System.out.println("time=" + (TimeUtil.currentTimeMillis() - start)); }
From source file:it.jnrpe.client.JNRPEClient.java
/** * //from w ww .j a va2 s.co m * @param args * command line arguments * - */ public static void main(final String[] args) { Parser parser = new Parser(); parser.setGroup(configureCommandLine()); CommandLine cli = null; try { cli = parser.parse(args); if (cli.hasOption("--help")) { printUsage(null); } //timeoutAsUnknown = cli.hasOption("--unknown"); String sHost = (String) cli.getValue("--host"); final Long port = (Long) cli.getValue("--port", Long.valueOf(DEFAULT_PORT)); String sCommand = (String) cli.getValue("--command", "_NRPE_CHECK"); JNRPEClient client = new JNRPEClient(sHost, port.intValue(), !cli.hasOption("--nossl")); client.setTimeout(((Long) cli.getValue("--timeout", Long.valueOf(DEFAULT_TIMEOUT))).intValue()); if (cli.hasOption("--weakCiherSuites")) { client.enableWeakCipherSuites(); } @SuppressWarnings("unchecked") List<String> argList = cli.getValues("--arglist"); ReturnValue ret = client.sendCommand(sCommand, argList.toArray(new String[argList.size()])); System.out.println(ret.getMessage()); System.exit(ret.getStatus().intValue()); } catch (JNRPEClientException exc) { Status returnStatus; Throwable cause = exc.getCause(); if (cli.hasOption("--unknown") && cause instanceof SocketTimeoutException) { returnStatus = Status.UNKNOWN; } else { returnStatus = Status.CRITICAL; } System.out.println(exc.getMessage()); System.exit(returnStatus.intValue()); } catch (OptionException oe) { printUsage(oe); } }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step10RemoveEmptyDocuments.java
public static void main(String[] args) throws IOException { // input dir - list of xml query containers File inputDir = new File(args[0]); // output dir File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs();// w w w . java 2s .c o m } boolean crop = args.length >= 3 && "crop".equals(args[2]); // first find the maximum of zero-sized documents int maxMissing = 7; /* // iterate over query containers for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) { QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); // first find the maximum of zero-sized documents in a query int missingInQuery = 0; for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) { // boilerplate removal if (rankedResults.plainText == null || rankedResults.plainText.isEmpty()) { missingInQuery++; } } maxMissing = Math.max(missingInQuery, maxMissing); } */ System.out.println("Max zeroLengthDocuments in query: " + maxMissing); // max is 7 = we're cut-off at 93 // iterate over query containers for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) { QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); List<QueryResultContainer.SingleRankedResult> nonEmptyDocsList = new ArrayList<>(); for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) { // collect non-empty documents if (rankedResults.plainText != null && !rankedResults.plainText.isEmpty()) { nonEmptyDocsList.add(rankedResults); } } System.out.println("Non-empty docs coune: " + nonEmptyDocsList.size()); if (crop) { // now cut at 93 nonEmptyDocsList = nonEmptyDocsList.subList(0, (100 - maxMissing)); System.out.println("After cropping: " + nonEmptyDocsList.size()); } System.out.println("After cleaning: " + nonEmptyDocsList.size()); queryResultContainer.rankedResults.clear(); queryResultContainer.rankedResults.addAll(nonEmptyDocsList); // and save the query to output dir File outputFile = new File(outputDir, queryResultContainer.qID + ".xml"); FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8"); System.out.println("Finished " + outputFile); } }
From source file:languageTools.Analyzer.java
/** * * @param args/*from w w w . ja v a 2 s .c o m*/ * @throws Exception */ public static void main(String[] args) { // Get start time. long startTime = System.nanoTime(); // Parse command line options File file; try { file = parseOptions(args); } catch (ParseException e) { System.out.println(e.getMessage()); showHelp(); return; } // Get all files that should be analyzed List<File> files = new ArrayList<File>(); if (file.isDirectory()) { // Search directory for indicated file types files = searchDirectory(file); System.out.println("Found " + files.size() + " file(s).\n"); } else { files.add(file); } // Process files found for (File filefound : files) { System.out.println("Processing file: " + filefound.getPath() + ".\n"); Validator<?, ?, ?, ?> validator = null; switch (Extension.getFileExtension(filefound)) { case GOAL: validator = new AgentValidator(filefound.getPath()); // TODO we need to set a KR interface; use default (only one) // right now. Best we can do now // is to ask user to set it. try { ((AgentValidator) validator).setKRInterface(KRFactory.getDefaultInterface()); } catch (KRInitFailedException e) { // TODO: use logger. System.out.println(e.getMessage()); } break; case MOD2G: validator = new ModuleValidator(filefound.getPath()); // TODO we need to set a KR interface; use default (only one) // right now. Best we can do now // is to ask user to set it. try { ((ModuleValidator) validator).setKRInterface(KRFactory.getDefaultInterface()); } catch (KRInitFailedException e) { // TODO: use logger. System.out.println(e.getMessage()); } break; case MAS2G: validator = new MASValidator(filefound.getPath()); break; case TEST2G: validator = new TestValidator(filefound.getPath()); break; default: // TODO: use logger. System.out.println("Expected file with extension 'goal', 'mas2g', 'mod2g', or 'test2g'"); continue; } // Validate program file validator.validate(); // Print lexer tokens if (lexer) { validator.printLexerTokens(); } // Print constructed program if (program) { System.out.println("\n\n" + validator.getProgram().toString(" ", " ")); } // Print report with warnings, and parsing and validation messages System.out.println(validator.report()); } // Get elapsed time. long elapsedTime = (System.nanoTime() - startTime) / 1000000; System.out.println("Took " + elapsedTime + " milliseconds to analyze " + files.size() + " file(s)."); }
From source file:de.unisb.cs.st.javaslicer.slicing.DirectSlicer.java
public static void main(String[] args) { Options options = createOptions();// w w w. j a v a 2 s. com CommandLineParser parser = new GnuParser(); CommandLine cmdLine; try { cmdLine = parser.parse(options, args, true); } catch (ParseException e) { System.err.println("Error parsing the command line arguments: " + e.getMessage()); return; } if (cmdLine.hasOption('h')) { printHelp(options, System.out); System.exit(0); } String[] additionalArgs = cmdLine.getArgs(); if (additionalArgs.length != 2) { printHelp(options, System.err); System.exit(-1); } File traceFile = new File(additionalArgs[0]); String slicingCriterionString = additionalArgs[1]; Long threadId = null; if (cmdLine.hasOption('t')) { try { threadId = Long.parseLong(cmdLine.getOptionValue('t')); } catch (NumberFormatException e) { System.err.println("Illegal thread id: " + cmdLine.getOptionValue('t')); System.exit(-1); } } TraceResult trace; try { trace = TraceResult.readFrom(traceFile); } catch (IOException e) { System.err.format("Could not read the trace file \"%s\": %s%n", traceFile, e); System.exit(-1); return; } List<SlicingCriterion> sc = null; try { sc = StaticSlicingCriterion.parseAll(slicingCriterionString, trace.getReadClasses()); } catch (IllegalArgumentException e) { System.err.println("Error parsing slicing criterion: " + e.getMessage()); System.exit(-1); return; } List<ThreadId> threads = trace.getThreads(); if (threads.size() == 0) { System.err.println("The trace file contains no tracing information."); System.exit(-1); } ThreadId tracing = null; for (ThreadId t : threads) { if (threadId == null) { if ("main".equals(t.getThreadName()) && (tracing == null || t.getJavaThreadId() < tracing.getJavaThreadId())) tracing = t; } else if (t.getJavaThreadId() == threadId.longValue()) { tracing = t; } } if (tracing == null) { System.err.println(threadId == null ? "Couldn't find the main thread." : "The thread you specified was not found."); System.exit(-1); return; } long startTime = System.nanoTime(); DirectSlicer slicer = new DirectSlicer(trace); if (cmdLine.hasOption("--progress")) slicer.addProgressMonitor(new ConsoleProgressMonitor()); Set<Instruction> slice = slicer.getDynamicSlice(tracing, sc); long endTime = System.nanoTime(); List<Instruction> sliceList = new ArrayList<Instruction>(slice); Collections.sort(sliceList); System.out.println("The dynamic slice for criterion " + sc + ":"); for (Instruction insn : sliceList) { System.out.format((Locale) null, "%s.%s:%d %s%n", insn.getMethod().getReadClass().getName(), insn.getMethod().getName(), insn.getLineNumber(), insn.toString()); } System.out.format((Locale) null, "%nSlice consists of %d bytecode instructions.%n", sliceList.size()); System.out.format((Locale) null, "Computation took %.2f seconds.%n", 1e-9 * (endTime - startTime)); }
From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java
public static void main(String[] args) throws Exception { // Let's use some colors :) // AnsiConsole.systemInstall(); CommandLineParser cliParser = new BasicParser(); CommandLine cli = null;/*from w w w. j a va2 s .c om*/ try { cli = cliParser.parse(OPTIONS, args); } catch (ParseException e) { printHelp(); } if (!cli.hasOption("s")) { printHelp(); } String sourcePattern; if (cli.hasOption("p")) { sourcePattern = cli.getOptionValue("p"); } else { sourcePattern = DEFAULT_SOURCE_PATTERN; } String defaultAnswer; if (cli.hasOption("default-answer")) { defaultAnswer = cli.getOptionValue("default-answer"); } else { defaultAnswer = DEFAULT_DEFAULT_PROMPT_ANSWER; } boolean defaultAnswerYes = defaultAnswer.equalsIgnoreCase("y"); boolean quiet = cli.hasOption("q"); boolean testWrite = cli.hasOption("t"); Path sourceDirectory = Paths.get(cli.getOptionValue("s")).toAbsolutePath(); // Since we use IO we will have some blocking threads hanging around int threadCount = Runtime.getRuntime().availableProcessors() * 2; ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); BlockingQueue<WidgetVarLocation> foundUsages = new LinkedBlockingQueue<>(); BlockingQueue<WidgetVarLocation> unusedOrAmbiguous = new LinkedBlockingQueue<>(); BlockingQueue<WidgetVarLocation> skippedUsages = new LinkedBlockingQueue<>(); List<Future<?>> futures = new ArrayList<>(); findWidgetVars(sourceDirectory, sourcePattern, threadPool).forEach(widgetVarLocation -> { // We can't really find usages of widget vars that use EL expressions :( if (widgetVarLocation.widgetVar.contains("#")) { unusedOrAmbiguous.add(widgetVarLocation); return; } try { FileActionVisitor visitor = new FileActionVisitor(sourceDirectory, sourcePattern, sourceFile -> futures.add(threadPool.submit((Callable<?>) () -> { findWidgetVarUsages(sourceFile, widgetVarLocation, foundUsages, skippedUsages, unusedOrAmbiguous); return null; }))); Files.walkFileTree(sourceDirectory, visitor); } catch (IOException ex) { throw new RuntimeException(ex); } }); awaitAll(futures); new TreeSet<>(skippedUsages).forEach(widgetUsage -> { int startIndex = widgetUsage.columnNr; int endIndex = startIndex + widgetUsage.widgetVar.length(); String relativePath = widgetUsage.location.toAbsolutePath().toString() .substring(sourceDirectory.toString().length()); String previous = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString()); System.out.println("Skipped " + relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr + " for widgetVar '" + widgetUsage.widgetVar + "'"); System.out.println("\t" + previous); }); Map<WidgetVarLocation, List<WidgetVarLocation>> written = new HashMap<>(); new TreeSet<>(foundUsages).forEach(widgetUsage -> { WidgetVarLocation key = new WidgetVarLocation(null, widgetUsage.location, widgetUsage.lineNr, -1, null); List<WidgetVarLocation> writtenList = written.get(key); int existing = writtenList == null ? 0 : writtenList.size(); int startIndex = widgetUsage.columnNr; int endIndex = startIndex + widgetUsage.widgetVar.length(); String relativePath = widgetUsage.location.toAbsolutePath().toString() .substring(sourceDirectory.toString().length()); String next = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED) .a("PF('" + widgetUsage.widgetVar + "')").reset().toString()); System.out .println(relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr); System.out.println("\t" + next); System.out.print("Replace (Y/N)? [" + (defaultAnswerYes ? "Y" : "N") + "]: "); String input; if (quiet) { input = ""; System.out.println(); } else { try { do { input = in.readLine(); } while (input != null && !input.isEmpty() && !"y".equalsIgnoreCase(input) && !"n".equalsIgnoreCase(input)); } catch (IOException ex) { throw new RuntimeException(ex); } } if (input == null) { System.out.println("Aborted!"); } else if (input.isEmpty() && defaultAnswerYes || !input.isEmpty() && !"n".equalsIgnoreCase(input)) { System.out.println("Replaced!"); System.out.print("\t"); if (writtenList == null) { writtenList = new ArrayList<>(); written.put(key, writtenList); } writtenList.add(widgetUsage); List<String> lines; try { lines = Files.readAllLines(widgetUsage.location); } catch (IOException ex) { throw new RuntimeException(ex); } try (OutputStream os = testWrite ? new ByteArrayOutputStream() : Files.newOutputStream(widgetUsage.location); PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) { String line; for (int i = 0; i < lines.size(); i++) { int lineNr = i + 1; line = lines.get(i); if (lineNr == widgetUsage.lineNr) { int begin = widgetUsage.columnNr + (testWrite ? 0 : existing * 6); int end = begin + widgetUsage.widgetVar.length(); String newLine = replace(line, begin, end, "PF('" + widgetUsage.widgetVar + "')", false); if (testWrite) { System.out.println(newLine); } else { pw.println(newLine); } } else { if (!testWrite) { pw.println(line); } } } } catch (IOException ex) { throw new RuntimeException(ex); } } else { System.out.println("Skipped!"); } }); new TreeSet<>(unusedOrAmbiguous).forEach(widgetUsage -> { int startIndex = widgetUsage.columnNr; int endIndex = startIndex + widgetUsage.widgetVar.length(); String relativePath = widgetUsage.location.toAbsolutePath().toString() .substring(sourceDirectory.toString().length()); String previous = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString()); System.out.println("Skipped unused or ambiguous " + relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr); System.out.println("\t" + previous); }); threadPool.shutdown(); }
From source file:caarray.client.test.full.LoadTest.java
/** * @param args/*ww w. j a v a 2s .co m*/ */ public static void main(String[] args) { List<ApiFacade> apiFacades = new ArrayList<ApiFacade>(); List<List<ConfigurableTestSuite>> testSuiteCollection = new ArrayList<List<ConfigurableTestSuite>>(); int numThreads = TestProperties.getNumThreads(); if (numThreads <= 1) { System.out.println( "Thread count for load test set to 1 - setting to default count of " + DEFAULT_THREADS); numThreads = DEFAULT_THREADS; } try { for (int i = apiFacades.size(); i < numThreads; i++) { apiFacades.add(new FullApiFacade()); } for (int i = testSuiteCollection.size(); i < numThreads; i++) { List<ConfigurableTestSuite> shortTests = TestMain.getShortTestSuites(apiFacades.get(i)); List<ConfigurableTestSuite> longTests = TestMain.getLongTestSuites(apiFacades.get(i)); List<ConfigurableTestSuite> testSuites = new ArrayList<ConfigurableTestSuite>(); testSuites.addAll(shortTests); testSuites.addAll(longTests); testSuiteCollection.add(testSuites); } TestResultReport[] threadReports = new TestResultReport[numThreads]; for (int i = 0; i < numThreads; i++) { threadReports[i] = new TestResultReport(); } Thread[] loadTestThreads = new Thread[numThreads]; for (int i = 0; i < numThreads; i++) { LoadTestThread thread = new LoadTestThread(apiFacades.get(i), testSuiteCollection.get(i), threadReports[i], i); loadTestThreads[i] = new Thread(thread); } System.out.println("Executing load tests for " + numThreads + " threads ..."); long start = System.currentTimeMillis(); for (int i = 0; i < numThreads; i++) { loadTestThreads[i].start(); } for (int i = 0; i < numThreads; i++) { loadTestThreads[i].join(); } long time = System.currentTimeMillis() - start; System.out.println("Load tests completed in " + (double) time / (double) 1000 + " seconds."); TestResultReport finalReport = new TestResultReport(); for (TestResultReport report : threadReports) { finalReport.merge(report); } System.out.println("Analyzing load test results ..."); finalReport.writeLoadTestReports(); } catch (Throwable t) { System.out.println("An exception occured execuitng the load tests: " + t.getClass()); System.out.println("Test suite aborted."); t.printStackTrace(); log.error("Exception encountered:", t); } }
From source file:net.pandoragames.far.ui.swing.FindAndReplace.java
/** * The main method. Expects no arguments. * /* ww w . j a v a 2 s .c o m*/ * @param args * not evaluated */ public static void main(String[] args) { if (FARConfig.getEffectiveJavaVersion() == 0) { // obscure jvm LogFactory.getLog(FindAndReplace.class) .warn("Java version could not be read. This may very well lead to unexpected crashes"); } else if (FARConfig.getEffectiveJavaVersion() < 5) { // won't work - // exit LogFactory.getLog(FindAndReplace.class) .error("FAR requires java 5 (1.5.x) or higher. Found 1." + FARConfig.getEffectiveJavaVersion()); System.exit(1); } else { LogFactory.getLog(FindAndReplace.class).debug("Running on java " + FARConfig.getEffectiveJavaVersion()); } JFrame.setDefaultLookAndFeelDecorated(SwingConfig.isMacOSX()); UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE); FindAndReplace far = new FindAndReplace(); far.configure(); far.init(); far.pack(); far.setVisible(true); // First time initialisation - speeds up the loading of the help views HelpView helpView = new HelpView(far, "About", "about.html", new Point(100, 100)); helpView.pack(); helpView.setVisible(false); if (args.length > 0 && SwingConfig.getEffectiveJavaVersion() > 5) { List<File> fileList = new ArrayList<File>(); for (String arg : args) { File file = new File(arg); if (file.exists()) fileList.add(file); } if (fileList.size() > 0) { far.fileImporter.importFiles(fileList); } } if (far.config.versionHasChanged()) { UpdateDialog updateWizzard = new UpdateDialog(far, far.config, far.componentRepository); if (updateWizzard.isUserInteractionRequired()) { updateWizzard.pack(); updateWizzard.setVisible(true); } else { updateWizzard.dispose(); } } }
From source file:com.siva.javamultithreading.MultiThreadExecutor.java
public static void main(String[] args) throws ExecutionException, IOException { //Populate the data List<DomainObject> list = new ArrayList<>(); DomainObject object = null;//from w ww . ja v a 2 s.c om for (int i = 0; i < 230000; i++) { object = new DomainObject(); object.setId("ID" + i); object.setName("NAME" + i); object.setComment("COMMENT" + i); list.add(object); } int maxNoOfRows = 40000; int noOfThreads = 1; int remaining = 0; if (list.size() > 40000) { noOfThreads = list.size() / maxNoOfRows; remaining = list.size() % maxNoOfRows; if (remaining > 0) { noOfThreads++; } } List<List<DomainObject>> dos = ListUtils.partition(list, maxNoOfRows); ExecutorService threadPool = Executors.newFixedThreadPool(noOfThreads); CompletionService<HSSFWorkbook> pool = new ExecutorCompletionService<>(threadPool); // Excel creation through multiple threads long startTime = System.currentTimeMillis(); for (List<DomainObject> listObj : dos) { pool.submit(new ExcelChunkSheetWriter(listObj)); } HSSFWorkbook hSSFWorkbook = null; HSSFWorkbook book = new HSSFWorkbook(); HSSFSheet sheet = book.createSheet("Report"); try { for (int i = 0; i < 5; i++) { hSSFWorkbook = pool.take().get(); System.out.println( "sheet row count : sheet.PhysicalNumberOfRows() = " + sheet.getPhysicalNumberOfRows()); int currentCount = sheet.getPhysicalNumberOfRows(); int incomingCount = hSSFWorkbook.getSheetAt(0).getPhysicalNumberOfRows(); if ((currentCount + incomingCount) > 60000) { sheet = book.createSheet("Report" + i); } ExcelUtil.copySheets(book, sheet, hSSFWorkbook.getSheetAt(0)); } } catch (InterruptedException ex) { Logger.getLogger(MultiThreadExecutor.class.getName()).log(Level.SEVERE, null, ex); } catch (ExecutionException ex) { Logger.getLogger(MultiThreadExecutor.class.getName()).log(Level.SEVERE, null, ex); } try { writeFile(book, new FileOutputStream("Report.xls")); } catch (Exception e) { e.printStackTrace(); } //System.out.println("No of Threads : " + noOfThreads + " Size : " + list.size() + " remaining : " + remaining); long endTime = System.currentTimeMillis(); System.out.println("Time taken: " + (endTime - startTime) + " ms"); threadPool.shutdown(); //startProcess(); }
From source file:com.kactech.otj.examples.App_otj.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String command = null;//from w ww .ja v a2 s. c o m String hisacct = null; String hisacctName = null; String hisacctAsset = null; String asset = null; String assetName = null; List<String> argList = null; boolean newAccount = false; File dir = null; ConnectionInfo connection = null; List<ScriptFilter> filters = null; CommandLineParser parser = new GnuParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println("Command-line parsing error: " + e.getMessage()); help(); System.exit(-1); } if (cmd.hasOption('h')) { help(); System.exit(0); } @SuppressWarnings("unchecked") List<String> list = cmd.getArgList(); if (list.size() > 1) { System.err.println("only one command is supported, you've typed " + list); help(); System.exit(-1); } if (list.size() > 0) command = list.get(0).trim(); List<SampleAccount> accounts = ExamplesUtils.getSampleAccounts(); if (cmd.hasOption('s')) { String v = cmd.getOptionValue('s').trim(); connection = ExamplesUtils.findServer(v); if (connection == null) { System.err.println("unknown server: " + v); System.exit(-1); } } else { connection = ExamplesUtils.findServer(DEF_SERVER_NAME); if (connection == null) { System.err.println("default server not found server: " + DEF_SERVER_NAME); System.exit(-1); } } if (cmd.hasOption('t')) { String v = cmd.getOptionValue('t'); for (SampleAccount ac : accounts) if (ac.accountName.startsWith(v)) { hisacct = ac.accountID; hisacctName = ac.accountName; hisacctAsset = ac.assetID; break; } if (hisacct == null) if (mayBeValid(v)) hisacct = v; else { System.err.println("invalid hisacct: " + v); System.exit(-1); } } if (cmd.hasOption('p')) { String v = cmd.getOptionValue('p'); for (SampleAccount ac : accounts) if (ac.assetName.startsWith(v)) { asset = ac.assetID; assetName = ac.assetName; break; } if (asset == null) if (mayBeValid(v)) asset = v; else { System.err.println("invalid asset: " + v); System.exit(-1); } } if (cmd.hasOption('a')) { String v = cmd.getOptionValue('a'); argList = new ArrayList<String>(); boolean q = false; StringBuilder b = new StringBuilder(); for (int i = 0; i < v.length(); i++) { char c = v.charAt(i); if (c == '"') { if (q) { argList.add(b.toString()); b = null; q = false; continue; } if (b != null) argList.add(b.toString()); b = new StringBuilder(); q = true; continue; } if (c == ' ' || c == '\t') { if (q) { b.append(c); continue; } if (b != null) argList.add(b.toString()); b = null; continue; } if (b == null) b = new StringBuilder(); b.append(c); } if (b != null) argList.add(b.toString()); if (q) { System.err.println("unclosed quote in args: " + v); System.exit(-1); } } dir = new File(cmd.hasOption('d') ? cmd.getOptionValue('d') : DEF_CLIENT_DIR); if (cmd.hasOption('x')) del(dir); newAccount = cmd.hasOption('n'); if (cmd.hasOption('f')) { filters = new ArrayList<ScriptFilter>(); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); Compilable compilingEngine = (Compilable) engine; for (String fn : cmd.getOptionValue('f').split(",")) { fn = fn.trim(); if (fn.isEmpty()) continue; fn += ".js"; Reader r = null; try { r = new InputStreamReader(new FileInputStream(new File("filters", fn)), Utils.UTF8); } catch (Exception e) { try { r = new InputStreamReader( App_otj.class.getResourceAsStream("/com/kactech/otj/examples/filters/" + fn)); } catch (Exception e2) { } } if (r == null) { System.err.println("filter not found: " + fn); System.exit(-1); } else try { CompiledScript compiled = compilingEngine.compile(r); ScriptFilter sf = new ScriptFilter(compiled); filters.add(sf); } catch (Exception ex) { System.err.println("error while loading " + fn + ": " + ex); System.exit(-1); } } } System.out.println("server: " + connection.getEndpoint() + " " + connection.getID()); System.out.println("command: '" + command + "'"); System.out.println("args: " + argList); System.out.println("hisacct: " + hisacct); System.out.println("hisacctName: " + hisacctName); System.out.println("hisacctAsset: " + hisacctAsset); System.out.println("asset: " + asset); System.out.println("assetName: " + assetName); if (asset != null && hisacctAsset != null && !asset.equals(hisacctAsset)) { System.err.println("asset differs from hisacctAsset"); System.exit(-1); } EClient client = new EClient(dir, connection); client.setAssetType(asset != null ? asset : hisacctAsset); client.setCreateNewAccount(newAccount); if (filters != null) client.setFilters(filters); try { Utils.init(); Client.DEBUG_JSON = true; client.init(); if ("balance".equals(command)) System.out.println("Balance: " + client.getAccount().getBalance().getAmount()); else if ("acceptall".equals(command)) client.processInbox(); else if ("transfer".equals(command)) { if (hisacct == null) System.err.println("please specify --hisacct"); else { int idx = argList != null ? argList.indexOf("amount") : -1; if (idx < 0) System.err.println("please specify amount"); else if (idx == argList.size()) System.err.println("amount argument needs value"); else { Long amount = -1l; try { amount = new Long(argList.get(idx + 1)); } catch (Exception e) { } if (amount <= 0) System.err.println("invalid amount"); else { client.notarizeTransaction(hisacct, amount); } } } } else if ("reload".equals(command)) client.reloadState(); else if ("procnym".equals(command)) client.processNymbox(); } finally { client.saveState(); client.close(); } }