List of usage examples for org.apache.commons.cli ParseException getMessage
public String getMessage()
From source file:com.indeed.imhotep.builder.tsv.TsvConverter.java
@SuppressWarnings("static-access") public static void main(String[] args) { final Options options; final CommandLineParser parser = new PosixParser(); final CommandLine cmd; options = new Options(); final Option idxLoc = OptionBuilder.withArgName("path").hasArg().withLongOpt("index-loc") .withDescription("").isRequired().create('i'); options.addOption(idxLoc);//from ww w .ja va 2 s.c o m final Option successLoc = OptionBuilder.withArgName("path").hasArg().withLongOpt("success-loc") .withDescription("").isRequired().create('s'); options.addOption(successLoc); final Option failureLoc = OptionBuilder.withArgName("path").hasArg().withLongOpt("failure-loc") .withDescription("").isRequired().create('f'); options.addOption(failureLoc); final Option dataLoc = OptionBuilder.withArgName("path").hasArg().withLongOpt("data-loc") .withDescription("Location to store the built indexes").isRequired().create('d'); options.addOption(dataLoc); final Option buildLoc = OptionBuilder.withArgName("path").hasArg().withLongOpt("build-loc") .withDescription("Local directory were the indexes are built").create('b'); options.addOption(buildLoc); final Option hdfsPrincipal = OptionBuilder.withArgName("name").hasArg().withLongOpt("hdfs-principal") .withDescription("HDFS principal (only when using HDFS)").create('p'); options.addOption(hdfsPrincipal); final Option hdfsKeytab = OptionBuilder.withArgName("file").hasArg().withLongOpt("hdfs-keytab") .withDescription("HDFS keytab file location (only when using HDFS)").create('k'); options.addOption(hdfsKeytab); final Option qaMode = OptionBuilder.withLongOpt("qa-mode").withDescription("Enable QA mode").create('q'); options.addOption(qaMode); try { cmd = parser.parse(options, args); } catch (ParseException exp) { System.out.println("Unexpected exception: " + exp.getMessage()); System.out.println("\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("shardBuilder", options, true); return; } /* start up the shard builder */ final TsvConverter converter = new TsvConverter(); converter.init(cmd.getOptionValue('i'), cmd.getOptionValue('s'), cmd.getOptionValue('f'), cmd.getOptionValue('d'), cmd.getOptionValue('b'), cmd.getOptionValue('p'), cmd.getOptionValue('k'), cmd.hasOption('q')); converter.run(); }
From source file:de.phillme.PhotoSorter.java
public static void main(String[] args) { PhotoConfig photoConfig = new PhotoConfig(); // create the parser CommandLineParser parser = new DefaultParser(); try {/*from w w w . j a v a2s .c o m*/ // parse the command line arguments CommandLine line = parser.parse(photoConfig.getOptions(), args); if (line.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("PhotoSorter", photoConfig.getOptions()); return; } PhotoSorter photoSorter = new PhotoSorter(line); List<PhotoFile> photoFileList; List<PhotoFile> sortedList; //photoSorter.probeFiletypes(); photoFileList = photoSorter.listSourceFiles(); sortedList = photoSorter.sortList(photoFileList); LOGGER.finest(sortedList.toString()); photoSorter.flagAllEvents(sortedList); photoSorter.printEventList(photoSorter.getEventList()); //LOGGER.info(pathList.toString()); } catch (org.apache.commons.cli.ParseException e) { LOGGER.severe(e.getMessage()); } catch (IOException e) { LOGGER.severe(e.getMessage()); } catch (ImageProcessingException e) { LOGGER.severe(e.getMessage()); } }
From source file:fullThreadDump.java
public static void main(String[] args) throws IOException { if (args.length < 2 && !args.toString().contains("-h")) { usage();//from www .j av a 2 s.c om } Options options = new Options(); options.addOption("h", "host", true, "jmx host:port"); options.addOption("j", "remoting-jmx", false, "jboss use remoting-jmx subsystem"); options.addOption("u", "user", true, "username"); options.addOption("p", "password", true, "password"); options.addOption("s", "stats", false, "include jmx stats in threaddump"); options.addOption("f", "file", true, "output file"); String hostname = null, user = null, passwd = null, file = null; boolean jbossRemotingJMX = false, stats = false; CommandLineParser parser = new PosixParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption("h")) { hostname = line.getOptionValue("h"); } if (line.hasOption("u")) { user = line.getOptionValue("u"); } if (line.hasOption("p")) { passwd = line.getOptionValue("p"); } if (line.hasOption("f")) { file = line.getOptionValue("f"); } if (line.hasOption("s")) { stats = true; } if (line.hasOption("j")) { jbossRemotingJMX = true; } if (hostname == null) { System.out.println("Enter jmx Hostname"); } } catch (ParseException exp) { System.out.println("Unexpected exception:" + exp.getMessage()); } fullThreadDump ftd = new fullThreadDump(jbossRemotingJMX, hostname, user, passwd, stats); if (file != null) { ftd.dump(file); } else { ftd.dump(); } }
From source file:edu.wustl.mir.erl.ihe.xdsi.util.StoreSCU.java
@SuppressWarnings("unchecked") public static void main(String[] args) { long t1, t2;/*ww w . j a va 2s.c om*/ try { CommandLine cl = parseComandLine(args); Device device = new Device("storescu"); Connection conn = new Connection(); device.addConnection(conn); ApplicationEntity ae = new ApplicationEntity("STORESCU"); device.addApplicationEntity(ae); ae.addConnection(conn); StoreSCU main = new StoreSCU(ae); configureTmpFile(main, cl); CLIUtils.configureConnect(main.remote, main.rq, cl); CLIUtils.configureBind(conn, ae, cl); CLIUtils.configure(conn, cl); main.remote.setTlsProtocols(conn.getTlsProtocols()); main.remote.setTlsCipherSuites(conn.getTlsCipherSuites()); configureRelatedSOPClass(main, cl); main.setAttributes(new Attributes()); CLIUtils.addAttributes(main.attrs, cl.getOptionValues("s")); main.setUIDSuffix(cl.getOptionValue("uid-suffix")); main.setPriority(CLIUtils.priorityOf(cl)); List<String> argList = cl.getArgList(); boolean echo = argList.isEmpty(); if (!echo) { System.out.println(rb.getString("scanning")); t1 = System.currentTimeMillis(); main.scanFiles(argList); t2 = System.currentTimeMillis(); int n = main.filesScanned; System.out.println(); if (n == 0) return; System.out.println( MessageFormat.format(rb.getString("scanned"), n, (t2 - t1) / 1000F, (t2 - t1) / n)); } ExecutorService executorService = Executors.newSingleThreadExecutor(); ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); device.setExecutor(executorService); device.setScheduledExecutor(scheduledExecutorService); try { t1 = System.currentTimeMillis(); main.open(); t2 = System.currentTimeMillis(); System.out .println(MessageFormat.format(rb.getString("connected"), main.as.getRemoteAET(), t2 - t1)); if (echo) main.echo(); else { t1 = System.currentTimeMillis(); main.sendFiles(); t2 = System.currentTimeMillis(); } } finally { main.close(); executorService.shutdown(); scheduledExecutorService.shutdown(); } if (main.filesScanned > 0) { float s = (t2 - t1) / 1000F; float mb = main.totalSize / 1048576F; System.out.println(MessageFormat.format(rb.getString("sent"), main.filesSent, mb, s, mb / s)); } } catch (ParseException e) { System.err.println("storescu: " + e.getMessage()); System.err.println(rb.getString("try")); System.exit(2); } catch (Exception e) { System.err.println("storescu: " + e.getMessage()); e.printStackTrace(); System.exit(2); } }
From source file:com.puppycrawl.tools.checkstyle.Main.java
/** * Loops over the files specified checking them for errors. The exit code * is the number of errors found in all the files. * @param args the command line arguments. * @throws FileNotFoundException if there is a problem with files access **//*from w w w . j a v a 2 s. c om*/ public static void main(String... args) throws FileNotFoundException { int errorCounter = 0; boolean cliViolations = false; // provide proper exit code based on results. final int exitWithCliViolation = -1; int exitStatus = 0; try { //parse CLI arguments final CommandLine commandLine = parseCli(args); // show version and exit if it is requested if (commandLine.hasOption(OPTION_V_NAME)) { System.out.println("Checkstyle version: " + Main.class.getPackage().getImplementationVersion()); exitStatus = 0; } else { // return error if something is wrong in arguments final List<String> messages = validateCli(commandLine); cliViolations = !messages.isEmpty(); if (cliViolations) { exitStatus = exitWithCliViolation; errorCounter = 1; for (String message : messages) { System.out.println(message); } } else { // create config helper object final CliOptions config = convertCliToPojo(commandLine); // run Checker errorCounter = runCheckstyle(config); exitStatus = errorCounter; } } } catch (ParseException pex) { // something wrong with arguments - print error and manual cliViolations = true; exitStatus = exitWithCliViolation; errorCounter = 1; System.out.println(pex.getMessage()); printUsage(); } catch (CheckstyleException e) { exitStatus = EXIT_WITH_CHECKSTYLE_EXCEPTION_CODE; errorCounter = 1; printMessageAndCause(e); } finally { // return exit code base on validation of Checker if (errorCounter != 0 && !cliViolations) { System.out.println(String.format("Checkstyle ends with %d errors.", errorCounter)); } if (exitStatus != 0) { System.exit(exitStatus); } } }
From source file:de.unisb.cs.st.javaslicer.slicing.DirectSlicer.java
public static void main(String[] args) { Options options = createOptions();//from w w w.j av a2 s .c om 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.rabbitmq.examples.MulticastMain.java
public static void main(String[] args) { Options options = getOptions();//from ww w.j av a 2s .c o m CommandLineParser parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('?')) { usage(options); System.exit(0); } String exchangeType = strArg(cmd, 't', "direct"); String exchangeName = strArg(cmd, 'e', exchangeType); String queueName = strArg(cmd, 'u', ""); int samplingInterval = intArg(cmd, 'i', 1); int rateLimit = intArg(cmd, 'r', 0); int producerCount = intArg(cmd, 'x', 1); int consumerCount = intArg(cmd, 'y', 1); int producerTxSize = intArg(cmd, 'm', 0); int consumerTxSize = intArg(cmd, 'n', 0); long confirm = intArg(cmd, 'c', -1); boolean autoAck = cmd.hasOption('a'); int prefetchCount = intArg(cmd, 'q', 0); int minMsgSize = intArg(cmd, 's', 0); int timeLimit = intArg(cmd, 'z', 0); List<?> flags = lstArg(cmd, 'f'); int frameMax = intArg(cmd, 'M', 0); int heartbeat = intArg(cmd, 'b', 0); String uri = strArg(cmd, 'h', "amqp://localhost"); boolean exclusive = "".equals(queueName); boolean autoDelete = !exclusive; //setup String id = UUID.randomUUID().toString(); Stats stats = new Stats(1000L * samplingInterval); ConnectionFactory factory = new ConnectionFactory(); factory.setUri(uri); factory.setRequestedFrameMax(frameMax); factory.setRequestedHeartbeat(heartbeat); Thread[] consumerThreads = new Thread[consumerCount]; Connection[] consumerConnections = new Connection[consumerCount]; for (int i = 0; i < consumerCount; i++) { System.out.println("starting consumer #" + i); Connection conn = factory.newConnection(); consumerConnections[i] = conn; Channel channel = conn.createChannel(); if (consumerTxSize > 0) channel.txSelect(); channel.exchangeDeclare(exchangeName, exchangeType); String qName = channel .queueDeclare(queueName, flags.contains("persistent"), exclusive, autoDelete, null) .getQueue(); if (prefetchCount > 0) channel.basicQos(prefetchCount); channel.queueBind(qName, exchangeName, id); Thread t = new Thread(new Consumer(channel, id, qName, consumerTxSize, autoAck, stats, timeLimit)); consumerThreads[i] = t; t.start(); } Thread[] producerThreads = new Thread[producerCount]; Connection[] producerConnections = new Connection[producerCount]; Channel[] producerChannels = new Channel[producerCount]; for (int i = 0; i < producerCount; i++) { System.out.println("starting producer #" + i); Connection conn = factory.newConnection(); producerConnections[i] = conn; Channel channel = conn.createChannel(); producerChannels[i] = channel; if (producerTxSize > 0) channel.txSelect(); if (confirm >= 0) channel.confirmSelect(); channel.exchangeDeclare(exchangeName, exchangeType); final Producer p = new Producer(channel, exchangeName, id, flags, producerTxSize, 1000L * samplingInterval, rateLimit, minMsgSize, timeLimit, confirm); channel.addReturnListener(p); channel.addConfirmListener(p); Thread t = new Thread(p); producerThreads[i] = t; t.start(); } for (int i = 0; i < producerCount; i++) { producerThreads[i].join(); producerChannels[i].clearReturnListeners(); producerChannels[i].clearConfirmListeners(); producerConnections[i].close(); } for (int i = 0; i < consumerCount; i++) { consumerThreads[i].join(); consumerConnections[i].close(); } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); usage(options); } catch (Exception e) { System.err.println("Main thread caught exception: " + e); e.printStackTrace(); System.exit(1); } }
From source file:graticules2wld.Main.java
/** * @param args//from w w w. j a va2 s .c o m * @throws Exception */ public static void main(String[] args) throws Exception { /* parse the command line arguments */ // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption("x", "originx", true, "x component of projected coordinates of upper left pixel"); options.addOption("y", "originy", true, "y component of projected coordinates of upper left pixel"); options.addOption("u", "tometers", true, "multiplication factor to get source units into meters"); options.addOption("h", "help", false, "prints this usage page"); options.addOption("d", "debug", false, "prints debugging information to stdout"); double originNorthing = 0; double originEasting = 0; String inputFileName = null; String outputFileName = null; try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("help")) printUsage(0); // print usage then exit using a non error exit status if (line.hasOption("debug")) debug = true; // these arguments are required if (!line.hasOption("originy") || !line.hasOption("originx")) printUsage(1); originNorthing = Double.parseDouble(line.getOptionValue("originy")); originEasting = Double.parseDouble(line.getOptionValue("originx")); if (line.hasOption("tometers")) unitsToMeters = Double.parseDouble(line.getOptionValue("tometers")); // two args should be left. the input csv file name and the output wld file name. String[] iofiles = line.getArgs(); if (iofiles.length < 2) { printUsage(1); } inputFileName = iofiles[0]; outputFileName = iofiles[1]; } catch (ParseException exp) { System.err.println("Unexpected exception:" + exp.getMessage()); System.exit(1); } // try to open the input file for reading and the output file for writing File graticulesCsvFile; BufferedReader csvReader = null; File wldFile; BufferedWriter wldWriter = null; try { graticulesCsvFile = new File(inputFileName); csvReader = new BufferedReader(new FileReader(graticulesCsvFile)); } catch (IOException exp) { System.err.println("Could not open input file for reading: " + inputFileName); System.exit(1); } try { wldFile = new File(outputFileName); wldWriter = new BufferedWriter(new FileWriter(wldFile)); } catch (IOException exp) { System.err.println("Could not open output file for writing: " + outputFileName); System.exit(1); } // list of lon graticules and lat graticules ArrayList<Graticule> lonGrats = new ArrayList<Graticule>(); ArrayList<Graticule> latGrats = new ArrayList<Graticule>(); // read the source CSV and convert its information into the two ArrayList<Graticule> data structures readCSV(csvReader, lonGrats, latGrats); // we now need to start finding the world file paramaters DescriptiveStatistics stats = new DescriptiveStatistics(); // find theta and phi for (Graticule g : latGrats) { stats.addValue(g.angle()); } double theta = stats.getMean(); // we use the mean of the lat angles as theta if (debug) System.out.println("theta range = " + Math.toDegrees(stats.getMax() - stats.getMin())); stats.clear(); for (Graticule g : lonGrats) { stats.addValue(g.angle()); } double phi = stats.getMean(); // ... and the mean of the lon angles for phi if (debug) System.out.println("phi range = " + Math.toDegrees(stats.getMax() - stats.getMin())); stats.clear(); // print these if in debug mode if (debug) { System.out.println("theta = " + Math.toDegrees(theta) + "deg"); System.out.println("phi = " + Math.toDegrees(phi) + "deg"); } // find x and y (distance beteen pixels in map units) Collections.sort(latGrats); Collections.sort(lonGrats); int prevMapValue = 0; //fixme: how to stop warning about not being initilised? Line2D prevGratPixelSys = new Line2D.Double(); boolean first = true; for (Graticule g : latGrats) { if (!first) { int deltaMapValue = Math.abs(g.realValue() - prevMapValue); double deltaPixelValue = (g.l.ptLineDist(prevGratPixelSys.getP1()) + (g.l.ptLineDist(prevGratPixelSys.getP2()))) / 2; double delta = deltaMapValue / deltaPixelValue; stats.addValue(delta); } else { first = false; prevMapValue = g.realValue(); prevGratPixelSys = (Line2D) g.l.clone(); } } double y = stats.getMean(); if (debug) System.out.println("y range = " + (stats.getMax() - stats.getMin())); stats.clear(); first = true; for (Graticule g : lonGrats) { if (!first) { int deltaMapValue = g.realValue() - prevMapValue; double deltaPixelValue = (g.l.ptLineDist(prevGratPixelSys.getP1()) + (g.l.ptLineDist(prevGratPixelSys.getP2()))) / 2; double delta = deltaMapValue / deltaPixelValue; stats.addValue(delta); } else { first = false; prevMapValue = g.realValue(); prevGratPixelSys = (Line2D) g.l.clone(); } } double x = stats.getMean(); if (debug) System.out.println("x range = " + (stats.getMax() - stats.getMin())); stats.clear(); if (debug) { System.out.println("x = " + x); System.out.println("y = " + y); } SimpleRegression regression = new SimpleRegression(); // C, F are translation terms: x, y map coordinates of the center of the upper-left pixel for (Graticule g : latGrats) { // find perp dist to pixel space 0,0 Double perpPixelDist = g.l.ptLineDist(new Point2D.Double(0, 0)); // find the map space distance from this graticule to the center of the 0,0 pixel Double perpMapDist = perpPixelDist * y; // perpMapDist / perpPixelDist = y regression.addData(perpMapDist, g.realValue()); } double F = regression.getIntercept(); regression.clear(); for (Graticule g : lonGrats) { // find perp dist to pixel space 0,0 Double perpPixelDist = g.l.ptLineDist(new Point2D.Double(0, 0)); // find the map space distance from this graticule to the center of the 0,0 pixel Double perpMapDist = perpPixelDist * x; // perpMapDist / perpPixelDist = x regression.addData(perpMapDist, g.realValue()); } double C = regression.getIntercept(); regression.clear(); if (debug) { System.out.println("Upper Left pixel has coordinates " + C + ", " + F); } // convert to meters C *= unitsToMeters; F *= unitsToMeters; // C,F store the projected (in map units) coordinates of the upper left pixel. // originNorthing,originEasting is the offset we need to apply to 0,0 to push the offsets into our global coordinate system C = originEasting + C; F = originNorthing + F; // calculate the affine transformation matrix elements double D = -1 * x * unitsToMeters * Math.sin(theta); double A = x * unitsToMeters * Math.cos(theta); double B = y * unitsToMeters * Math.sin(phi); // if should be negative, it'll formed by negative sin double E = -1 * y * unitsToMeters * Math.cos(phi); /* * Line 1: A: pixel size in the x-direction in map units/pixel * Line 2: D: rotation about y-axis * Line 3: B: rotation about x-axis * Line 4: E: pixel size in the y-direction in map units, almost always negative[3] * Line 5: C: x-coordinate of the center of the upper left pixel * Line 6: F: y-coordinate of the center of the upper left pixel */ if (debug) { System.out.println("A = " + A); System.out.println("D = " + D); System.out.println("B = " + B); System.out.println("E = " + E); System.out.println("C = " + C); System.out.println("F = " + F); // write the world file System.out.println(); System.out.println("World File:"); System.out.println(A); System.out.println(D); System.out.println(B); System.out.println(E); System.out.println(C); System.out.println(F); } // write to the .wld file wldWriter.write(A + "\n"); wldWriter.write(D + "\n"); wldWriter.write(B + "\n"); wldWriter.write(E + "\n"); wldWriter.write(C + "\n"); wldWriter.write(F + "\n"); wldWriter.close(); }
From source file:com.cws.esolutions.security.main.PasswordUtility.java
public static void main(final String[] args) { final String methodName = PasswordUtility.CNAME + "#main(final String[] args)"; if (DEBUG) {//from www . j av a 2 s. com DEBUGGER.debug("Value: {}", methodName); } if (args.length == 0) { HelpFormatter usage = new HelpFormatter(); usage.printHelp(PasswordUtility.CNAME, options, true); System.exit(1); } BufferedReader bReader = null; BufferedWriter bWriter = null; try { // load service config first !! SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG, false); if (DEBUG) { DEBUGGER.debug("Options options: {}", options); for (String arg : args) { DEBUGGER.debug("Value: {}", arg); } } CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse(options, args); if (DEBUG) { DEBUGGER.debug("CommandLineParser parser: {}", parser); DEBUGGER.debug("CommandLine commandLine: {}", commandLine); DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions()); DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList()); } final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData(); final SecurityConfig secConfig = secConfigData.getSecurityConfig(); final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo(); final SystemConfig systemConfig = secConfigData.getSystemConfig(); if (DEBUG) { DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData); DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig); DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig); DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig); } if (commandLine.hasOption("encrypt")) { if ((StringUtils.isBlank(repoConfig.getPasswordFile())) || (StringUtils.isBlank(repoConfig.getSaltFile()))) { System.err.println("The password/salt files are not configured. Entries will not be stored!"); } File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile()); File saltFile = FileUtils.getFile(repoConfig.getSaltFile()); if (DEBUG) { DEBUGGER.debug("File passwordFile: {}", passwordFile); DEBUGGER.debug("File saltFile: {}", saltFile); } final String entryName = commandLine.getOptionValue("entry"); final String username = commandLine.getOptionValue("username"); final String password = commandLine.getOptionValue("password"); final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength()); if (DEBUG) { DEBUGGER.debug("String entryName: {}", entryName); DEBUGGER.debug("String username: {}", username); DEBUGGER.debug("String password: {}", password); DEBUGGER.debug("String salt: {}", salt); } final String encodedSalt = PasswordUtils.base64Encode(salt); final String encodedUserName = PasswordUtils.base64Encode(username); final String encryptedPassword = PasswordUtils.encryptText(password, salt, secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()); final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword); if (DEBUG) { DEBUGGER.debug("String encodedSalt: {}", encodedSalt); DEBUGGER.debug("String encodedUserName: {}", encodedUserName); DEBUGGER.debug("String encodedPassword: {}", encodedPassword); } if (commandLine.hasOption("store")) { try { new File(passwordFile.getParent()).mkdirs(); new File(saltFile.getParent()).mkdirs(); boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile(); if (DEBUG) { DEBUGGER.debug("saltFileExists: {}", saltFileExists); } // write the salt out first if (!(saltFileExists)) { throw new IOException("Unable to create salt file"); } boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile(); if (!(passwordFileExists)) { throw new IOException("Unable to create password file"); } if (commandLine.hasOption("replace")) { File[] files = new File[] { saltFile, passwordFile }; if (DEBUG) { DEBUGGER.debug("File[] files: {}", (Object) files); } for (File file : files) { if (DEBUG) { DEBUGGER.debug("File: {}", file); } String currentLine = null; File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile"); if (DEBUG) { DEBUGGER.debug("File tmpFile: {}", tmpFile); } bReader = new BufferedReader(new FileReader(file)); bWriter = new BufferedWriter(new FileWriter(tmpFile)); while ((currentLine = bReader.readLine()) != null) { if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) { bWriter.write(currentLine + System.getProperty("line.separator")); bWriter.flush(); } } bWriter.close(); FileUtils.deleteQuietly(file); FileUtils.copyFile(tmpFile, file); FileUtils.deleteQuietly(tmpFile); } } FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt + System.getProperty("line.separator"), true); FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + "," + encodedPassword + System.getProperty("line.separator"), true); } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } System.out.println("Entry Name " + entryName + " stored."); } if (commandLine.hasOption("decrypt")) { String saltEntryName = null; String saltEntryValue = null; String decryptedPassword = null; String passwordEntryName = null; if ((StringUtils.isEmpty(commandLine.getOptionValue("entry")) && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) { throw new ParseException("No entry or username was provided to decrypt."); } if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) { throw new ParseException("no entry provided to decrypt"); } String entryName = commandLine.getOptionValue("entry"); String username = commandLine.getOptionValue("username"); if (DEBUG) { DEBUGGER.debug("String entryName: {}", entryName); DEBUGGER.debug("String username: {}", username); } File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile()); File saltFile = FileUtils.getFile(repoConfig.getSaltFile()); if (DEBUG) { DEBUGGER.debug("File passwordFile: {}", passwordFile); DEBUGGER.debug("File saltFile: {}", saltFile); } if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) { throw new IOException( "Unable to read configured password/salt file. Please check configuration and/or permissions."); } for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) { saltEntryName = lineEntry.split(",")[0]; if (DEBUG) { DEBUGGER.debug("String saltEntryName: {}", saltEntryName); } if (StringUtils.equals(saltEntryName, entryName)) { saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]); break; } } if (StringUtils.isEmpty(saltEntryValue)) { throw new SecurityException("No entries were found that matched the provided information"); } for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) { passwordEntryName = lineEntry.split(",")[0]; if (DEBUG) { DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName); } if (StringUtils.equals(passwordEntryName, saltEntryName)) { String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]); decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue, secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()); break; } } if (StringUtils.isEmpty(decryptedPassword)) { throw new SecurityException("No entries were found that matched the provided information"); } System.out.println(decryptedPassword); } else if (commandLine.hasOption("encode")) { System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0))); } else if (commandLine.hasOption("decode")) { System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0))); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); System.err.println("An error occurred during processing: " + iox.getMessage()); System.exit(1); } catch (ParseException px) { ERROR_RECORDER.error(px.getMessage(), px); System.err.println("An error occurred during processing: " + px.getMessage()); System.exit(1); } catch (SecurityException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); System.err.println("An error occurred during processing: " + sx.getMessage()); System.exit(1); } catch (SecurityServiceException ssx) { ERROR_RECORDER.error(ssx.getMessage(), ssx); System.exit(1); } finally { try { if (bReader != null) { bReader.close(); } if (bWriter != null) { bReader.close(); } } catch (IOException iox) { } } System.exit(0); }
From source file:com.zimbra.soap.SoapCommandUtil.java
public static void main(String[] args) { CliUtil.toolSetup();//from ww w. j av a 2s.co m SoapTransport.setDefaultUserAgent("zmsoap", null); SoapCommandUtil app = new SoapCommandUtil(); try { app.parseCommandLine(args); } catch (ParseException e) { app.usage(e.getMessage()); } try { app.run(); } catch (ServiceException e) { System.err.println(formatServiceException(e)); if (app.mVerbose) { e.printStackTrace(System.err); } System.exit(1); } catch (Exception e) { if (app.mVerbose || app.mVeryVerbose) { e.printStackTrace(System.err); } else { System.err.println(e); } } }