List of usage examples for java.lang Long parseLong
public static long parseLong(String s) throws NumberFormatException
From source file:it.geosolutions.unredd.apputil.AreaBuilder.java
public static void main(String[] args) { Option help = OptionBuilder.withLongOpt("help").withDescription("print help").create('?'); Options helpOptions = new Options().addOption(help); Options options = new Options().addOption(help) .addOption(OptionBuilder.withLongOpt("extents").withArgName("n/e/s/w") .withDescription("extents in the format n/e/s/w").hasArgs(4).withValueSeparator('/') .isRequired().withType(Double.class).create(OPT_EXTENTS)) .addOption(OptionBuilder.withLongOpt("size").withArgName("width,height") .withDescription("size of output image in pixel in the format width,height").hasArgs(2) .withValueSeparator(',').isRequired().withType(Integer.class).create(OPT_SIZE)) .addOption(OptionBuilder.withLongOpt("outfile").withArgName("file") .withDescription("the output tiff file").hasArg().isRequired().withType(String.class) .create(OPT_OUTFILE)) .addOption(OptionBuilder.withLongOpt("mem").withArgName("megabytes") .withDescription("the max memory available for the operation").hasArg().create(OPT_MEM)) .addOption(OptionBuilder.withLongOpt("threads").withArgName("numThreads") .withDescription("number of threads JAI will use").hasArg().create(OPT_THREADS)); try {// w w w .jav a 2s. c o m //=== Create parser CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); //=== Parse input params String sFile = cmd.getOptionValue(OPT_OUTFILE); String[] sSizeArr = cmd.getOptionValues(OPT_SIZE); if (sSizeArr.length != 2) { LOGGER.error("size requires 2 args"); return; } String[] sExtArr = cmd.getOptionValues(OPT_EXTENTS); if (sExtArr.length != 4) { LOGGER.error("extents require 4 args"); return; } File file = new File(sFile); LOGGER.info("Output file " + file); int w = Integer.parseInt(sSizeArr[0]); int h = Integer.parseInt(sSizeArr[1]); LOGGER.info("Image size " + w + " x " + h); double boxn = Double.parseDouble(sExtArr[0]); double boxe = Double.parseDouble(sExtArr[1]); double boxs = Double.parseDouble(sExtArr[2]); double boxw = Double.parseDouble(sExtArr[3]); LOGGER.info("Image bbox is n:" + boxn + "e:" + boxe + " s:" + boxs + " w:" + boxw); //=== Parse and set tilecache memory Long mega = 512l; if (cmd.hasOption(OPT_MEM)) { mega = Long.parseLong(cmd.getOptionValue(OPT_MEM)); LOGGER.info("JAI tilecache memory set to " + mega + "MB"); } else { LOGGER.info("JAI tilecache memory defaulting to " + mega + "MB"); } JAI.getDefaultInstance().getTileCache().setMemoryCapacity(mega * MEGA); //=== Parse and set JAI parallelism level int threads = 4; if (cmd.hasOption(OPT_THREADS)) { threads = Integer.parseInt(cmd.getOptionValue(OPT_THREADS)); LOGGER.info("JAI tile scheduler parallelism set to " + threads); } else { LOGGER.info("JAI tile scheduler parallelism defaulting to " + threads); } TileScheduler ts = JAI.getDefaultInstance().getTileScheduler(); ts.setParallelism(threads); ts.setPrefetchParallelism(threads); //=== Create grid and save System.setProperty("org.geotools.referencing.forceXY", "true"); GridCoverage2D grid = createAreaGrid(w, h, boxw, boxe, boxs, boxn); saveAreaGrid(grid, file); } catch (ParseException ex) { CommandLine cmd0 = null; try { // find out if an help was requested (it's missing mandatory params) CommandLineParser helpParser = new PosixParser(); cmd0 = helpParser.parse(helpOptions, args); } catch (ParseException ex1) { LOGGER.error("Unexpected error: " + ex1); } if (cmd0 == null || !cmd0.hasOption("help")) { LOGGER.error("Parse error: " + ex); } HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("createAreaLayer", options); } catch (Exception e) { LOGGER.error("Unexpected exception", e); } }
From source file:co.cask.cdap.data.tools.ReplicationStatusTool.java
public static void main(String args[]) throws Exception { CommandLine cmd;/*from w w w. j av a 2 s. c om*/ try { // parse the command line arguments cmd = parseArgs(args); } catch (ParseException e) { LOG.error("Error when parsing command-line arguemnts", e); printUsage(); return; } if (cmd.hasOption(DEBUG_OPTION)) { setupChecksumDirs(); dumpClusterChecksums(); dumpReplicationStateTable(); return; } inputStatusFileName = cmd.getOptionValue(INPUT_OPTION); outputStatusFileName = cmd.getOptionValue(OUTPUT_OPTION); dirsFileName = cmd.getOptionValue(FILE_OPTION); if (cmd.hasOption(SHUTDOWNTIME_OPTION)) { shutDownTimeArgument = Long.parseLong(cmd.getOptionValue(SHUTDOWNTIME_OPTION)); if (shutDownTimeArgument < 0L) { System.out.println("Invalid ShutDown time."); return; } } if (cmd.hasOption(HELP_OPTION) || !sanityCheckOptions(cmd)) { printUsage(); return; } if (cmd.hasOption(MASTER_OPTION)) { setupChecksumDirs(); processMasterCluster(); } else { setupChecksumDirs(); processSlaveCluster(); } }
From source file:de.urszeidler.ethereum.licencemanager1.deployer.LicenseManagerDeployer.java
/** * @param args/*from w w w . j a v a2s . co m*/ */ public static void main(String[] args) { Options options = createOptions(); CommandLineParser parser = new DefaultParser(); int returnValue = 0; boolean dontExit = false; try { CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { printHelp(options); return; } if (commandLine.hasOption("de")) dontExit = true; String senderKey = null; String senderPass = null; if (commandLine.hasOption("sk")) senderKey = commandLine.getOptionValue("sk"); if (commandLine.hasOption("sp")) senderPass = commandLine.getOptionValue("sp"); LicenseManagerDeployer manager = new LicenseManagerDeployer(); try { manager.init(senderKey, senderPass); long currentMili = 0; EthValue balance = null; if (commandLine.hasOption("calcDeploymendCost")) { currentMili = System.currentTimeMillis(); balance = manager.ethereum.getBalance(manager.sender); } if (commandLine.hasOption("observeBlock")) { manager.ethereum.events().observeBlocks() .subscribe(b -> System.out.println("Block: " + b.blockNumber + " " + b.receipts)); } if (commandLine.hasOption("f")) { String[] values = commandLine.getOptionValues("f"); String filename = values[0]; String isCompiled = values[1]; manager.deployer.setContractSource(filename, Boolean.parseBoolean(isCompiled)); } if (commandLine.hasOption("millis")) { manager.setMillis(Long.parseLong(commandLine.getOptionValue("millis"))); } if (commandLine.hasOption("c")) { String[] values = commandLine.getOptionValues("c"); if (values == null || values.length != 2) { System.out.println("Error. Need 2 parameters: paymentAddress,name"); System.out.println(""); printHelp(options); return; } String paymentAddress = values[0]; String name = values[1]; manager.deployLicenseManager(EthAddress.of(paymentAddress), name); } else if (commandLine.hasOption("l")) { String contractAddress = commandLine.getOptionValue("l"); if (contractAddress == null) { System.out.println("Error. Need 1 parameters: contract address"); System.out.println(""); printHelp(options); return; } manager.setManager(EthAddress.of(contractAddress)); manager.listContractData(EthAddress.of(contractAddress)); } else if (commandLine.hasOption("cic")) { String[] values = commandLine.getOptionValues("cic"); if (values == null || values.length != 6) { System.out.println("Error. Need 6 itemName, textHash, url, lifeTime, price"); System.out.println(""); printHelp(options); return; } String contractAddress = values[0]; String itemName = values[1]; String textHash = values[2]; String url = values[3]; String lifeTime = values[4]; String price = values[5]; manager.setManager(EthAddress.of(contractAddress)); manager.createIssuerContract(itemName, textHash, url, Integer.parseInt(lifeTime), Integer.parseInt(price)); } else if (commandLine.hasOption("bli")) { String[] values = commandLine.getOptionValues("bli"); if (values == null || values.length < 2 || values.length > 3) { System.out.println( "Error. Need 2-3 issuerAddress, name, optional an address when not use the sender."); System.out.println(""); printHelp(options); return; } String issuerAddress = values[0]; String name = values[1]; String address = values.length > 2 ? values[2] : null; manager.buyLicense(issuerAddress, name, address); } else if (commandLine.hasOption("v")) { String[] values = commandLine.getOptionValues("v"); String issuerAddress = values[0]; String message = values[1]; String signature = values[2]; String publicKey = values[3]; manager.verifyLicense(issuerAddress, message, signature, publicKey); } else if (commandLine.hasOption("cs")) { String message = commandLine.getOptionValue("cs"); if (message == null) { System.out.println("Error. Need 1 parameter: message"); System.out.println(""); printHelp(options); return; } String signature = createSignature(manager.sender, message); String publicKeyString = toPublicKeyString(manager.sender); System.out.println("The signature for the message is:"); System.out.println(signature); System.out.println("The public key is:"); System.out.println(publicKeyString); } else if (commandLine.hasOption("co")) { String[] values = commandLine.getOptionValues("co"); if (values == null || values.length != 2) { System.out.println("Error. Need 2 parameters: contractAddress, newOwnerAddress"); System.out.println(""); printHelp(options); return; } String contractAddress = values[0]; String newOwner = values[1]; manager.changeOwner(EthAddress.of(contractAddress), EthAddress.of(newOwner)); } else if (commandLine.hasOption("si")) { String contractAddress = commandLine.getOptionValue("si"); if (contractAddress == null) { System.out.println("Error. Need 1 parameters: contract address"); System.out.println(""); printHelp(options); return; } manager.setManager(EthAddress.of(contractAddress)); manager.stopIssue(contractAddress); } else if (commandLine.hasOption("ppuk")) { System.out.println("Public key: " + toPublicKeyString(manager.sender)); } if (manager.licenseManager != null && commandLine.hasOption("wca")) { String[] values = commandLine.getOptionValues("wca"); String filename = values[0]; File file = new File(filename); IOUtils.write( !commandLine.hasOption("cic") ? manager.licenseManager.contractAddress.withLeading0x() : manager.licenseManager.contractInstance .contracts(manager.licenseManager.contractInstance.contractCount() - 1) .withLeading0x(), new FileOutputStream(file), "UTF-8"); } if (commandLine.hasOption("calcDeploymendCost")) { balance = balance.minus(manager.ethereum.getBalance(manager.sender)); BigDecimal divide = new BigDecimal(balance.inWei()) .divide(BigDecimal.valueOf(1_000_000_000_000_000_000L)); System.out.println("Deployment cost: " + (divide) + " in wei:" + balance.inWei() + " time need: " + (System.currentTimeMillis() - currentMili)); } } catch (Exception e) { System.out.println(e.getMessage()); printHelp(options); returnValue = 10; } } catch (ParseException e1) { System.out.println(e1.getMessage()); printHelp(options); returnValue = 10; } if (!dontExit) System.exit(returnValue); }
From source file:de.unisb.cs.st.javaslicer.jung.ShowJungGraph.java
public static void main(String[] args) throws InterruptedException { Options options = createOptions();// w w w . ja 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; } Transformer<InstructionInstance, Object> transformer; Transformer<Object, String> vertexLabelTransformer; Transformer<Object, String> vertexTooltipTransformer; String granularity = cmdLine.getOptionValue("granularity"); if (granularity == null || "instance".equals(granularity)) { transformer = new Transformer<InstructionInstance, Object>() { @Override public InstructionInstance transform(InstructionInstance inst) { return inst; } }; vertexLabelTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { return getShortInstructionText(((InstructionInstance) inst).getInstruction()); } }; vertexTooltipTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { return getInstructionTooltip(((InstructionInstance) inst).getInstruction()); } }; } else if ("instruction".equals(granularity)) { transformer = new Transformer<InstructionInstance, Object>() { @Override public Instruction transform(InstructionInstance inst) { return inst.getInstruction(); } }; vertexLabelTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { return getShortInstructionText(((Instruction) inst)); } }; vertexTooltipTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { return getInstructionTooltip(((Instruction) inst)); } }; } else if ("line".equals(granularity)) { transformer = new Transformer<InstructionInstance, Object>() { @Override public Line transform(InstructionInstance inst) { return new Line(inst.getInstruction().getMethod(), inst.getInstruction().getLineNumber()); } }; vertexLabelTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { Line line = (Line) inst; return line.getMethod().getName() + ":" + line.getLineNr(); } }; vertexTooltipTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { Line line = (Line) inst; return "Line " + line.getLineNr() + " in method " + line.getMethod().getReadClass().getName() + "." + line.getMethod(); } }; } else { System.err.println("Illegal granularity specification: " + granularity); System.exit(-1); return; } int maxLevel = Integer.MAX_VALUE; if (cmdLine.hasOption("maxlevel")) { try { maxLevel = Integer.parseInt(cmdLine.getOptionValue("maxlevel")); } catch (NumberFormatException e) { System.err.println("Argument to \"maxlevel\" must be an integer."); System.exit(-1); return; } } long startTime = System.nanoTime(); ShowJungGraph<Object> showGraph = new ShowJungGraph<Object>(trace, transformer); showGraph.setMaxLevel(maxLevel); showGraph.setVertexLabelTransformer(vertexLabelTransformer); showGraph.setVertexTooltipTransformer(vertexTooltipTransformer); if (cmdLine.hasOption("progress")) showGraph.addProgressMonitor(new ConsoleProgressMonitor()); boolean multithreaded; if (cmdLine.hasOption("multithreaded")) { String multithreadedStr = cmdLine.getOptionValue("multithreaded"); multithreaded = ("1".equals(multithreadedStr) || "true".equals(multithreadedStr)); } else { multithreaded = Runtime.getRuntime().availableProcessors() > 1; } DirectedGraph<Object, SliceEdge<Object>> graph = showGraph.getGraph(tracing, sc, multithreaded); long endTime = System.nanoTime(); System.out.format((Locale) null, "%nSlice graph consists of %d nodes.%n", graph.getVertexCount()); System.out.format((Locale) null, "Computation took %.2f seconds.%n", 1e-9 * (endTime - startTime)); showGraph.displayGraph(graph); }
From source file:com.bitsofproof.example.Simple.java
public static void main(String[] args) { Security.addProvider(new BouncyCastleProvider()); final CommandLineParser parser = new GnuParser(); final Options gnuOptions = new Options(); gnuOptions.addOption("h", "help", false, "I can't help you yet"); gnuOptions.addOption("s", "server", true, "Server URL"); gnuOptions.addOption("u", "user", true, "User"); gnuOptions.addOption("p", "password", true, "Password"); System.out.println("BOP Bitcoin Server Simple Client 3.5.0 (c) 2013-2014 bits of proof zrt."); CommandLine cl = null;/* www.j a v a 2 s. c o m*/ String url = null; String user = null; String password = null; try { cl = parser.parse(gnuOptions, args); url = cl.getOptionValue('s'); user = cl.getOptionValue('u'); password = cl.getOptionValue('p'); } catch (org.apache.commons.cli.ParseException e) { e.printStackTrace(); System.exit(1); } if (url == null || user == null || password == null) { System.err.println("Need -s server -u user -p password"); System.exit(1); } BCSAPI api = getServer(url, user, password); try { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); long start = System.currentTimeMillis(); api.ping(start); System.out.println("Server round trip " + (System.currentTimeMillis() - start) + "ms"); api.addAlertListener(new AlertListener() { @Override public void alert(String s, int severity) { System.err.println("ALERT: " + s); } }); System.out.println("Talking to " + (api.isProduction() ? "PRODUCTION" : "test") + " server"); ConfirmationManager confirmationManager = new ConfirmationManager(); confirmationManager.init(api, 144); System.out.printf("Please enter wallet name: "); String wallet = input.readLine(); SimpleFileWallet w = new SimpleFileWallet(wallet + ".wallet"); TransactionFactory am = null; if (!w.exists()) { System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); System.out.printf("Enter master (empty for new): "); String master = input.readLine(); if (master.equals("")) { w.init(passphrase); w.unlock(passphrase); System.out.printf("First account: "); String account = input.readLine(); am = w.createAccountManager(account); w.lock(); w.persist(); } else { StringTokenizer tokenizer = new StringTokenizer(master, "@"); String key = tokenizer.nextToken(); long since = 0; if (tokenizer.hasMoreElements()) { since = Long.parseLong(tokenizer.nextToken()) * 1000; } w.init(passphrase, ExtendedKey.parse(key), true, since); w.unlock(passphrase); System.out.printf("First account: "); String account = input.readLine(); am = w.createAccountManager(account); w.lock(); w.persist(); w.sync(api); } } else { w = SimpleFileWallet.read(wallet + ".wallet"); w.sync(api); List<String> names = w.getAccountNames(); System.out.println("Accounts:"); System.out.println("---------"); String first = null; for (String name : names) { System.out.println(name); if (first == null) { first = name; } } System.out.println("---------"); am = w.getAccountManager(first); System.out.println("Using account " + first); } confirmationManager.addAccount(am); api.registerTransactionListener(am); while (true) { printMenu(); String answer = input.readLine(); System.out.printf("\n"); if (answer.equals("1")) { System.out.printf("The balance is: " + printBit(am.getBalance()) + "\n"); System.out.printf(" confirmed: " + printBit(am.getConfirmed()) + "\n"); System.out.printf(" receiveing: " + printBit(am.getReceiving()) + "\n"); System.out.printf(" change: " + printBit(am.getChange()) + "\n"); System.out.printf("( sending: " + printBit(am.getSending()) + ")\n"); } else if (answer.equals("2")) { for (Address a : am.getAddresses()) { System.out.printf(a + "\n"); } } else if (answer.equals("3")) { ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am; System.out.printf( im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n"); } else if (answer.equals("4")) { System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); w.unlock(passphrase); ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am; System.out.printf( im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n"); w.lock(); } else if (answer.equals("5")) { System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); w.unlock(passphrase); System.out.printf("Number of recipients"); Integer nr = Integer.valueOf(input.readLine()); Transaction spend; if (nr.intValue() == 1) { System.out.printf("Receiver address: "); String address = input.readLine(); System.out.printf("amount (Bit): "); long amount = parseBit(input.readLine()); spend = am.pay(Address.fromSatoshiStyle(address), amount); System.out.println("About to send " + printBit(amount) + " to " + address); } else { List<Address> addresses = new ArrayList<>(); List<Long> amounts = new ArrayList<>(); long total = 0; for (int i = 0; i < nr; ++i) { System.out.printf("Receiver address: "); String address = input.readLine(); addresses.add(Address.fromSatoshiStyle(address)); System.out.printf("amount (Bit): "); long amount = parseBit(input.readLine()); amounts.add(amount); total += amount; } spend = am.pay(addresses, amounts); System.out.println("About to send " + printBit(total)); } System.out.println("inputs"); for (TransactionInput in : spend.getInputs()) { System.out.println(in.getSourceHash() + " " + in.getIx()); } System.out.println("outputs"); for (TransactionOutput out : spend.getOutputs()) { System.out.println(out.getOutputAddress() + " " + printBit(out.getValue())); } w.lock(); System.out.printf("Type yes to go: "); if (input.readLine().equals("yes")) { api.sendTransaction(spend); System.out.printf("Sent transaction: " + spend.getHash()); } else { System.out.printf("Nothing happened."); } } else if (answer.equals("6")) { System.out.printf("Address: "); Set<Address> match = new HashSet<Address>(); match.add(Address.fromSatoshiStyle(input.readLine())); api.scanTransactionsForAddresses(match, 0, new TransactionListener() { @Override public boolean process(Transaction t) { System.out.printf("Found transaction: " + t.getHash() + "\n"); return true; } }); } else if (answer.equals("7")) { System.out.printf("Public key: "); ExtendedKey ek = ExtendedKey.parse(input.readLine()); api.scanTransactions(ek, 0, 10, 0, new TransactionListener() { @Override public boolean process(Transaction t) { System.out.printf("Found transaction: " + t.getHash() + "\n"); return true; } }); } else if (answer.equals("a")) { System.out.printf("Enter account name: "); String account = input.readLine(); am = w.getAccountManager(account); api.registerTransactionListener(am); confirmationManager.addAccount(am); } else if (answer.equals("c")) { System.out.printf("Enter account name: "); String account = input.readLine(); System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); w.unlock(passphrase); am = w.createAccountManager(account); System.out.println("using account: " + account); w.lock(); w.persist(); api.registerTransactionListener(am); confirmationManager.addAccount(am); } else if (answer.equals("m")) { System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); w.unlock(passphrase); System.out.println(w.getMaster().serialize(api.isProduction())); System.out.println(w.getMaster().getReadOnly().serialize(true)); w.lock(); } else if (answer.equals("s")) { System.out.printf("Enter private key: "); String key = input.readLine(); ECKeyPair k = ECKeyPair.parseWIF(key); KeyListAccountManager alm = new KeyListAccountManager(); alm.addKey(k); alm.syncHistory(api); Address a = am.getNextReceiverAddress(); Transaction t = alm.pay(a, alm.getBalance(), PaymentOptions.receiverPaysFee); System.out.println("About to sweep " + printBit(alm.getBalance()) + " to " + a); System.out.println("inputs"); for (TransactionInput in : t.getInputs()) { System.out.println(in.getSourceHash() + " " + in.getIx()); } System.out.println("outputs"); for (TransactionOutput out : t.getOutputs()) { System.out.println(out.getOutputAddress() + " " + printBit(out.getValue())); } System.out.printf("Type yes to go: "); if (input.readLine().equals("yes")) { api.sendTransaction(t); System.out.printf("Sent transaction: " + t.getHash()); } else { System.out.printf("Nothing happened."); } } else { System.exit(0); } } } catch (Exception e) { System.err.println("Something went wrong"); e.printStackTrace(); System.exit(1); } }
From source file:jackrabbit.app.App.java
public static void main(String[] args) { if (args.length == 0 || args.length == 1 && args[0].equals("-h")) { System.out.println("Usage: java -jar ackrabbit-migration-query-tool-" + VERSION + "-jar-with-dependencies.jar " + "--src src --src-conf conf [--src-repo-path path] [--src-user src_user] [--src-passwd src_pw] " + "[--dest-user dest_user] [--dest-passwd dest_pw] [--dest dest] [--dest-conf conf] [--dest-repo-path path] " + "[--cnd cnd] [--node-limit limit] " + "[--query-type type] [--query query]"); System.out.println("\t --src source repository directory"); System.out.println("\t --src-conf source repository configuration file"); System.out.println("\t --src-repo-path path to source node to copy from; default is \"/\""); System.out.println("\t --src-user source repository login"); System.out.println("\t --src-passwd source repository password"); System.out.println("\t --dest destination repository directory"); System.out.println("\t --dest-conf destination repository configuration file"); System.out.println("\t --dest-repo-path path to destination node to copy to; default is \"/\""); System.out.println("\t --dest-user destination repository login"); System.out.println("\t --dest-passwd destination repository password"); System.out.println(/* w w w . j ava 2 s.c o m*/ "\t --node-limit size to partition nodes with before copying. If it is not supplied, no partitioning is performed"); System.out.println("\t --cnd common node type definition file"); System.out.println( "\t --query query to run in src. If --query is specified, then --dest, --dest-conf, --dest-repo-path and --cnd will be ignored."); System.out.println("\t --query-type query type (sql, xpath, JCR-SQL2); default is JCR-SQL2"); return; } for (int i = 0; i < args.length; i = i + 2) { if (args[i].equals("--src") && i + 1 < args.length) { srcRepoDir = args[i + 1]; } else if (args[i].equals("--dest") && i + 1 < args.length) { destRepoDir = args[i + 1]; } else if (args[i].equals("--src-conf") && i + 1 < args.length) { srcConf = args[i + 1]; } else if (args[i].equals("--dest-conf") && i + 1 < args.length) { destConf = args[i + 1]; } else if (args[i].equals("--src-repo-path") && i + 1 < args.length) { srcRepoPath = args[i + 1]; } else if (args[i].equals("--dest-repo-path") && i + 1 < args.length) { destRepoPath = args[i + 1]; } else if (args[i].equals("--src-user") && i + 1 < args.length) { srcUser = args[i + 1]; } else if (args[i].equals("--src-passwd") && i + 1 < args.length) { srcPasswd = args[i + 1]; } else if (args[i].equals("--dest-user") && i + 1 < args.length) { destUser = args[i + 1]; } else if (args[i].equals("--dest-passwd") && i + 1 < args.length) { destPasswd = args[i + 1]; } else if (args[i].equals("--node-limit") && i + 1 < args.length) { nodeLimit = Long.parseLong(args[i + 1]); } else if (args[i].equals("--cnd") && i + 1 < args.length) { cndPath = args[i + 1]; } else if (args[i].equals("--query") && i + 1 < args.length) { query = args[i + 1]; } else if (args[i].equals("--query-type") && i + 1 < args.length) { queryType = args[i + 1]; } } boolean missingArgs = false; if (srcRepoDir.isEmpty()) { missingArgs = true; log.error("Please specify the --src option."); } if (destRepoDir.isEmpty() && !destConf.isEmpty()) { missingArgs = true; log.error("Please specify the --dest option."); } if (srcConf.isEmpty()) { missingArgs = true; log.error("Please specify the --src-conf option."); } if (destConf.isEmpty() && !destRepoDir.isEmpty()) { missingArgs = true; log.error("Please specify the --dest-conf option."); } if (missingArgs) return; SimpleCredentials credentials = new SimpleCredentials(srcUser, srcPasswd.toCharArray()); SimpleCredentials destCredentials = new SimpleCredentials(destUser, destPasswd.toCharArray()); JackrabbitRepository dest = null; RepositoryFactory destRf = null; RepositoryFactory srcRf = new RepositoryFactoryImpl(srcConf, srcRepoDir); if (!destConf.isEmpty()) { destRf = new RepositoryFactoryImpl(destConf, destRepoDir); } try { final JackrabbitRepository src = srcRf.getRepository(); SessionFactory srcSf = new SessionFactoryImpl(src, credentials); final Session srcSession = srcSf.getSession(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { srcSession.logout(); src.shutdown(); } }); if (destConf.isEmpty()) {//query mode BufferedReader in = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); if (query.isEmpty()) { while (true) { System.out.print(">"); String line = in.readLine(); if (line == null || line.isEmpty() || line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit")) { break; } try { runQuery(srcSession, line, queryType); } catch (RepositoryException e) { log.error(e.getMessage(), e); } } } else { try { runQuery(srcSession, query, queryType); } catch (RepositoryException e) { log.error(e.getMessage(), e); } } return; } dest = destRf.getRepository(); SessionFactory destSf = new SessionFactoryImpl(dest, destCredentials); Session destSession = destSf.getSession(); try { RepositoryManager.registerCustomNodeTypes(destSession, cndPath); if (nodeLimit == 0) NodeCopier.copy(srcSession, destSession, srcRepoPath, destRepoPath, true); else NodeCopier.copy(srcSession, destSession, srcRepoPath, destRepoPath, nodeLimit, true); log.info("Copying " + srcSession.getWorkspace().getName() + " to " + destSession.getWorkspace().getName() + " for " + srcRepoDir + " done."); } catch (ParseException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } catch (PathNotFoundException e) { log.error(e.getMessage(), e); } catch (RepositoryException e) { log.error(e.getMessage(), e); } List<String> destWkspaces = RepositoryManager.getDestinationWorkspaces(srcSession, destSession); for (String workspace : destWkspaces) { Session wsSession = srcSf.getSession(workspace); Session wsDestSession = destSf.getSession(workspace); try { RepositoryManager.registerCustomNodeTypes(wsDestSession, cndPath); if (nodeLimit == 0) NodeCopier.copy(wsSession, wsDestSession, srcRepoPath, destRepoPath, true); else { NodeCopier.copy(wsSession, wsDestSession, srcRepoPath, destRepoPath, nodeLimit, true); } log.info("Copying " + wsSession.getWorkspace().getName() + " to " + wsDestSession.getWorkspace().getName() + " for " + srcRepoDir + " done."); } catch (IOException e) { log.error(e.getMessage(), e); } catch (ParseException e) { log.error(e.getMessage(), e); } catch (PathNotFoundException e) { log.error(e.getMessage(), e); } catch (RepositoryException e) { log.error(e.getMessage(), e); } finally { wsSession.logout(); wsDestSession.logout(); } } } catch (IOException e) { log.error(e.getMessage(), e); } catch (PathNotFoundException e) { log.error(e.getMessage(), e); } catch (RepositoryException e) { log.error(e.getMessage(), e); } finally { if (dest != null) dest.shutdown(); } }
From source file:com.stumbleupon.hbaseadmin.HBaseCompact.java
/** * Main entry point/*from ww w .j av a 2 s. co m*/ * @param args command line arguments * @throws Exception */ public static void main(String[] args) throws Exception { CommandLineParser parser = new PosixParser(); CommandLine cmd = null; String hbaseSite = null; String jmxRemotePasswordFile = null; String jmxPort = null; Date startDate = null; Date endDate = null; int throttleFactor = 1; int numCycles = 1; int pauseInterval = DEFAULT_PAUSE_INTERVAL; int waitInterval = DEFAULT_WAIT_INTERVAL; int filesKeep = DEFAULT_FILES_KEEP; long regionCompactWaitTime = DEFAULT_REGION_COMPACT_WAIT_TIME; long maxStoreFileAge = 0; boolean excludeTables = false; String tableNamesString = ""; List<String> tableNames = new ArrayList<String>(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); // Parse command line options try { cmd = parser.parse(getOptions(), args); } catch (org.apache.commons.cli.ParseException e) { System.out.println(e.getMessage()); printOptions(); System.exit(-1); } for (Option option : cmd.getOptions()) { switch (option.getId()) { case 'c': hbaseSite = option.getValue(); break; case 'j': jmxRemotePasswordFile = option.getValue(); break; case 't': throttleFactor = Integer.parseInt(option.getValue()); break; case 'n': numCycles = Integer.parseInt(option.getValue()); break; case 'p': pauseInterval = Integer.parseInt(option.getValue()); break; case 'w': waitInterval = Integer.parseInt(option.getValue()); break; case 's': startDate = sdf.parse(option.getValue()); break; case 'e': endDate = sdf.parse(option.getValue()); break; case 'b': tableNamesString = option.getValue(); tableNames = Arrays.asList(option.getValue().split(",")); break; case 'f': filesKeep = Integer.parseInt(option.getValue()); break; case 'r': jmxPort = option.getValue(); break; case 'x': excludeTables = true; break; case 'm': regionCompactWaitTime = Long.parseLong(option.getValue()); break; case 'a': maxStoreFileAge = Long.parseLong(option.getValue()); break; default: throw new IllegalArgumentException("unexpected option " + option); } } LOG.info("Starting compactor"); LOG.info("--------------------------------------------------"); LOG.info("HBase site : {}", hbaseSite); LOG.info("RegionServer Jmx port : {}", jmxPort); LOG.info("Jmx password file : {}", jmxRemotePasswordFile); LOG.info("Compact interval : {}", pauseInterval); LOG.info("Check interval : {}", waitInterval); LOG.info("Throttle factor : {}", throttleFactor); LOG.info("Number of cycles : {}", numCycles); LOG.info("Off-peak start time : {}", Utils.dateString(startDate, "HH:mm")); LOG.info("Off-peak end time : {}", Utils.dateString(endDate, "HH:mm")); LOG.info("Minimum store files : {}", filesKeep); LOG.info("Table names : {}", tableNamesString); LOG.info("Exclude tables : {}", excludeTables); LOG.info("Region compact wait time: {}", regionCompactWaitTime); LOG.info("Max store file age : {}", maxStoreFileAge); LOG.info("--------------------------------------------------"); // Get command line options final Configuration conf = HBaseConfiguration.create(); conf.addResource(new Path(hbaseSite)); HBaseCompact compact = new HBaseCompact(); ClusterUtils clusterUtils = new ClusterUtils(compact, regionCompactWaitTime); compact.setClusterUtils(clusterUtils); compact.setAdmin(new HBaseAdmin(conf)); compact.setSleepBetweenCompacts(pauseInterval); compact.setSleepBetweenChecks(waitInterval); compact.setThrottleFactor(throttleFactor); compact.setNumCycles(numCycles); compact.setStartDate(startDate); compact.setEndDate(endDate); compact.setNumStoreFiles(filesKeep); compact.setTableNames(tableNames); compact.setExcludeTables(excludeTables); compact.setMaxStoreFileAge(maxStoreFileAge); clusterUtils.setJmxPort(jmxPort); clusterUtils.setJmxPasswordFile(jmxRemotePasswordFile); compact.runCompactions(); }
From source file:io.anserini.index.IndexTweets.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(HELP_OPTION, "show help")); options.addOption(new Option(OPTIMIZE_OPTION, "merge indexes into a single segment")); options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors")); options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory") .create(COLLECTION_OPTION)); options.addOption(// w ww .j a v a 2s . c om OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("file with deleted tweetids") .create(DELETES_OPTION)); options.addOption(OptionBuilder.withArgName("id").hasArg().withDescription("max id").create(MAX_ID_OPTION)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(COLLECTION_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(IndexTweets.class.getName(), options); System.exit(-1); } String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION); String indexPath = cmdline.getOptionValue(INDEX_OPTION); final FieldType textOptions = new FieldType(); textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); textOptions.setStored(true); textOptions.setTokenized(true); if (cmdline.hasOption(STORE_TERM_VECTORS_OPTION)) { textOptions.setStoreTermVectors(true); } LOG.info("collection: " + collectionPath); LOG.info("index: " + indexPath); LongOpenHashSet deletes = null; if (cmdline.hasOption(DELETES_OPTION)) { deletes = new LongOpenHashSet(); File deletesFile = new File(cmdline.getOptionValue(DELETES_OPTION)); if (!deletesFile.exists()) { System.err.println("Error: " + deletesFile + " does not exist!"); System.exit(-1); } LOG.info("Reading deletes from " + deletesFile); FileInputStream fin = new FileInputStream(deletesFile); byte[] ignoreBytes = new byte[2]; fin.read(ignoreBytes); // "B", "Z" bytes from commandline tools BufferedReader br = new BufferedReader(new InputStreamReader(new CBZip2InputStream(fin))); String s; while ((s = br.readLine()) != null) { if (s.contains("\t")) { deletes.add(Long.parseLong(s.split("\t")[0])); } else { deletes.add(Long.parseLong(s)); } } br.close(); fin.close(); LOG.info("Read " + deletes.size() + " tweetids from deletes file."); } long maxId = Long.MAX_VALUE; if (cmdline.hasOption(MAX_ID_OPTION)) { maxId = Long.parseLong(cmdline.getOptionValue(MAX_ID_OPTION)); LOG.info("index: " + maxId); } long startTime = System.currentTimeMillis(); File file = new File(collectionPath); if (!file.exists()) { System.err.println("Error: " + file + " does not exist!"); System.exit(-1); } StatusStream stream = new JsonStatusCorpusReader(file); Directory dir = FSDirectory.open(Paths.get(indexPath)); final IndexWriterConfig config = new IndexWriterConfig(ANALYZER); config.setOpenMode(IndexWriterConfig.OpenMode.CREATE); IndexWriter writer = new IndexWriter(dir, config); int cnt = 0; Status status; try { while ((status = stream.next()) != null) { if (status.getText() == null) { continue; } // Skip deletes tweetids. if (deletes != null && deletes.contains(status.getId())) { continue; } if (status.getId() > maxId) { continue; } cnt++; Document doc = new Document(); doc.add(new LongPoint(StatusField.ID.name, status.getId())); doc.add(new StoredField(StatusField.ID.name, status.getId())); doc.add(new LongPoint(StatusField.EPOCH.name, status.getEpoch())); doc.add(new StoredField(StatusField.EPOCH.name, status.getEpoch())); doc.add(new TextField(StatusField.SCREEN_NAME.name, status.getScreenname(), Store.YES)); doc.add(new Field(StatusField.TEXT.name, status.getText(), textOptions)); doc.add(new IntPoint(StatusField.FRIENDS_COUNT.name, status.getFollowersCount())); doc.add(new StoredField(StatusField.FRIENDS_COUNT.name, status.getFollowersCount())); doc.add(new IntPoint(StatusField.FOLLOWERS_COUNT.name, status.getFriendsCount())); doc.add(new StoredField(StatusField.FOLLOWERS_COUNT.name, status.getFriendsCount())); doc.add(new IntPoint(StatusField.STATUSES_COUNT.name, status.getStatusesCount())); doc.add(new StoredField(StatusField.STATUSES_COUNT.name, status.getStatusesCount())); long inReplyToStatusId = status.getInReplyToStatusId(); if (inReplyToStatusId > 0) { doc.add(new LongPoint(StatusField.IN_REPLY_TO_STATUS_ID.name, inReplyToStatusId)); doc.add(new StoredField(StatusField.IN_REPLY_TO_STATUS_ID.name, inReplyToStatusId)); doc.add(new LongPoint(StatusField.IN_REPLY_TO_USER_ID.name, status.getInReplyToUserId())); doc.add(new StoredField(StatusField.IN_REPLY_TO_USER_ID.name, status.getInReplyToUserId())); } String lang = status.getLang(); if (!lang.equals("unknown")) { doc.add(new TextField(StatusField.LANG.name, status.getLang(), Store.YES)); } long retweetStatusId = status.getRetweetedStatusId(); if (retweetStatusId > 0) { doc.add(new LongPoint(StatusField.RETWEETED_STATUS_ID.name, retweetStatusId)); doc.add(new StoredField(StatusField.RETWEETED_STATUS_ID.name, retweetStatusId)); doc.add(new LongPoint(StatusField.RETWEETED_USER_ID.name, status.getRetweetedUserId())); doc.add(new StoredField(StatusField.RETWEETED_USER_ID.name, status.getRetweetedUserId())); doc.add(new IntPoint(StatusField.RETWEET_COUNT.name, status.getRetweetCount())); doc.add(new StoredField(StatusField.RETWEET_COUNT.name, status.getRetweetCount())); if (status.getRetweetCount() < 0 || status.getRetweetedStatusId() < 0) { LOG.warn("Error parsing retweet fields of " + status.getId()); } } writer.addDocument(doc); if (cnt % 100000 == 0) { LOG.info(cnt + " statuses indexed"); } } LOG.info(String.format("Total of %s statuses added", cnt)); if (cmdline.hasOption(OPTIMIZE_OPTION)) { LOG.info("Merging segments..."); writer.forceMerge(1); LOG.info("Done!"); } LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms"); } catch (Exception e) { e.printStackTrace(); } finally { writer.close(); dir.close(); stream.close(); } }
From source file:com.cloud.test.stress.StressTestDirectAttach.java
public static void main(String[] args) { String host = "http://localhost"; String port = "8092"; String devPort = "8080"; String apiUrl = "/client/api"; try {/*from ww w . ja v a 2 s .c om*/ // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); // host if (arg.equals("-h")) { host = "http://" + iter.next(); } if (arg.equals("-p")) { port = iter.next(); } if (arg.equals("-dp")) { devPort = iter.next(); } if (arg.equals("-t")) { numThreads = Integer.parseInt(iter.next()); } if (arg.equals("-s")) { sleepTime = Long.parseLong(iter.next()); } if (arg.equals("-a")) { accountName = iter.next(); } if (arg.equals("-c")) { cleanUp = Boolean.parseBoolean(iter.next()); if (!cleanUp) sleepTime = 0L; // no need to wait if we don't ever // cleanup } if (arg.equals("-r")) { repeat = Boolean.parseBoolean(iter.next()); } if (arg.equals("-i")) { internet = Boolean.parseBoolean(iter.next()); } if (arg.equals("-w")) { wait = Integer.parseInt(iter.next()); } if (arg.equals("-z")) { zoneId = iter.next(); } if (arg.equals("-so")) { serviceOfferingId = iter.next(); } } final String server = host + ":" + port + "/"; final String developerServer = host + ":" + devPort + apiUrl; s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)"); if (cleanUp) s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up"); for (int i = 0; i < numThreads; i++) { new Thread(new Runnable() { @Override public void run() { do { String username = null; try { long now = System.currentTimeMillis(); Random ran = new Random(); username = Math.abs(ran.nextInt()) + "-user"; NDC.push(username); s_logger.info("Starting test for the user " + username); int response = executeDeployment(server, developerServer, username); boolean success = false; String reason = null; if (response == 200) { success = true; if (internet) { s_logger.info("Deploy successful...waiting 5 minute before SSH tests"); Thread.sleep(300000L); // Wait 60 // seconds so // the windows VM // can boot up and do a sys prep. s_logger.info("Begin Linux SSH test for account " + _account.get()); reason = sshTest(_linuxIP.get(), _linuxPassword.get()); if (reason == null) { s_logger.info( "Linux SSH test successful for account " + _account.get()); } } if (reason == null) { if (internet) { s_logger.info( "Windows SSH test successful for account " + _account.get()); } else { s_logger.info("deploy test successful....now cleaning up"); if (cleanUp) { s_logger.info( "Waiting " + sleepTime + " ms before cleaning up vms"); Thread.sleep(sleepTime); } else { success = true; } } if (usageIterator >= numThreads) { int eventsAndBillingResponseCode = executeEventsAndBilling(server, developerServer); s_logger.info( "events and usage records command finished with response code: " + eventsAndBillingResponseCode); usageIterator = 1; } else { s_logger.info( "Skipping events and usage records for this user: usageIterator " + usageIterator + " and number of Threads " + numThreads); usageIterator++; } if ((users == null) && (accountName == null)) { s_logger.info("Sending cleanup command"); int cleanupResponseCode = executeCleanup(server, developerServer, username); s_logger.info("cleanup command finished with response code: " + cleanupResponseCode); success = (cleanupResponseCode == 200); } else { s_logger.info("Sending stop DomR / destroy VM command"); int stopResponseCode = executeStop(server, developerServer, username); s_logger.info("stop(destroy) command finished with response code: " + stopResponseCode); success = (stopResponseCode == 200); } } else { // Just stop but don't destroy the // VMs/Routers s_logger.info("SSH test failed for account " + _account.get() + "with reason '" + reason + "', stopping VMs"); int stopResponseCode = executeStop(server, developerServer, username); s_logger.info( "stop command finished with response code: " + stopResponseCode); success = false; // since the SSH test // failed, mark the // whole test as // failure } } else { // Just stop but don't destroy the // VMs/Routers s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs"); int stopResponseCode = executeStop(server, developerServer, username); s_logger.info("stop command finished with response code: " + stopResponseCode); success = false; // since the deploy test // failed, mark the // whole test as failure } if (success) { s_logger.info("***** Completed test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds"); } else { s_logger.info("##### FAILED test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds with reason : " + reason); } s_logger.info("Sleeping for " + wait + " seconds before starting next iteration"); Thread.sleep(wait); } catch (Exception e) { s_logger.warn("Error in thread", e); try { int stopResponseCode = executeStop(server, developerServer, username); s_logger.info("stop response code: " + stopResponseCode); } catch (Exception e1) { } } finally { NDC.clear(); } } while (repeat); } }).start(); } } catch (Exception e) { s_logger.error(e); } }
From source file:com.adobe.aem.demomachine.Json2Csv.java
public static void main(String[] args) throws IOException { String inputFile1 = null;/*w w w . j a va 2 s . c om*/ String inputFile2 = null; String outputFile = null; HashMap<String, String> hmReportSuites = new HashMap<String, String>(); // Command line options for this tool Options options = new Options(); options.addOption("c", true, "Filename 1"); options.addOption("r", true, "Filename 2"); options.addOption("o", true, "Filename 3"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("c")) { inputFile1 = cmd.getOptionValue("c"); } if (cmd.hasOption("r")) { inputFile2 = cmd.getOptionValue("r"); } if (cmd.hasOption("o")) { outputFile = cmd.getOptionValue("o"); } if (inputFile1 == null || inputFile1 == null || outputFile == null) { System.exit(-1); } } catch (ParseException ex) { logger.error(ex.getMessage()); } // List of customers and report suites for these customers String sInputFile1 = readFile(inputFile1, Charset.defaultCharset()); sInputFile1 = sInputFile1.replaceAll("ObjectId\\(\"([0-9a-z]*)\"\\)", "\"$1\""); // Processing the list of report suites for each customer try { JSONArray jCustomers = new JSONArray(sInputFile1.trim()); for (int i = 0, size = jCustomers.length(); i < size; i++) { JSONObject jCustomer = jCustomers.getJSONObject(i); Iterator<?> keys = jCustomer.keys(); String companyName = null; while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("company")) { companyName = jCustomer.getString(key); } } keys = jCustomer.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("report_suites")) { JSONArray jReportSuites = jCustomer.getJSONArray(key); for (int j = 0, rSize = jReportSuites.length(); j < rSize; j++) { hmReportSuites.put(jReportSuites.getString(j), companyName); System.out.println(jReportSuites.get(j) + " for company " + companyName); } } } } // Creating the out put file PrintWriter writer = new PrintWriter(outputFile, "UTF-8"); writer.println("\"" + "Customer" + "\",\"" + "ReportSuite ID" + "\",\"" + "Number of Documents" + "\",\"" + "Last Updated" + "\""); // Processing the list of SOLR collections String sInputFile2 = readFile(inputFile2, Charset.defaultCharset()); sInputFile2 = sInputFile2.replaceAll("NumberLong\\(\"([0-9a-z]*)\"\\)", "\"$1\""); JSONObject jResults = new JSONObject(sInputFile2.trim()); JSONArray jCollections = jResults.getJSONArray("result"); for (int i = 0, size = jCollections.length(); i < size; i++) { JSONObject jCollection = jCollections.getJSONObject(i); String id = null; String number = null; String lastupdate = null; Iterator<?> keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("_id")) { id = jCollection.getString(key); } } keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("noOfDocs")) { number = jCollection.getString(key); } } keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("latestUpdateDate")) { lastupdate = jCollection.getString(key); } } Date d = new Date(Long.parseLong(lastupdate)); System.out.println(hmReportSuites.get(id) + "," + id + "," + number + "," + lastupdate + "," + new SimpleDateFormat("MM-dd-yyyy").format(d)); writer.println("\"" + hmReportSuites.get(id) + "\",\"" + id + "\",\"" + number + "\",\"" + new SimpleDateFormat("MM-dd-yyyy").format(d) + "\""); } writer.close(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }