Example usage for org.apache.commons.cli CommandLine getArgList

List of usage examples for org.apache.commons.cli CommandLine getArgList

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine getArgList.

Prototype

public List getArgList() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:net.sf.mcf2pdf.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();

    Option o = OptionBuilder.hasArg().isRequired()
            .withDescription("Installation location of My CEWE Photobook. REQUIRED.").create('i');
    options.addOption(o);//from  ww w.ja  v a 2  s  .co m
    options.addOption("h", false, "Prints this help and exits.");
    options.addOption("t", true, "Location of MCF temporary files.");
    options.addOption("w", true, "Location for temporary images generated during conversion.");
    options.addOption("r", true, "Sets the resolution to use for page rendering, in DPI. Default is 150.");
    options.addOption("n", true, "Sets the page number to render up to. Default renders all pages.");
    options.addOption("b", false, "Prevents rendering of binding between double pages.");
    options.addOption("x", false, "Generates only XSL-FO content instead of PDF content.");
    options.addOption("q", false, "Quiet mode - only errors are logged.");
    options.addOption("d", false, "Enables debugging logging output.");

    CommandLine cl;
    try {
        CommandLineParser parser = new PosixParser();
        cl = parser.parse(options, args);
    } catch (ParseException pe) {
        printUsage(options, pe);
        System.exit(3);
        return;
    }

    if (cl.hasOption("h")) {
        printUsage(options, null);
        return;
    }

    if (cl.getArgs().length != 2) {
        printUsage(options,
                new ParseException("INFILE and OUTFILE must be specified. Arguments were: " + cl.getArgList()));
        System.exit(3);
        return;
    }

    File installDir = new File(cl.getOptionValue("i"));
    if (!installDir.isDirectory()) {
        printUsage(options, new ParseException("Specified installation directory does not exist."));
        System.exit(3);
        return;
    }

    File tempDir = null;
    String sTempDir = cl.getOptionValue("t");
    if (sTempDir == null) {
        tempDir = new File(new File(System.getProperty("user.home")), ".mcf");
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("MCF temporary location not specified and default location "
                    + tempDir + " does not exist."));
            System.exit(3);
            return;
        }
    } else {
        tempDir = new File(sTempDir);
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("Specified temporary location does not exist."));
            System.exit(3);
            return;
        }
    }

    File mcfFile = new File(cl.getArgs()[0]);
    if (!mcfFile.isFile()) {
        printUsage(options, new ParseException("MCF input file does not exist."));
        System.exit(3);
        return;
    }
    mcfFile = mcfFile.getAbsoluteFile();

    File tempImages = new File(new File(System.getProperty("user.home")), ".mcf2pdf");
    if (cl.hasOption("w")) {
        tempImages = new File(cl.getOptionValue("w"));
        if (!tempImages.mkdirs() && !tempImages.isDirectory()) {
            printUsage(options,
                    new ParseException("Specified working dir does not exist and could not be created."));
            System.exit(3);
            return;
        }
    }

    int dpi = 150;
    if (cl.hasOption("r")) {
        try {
            dpi = Integer.valueOf(cl.getOptionValue("r")).intValue();
            if (dpi < 30 || dpi > 600)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options,
                    new ParseException("Parameter for option -r must be an integer between 30 and 600."));
        }
    }

    int maxPageNo = -1;
    if (cl.hasOption("n")) {
        try {
            maxPageNo = Integer.valueOf(cl.getOptionValue("n")).intValue();
            if (maxPageNo < 0)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options, new ParseException("Parameter for option -n must be an integer >= 0."));
        }
    }

    boolean binding = true;
    if (cl.hasOption("b")) {
        binding = false;
    }

    OutputStream finalOut;
    if (cl.getArgs()[1].equals("-"))
        finalOut = System.out;
    else {
        try {
            finalOut = new FileOutputStream(cl.getArgs()[1]);
        } catch (IOException e) {
            printUsage(options, new ParseException("Output file could not be created."));
            System.exit(3);
            return;
        }
    }

    // configure logging, if no system property is present
    if (System.getProperty("log4j.configuration") == null) {
        PropertyConfigurator.configure(Main.class.getClassLoader().getResource("log4j.properties"));

        Logger.getRootLogger().setLevel(Level.INFO);
        if (cl.hasOption("q"))
            Logger.getRootLogger().setLevel(Level.ERROR);
        if (cl.hasOption("d"))
            Logger.getRootLogger().setLevel(Level.DEBUG);
    }

    // start conversion to XSL-FO
    // if -x is specified, this is the only thing we do
    OutputStream xslFoOut;
    if (cl.hasOption("x"))
        xslFoOut = finalOut;
    else
        xslFoOut = new ByteArrayOutputStream();

    Log log = LogFactory.getLog(Main.class);

    try {
        new Mcf2FoConverter(installDir, tempDir, tempImages).convert(mcfFile, xslFoOut, dpi, binding,
                maxPageNo);
        xslFoOut.flush();

        if (!cl.hasOption("x")) {
            // convert to PDF
            log.debug("Converting XSL-FO data to PDF");
            byte[] data = ((ByteArrayOutputStream) xslFoOut).toByteArray();
            PdfUtil.convertFO2PDF(new ByteArrayInputStream(data), finalOut, dpi);
            finalOut.flush();
        }
    } catch (Exception e) {
        log.error("An exception has occured", e);
        System.exit(1);
        return;
    } finally {
        if (finalOut instanceof FileOutputStream) {
            try {
                finalOut.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:edu.ksu.cis.indus.staticanalyses.callgraphs.CallGraphXMLizerCLI.java

/**
 * The entry point to the program via command line.
 * /*from w w  w.jav a 2s.  c o  m*/
 * @param args is the command line arguments.
 * @throws RuntimeException when the analyses fail.
 */
public static void main(final String[] args) {
    final Options _options = new Options();
    Option _option = new Option("c", "cumulative", false,
            "Builds one call graph that includes all root methods.");
    _options.addOption(_option);
    _option = new Option("o", "output", true,
            "Directory into which xml files will be written into.  Defaults to current directory if omitted");
    _option.setArgs(1);
    _option.setArgName("output-dir");
    _options.addOption(_option);
    _option = new Option("j", "jimple", false, "Dump xmlized jimple.");
    _option.setArgName("dump-jimple");
    _options.addOption(_option);
    _option = new Option("p", "soot-classpath", true, "Prepend this to soot class path.");
    _option.setArgs(1);
    _option.setArgName("classpath");
    _option.setOptionalArg(false);
    _options.addOption(_option);
    _option = new Option("h", "help", false, "Display message.");
    _option.setOptionalArg(false);
    _options.addOption(_option);
    _option = new Option("t", "call-graph-type", true,
            "Call graph type.  This has to be one of {cha, rta, ofa-oi, " + "ofa-oirt, ofa-os}.");
    _option.setArgs(1);
    _option.setArgName("type");
    _option.setRequired(true);
    _options.addOption(_option);
    _option = new Option("S", "scope", true, "The scope that should be analyzed.");
    _option.setArgs(1);
    _option.setArgName("scope");
    _option.setRequired(false);
    _options.addOption(_option);

    final PosixParser _parser = new PosixParser();

    try {
        final CommandLine _cl = _parser.parse(_options, args);

        if (_cl.hasOption('h')) {
            printUsage(_options);
            System.exit(1);
        }

        String _outputDir = _cl.getOptionValue('o');

        if (_outputDir == null) {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("Defaulting to current directory for output.");
            }
            _outputDir = ".";
        }

        if (_cl.getArgList().isEmpty()) {
            throw new MissingArgumentException("Please specify atleast one class.");
        }

        final CallGraphXMLizerCLI _cli = new CallGraphXMLizerCLI();

        _cli.xmlizer.setXmlOutputDir(_outputDir);
        _cli.xmlizer.setGenerator(new UniqueJimpleIDGenerator());
        _cli.setCumulative(_cl.hasOption('c'));
        _cli.setClassNames(_cl.getArgList());
        _cli.addToSootClassPath(_cl.getOptionValue('p'));

        if (_cl.hasOption('S')) {
            _cli.setScopeSpecFile(_cl.getOptionValue('S'));
        }

        _cli.initialize();

        _cli.execute(_cl.hasOption('j'), _cl.getOptionValue('t'));
    } catch (final ParseException _e) {
        LOGGER.error("Error while parsing command line.", _e);
        System.out.println("Error while parsing command line." + _e);
        printUsage(_options);
    } catch (final Throwable _e) {
        LOGGER.error("Beyond our control. May day! May day!", _e);
        throw new RuntimeException(_e);
    }
}

From source file:com.aerospike.examples.tweetaspike.Program.java

public static void main(String[] args) throws AerospikeException {
    try {/*from   w  w  w . ja  v a 2  s.com*/
        Options options = new Options();
        options.addOption("h", "host", true, "Server hostname (default: 12)");
        options.addOption("p", "port", true, "Server port (default: 3000)");
        options.addOption("n", "namespace", true, "Namespace (default: test)");
        options.addOption("s", "set", true, "Set (default: demo)");
        options.addOption("u", "usage", false, "Print usage.");

        CommandLineParser parser = new PosixParser();
        CommandLine cl = parser.parse(options, args, false);

        String host = cl.getOptionValue("h", "127.0.0.1");
        String portString = cl.getOptionValue("p", "3000");
        int port = Integer.parseInt(portString);
        String namespace = cl.getOptionValue("n", "test");
        String set = cl.getOptionValue("s", "demo");
        log.debug("Host: " + host);
        log.debug("Port: " + port);
        log.debug("Namespace: " + namespace);
        log.debug("Set: " + set);

        @SuppressWarnings("unchecked")
        List<String> cmds = cl.getArgList();
        if (cmds.size() == 0 && cl.hasOption("u")) {
            logUsage(options);
            return;
        }

        Program as = new Program(host, port, namespace, set);

        as.work();

    } catch (Exception e) {
        log.error("Critical error", e);
    }
}

From source file:com.cyberway.issue.io.arc.ARCReader.java

/**
 * Command-line interface to ARCReader./*from   w w w. jav  a2 s.co  m*/
 *
 * Here is the command-line interface:
 * <pre>
 * usage: java com.cyberway.issue.io.arc.ARCReader [--offset=#] ARCFILE
 *  -h,--help      Prints this message and exits.
 *  -o,--offset    Outputs record at this offset into arc file.</pre>
 *
 * <p>See in <code>$HERITRIX_HOME/bin/arcreader</code> for a script that'll
 * take care of classpaths and the calling of ARCReader.
 *
 * <p>Outputs using a pseudo-CDX format as described here:
 * <a href="http://www.archive.org/web/researcher/cdx_legend.php">CDX
 * Legent</a> and here
 * <a href="http://www.archive.org/web/researcher/example_cdx.php">Example</a>.
 * Legend used in below is: 'CDX b e a m s c V (or v if uncompressed) n g'.
 * Hash is hard-coded straight SHA-1 hash of content.
 *
 * @param args Command-line arguments.
 * @throws ParseException Failed parse of the command line.
 * @throws IOException
 * @throws java.text.ParseException
 */
public static void main(String[] args) throws ParseException, IOException, java.text.ParseException {
    Options options = getOptions();
    options.addOption(new Option("p", "parse", false, "Parse headers."));
    PosixParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args, false);
    List cmdlineArgs = cmdline.getArgList();
    Option[] cmdlineOptions = cmdline.getOptions();
    HelpFormatter formatter = new HelpFormatter();

    // If no args, print help.
    if (cmdlineArgs.size() <= 0) {
        usage(formatter, options, 0);
    }

    // Now look at options passed.
    long offset = -1;
    boolean digest = false;
    boolean strict = false;
    boolean parse = false;
    String format = CDX;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'o':
            offset = Long.parseLong(cmdlineOptions[i].getValue());
            break;

        case 's':
            strict = true;
            break;

        case 'p':
            parse = true;
            break;

        case 'd':
            digest = getTrueOrFalse(cmdlineOptions[i].getValue());
            break;

        case 'f':
            format = cmdlineOptions[i].getValue().toLowerCase();
            boolean match = false;
            // List of supported formats.
            final String[] supportedFormats = { CDX, DUMP, GZIP_DUMP, HEADER, NOHEAD, CDX_FILE };
            for (int ii = 0; ii < supportedFormats.length; ii++) {
                if (supportedFormats[ii].equals(format)) {
                    match = true;
                    break;
                }
            }
            if (!match) {
                usage(formatter, options, 1);
            }
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    if (offset >= 0) {
        if (cmdlineArgs.size() != 1) {
            System.out.println("Error: Pass one arcfile only.");
            usage(formatter, options, 1);
        }
        ARCReader arc = ARCReaderFactory.get((String) cmdlineArgs.get(0), offset);
        arc.setStrict(strict);
        // We must parse headers if we need to skip them.
        if (format.equals(NOHEAD) || format.equals(HEADER)) {
            parse = true;
        }
        arc.setParseHttpHeaders(parse);
        outputRecord(arc, format);
    } else {
        for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) {
            String urlOrPath = (String) i.next();
            try {
                ARCReader r = ARCReaderFactory.get(urlOrPath);
                r.setStrict(strict);
                r.setParseHttpHeaders(parse);
                r.setDigest(digest);
                output(r, format);
            } catch (RuntimeException e) {
                // Write out name of file we failed on to help with
                // debugging.  Then print stack trace and try to keep
                // going.  We do this for case where we're being fed
                // a bunch of ARCs; just note the bad one and move
                // on to the next.
                System.err.println("Exception processing " + urlOrPath + ": " + e.getMessage());
                e.printStackTrace(System.err);
                System.exit(1);
            }
        }
    }
}

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  w w. j  av a  2 s . c om
    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();
    }
}

From source file:com.cws.esolutions.core.main.EmailUtility.java

public static final void main(final String[] args) {
    final String methodName = EmailUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {//from   w  ww .  j  a  va  2 s  .  c om
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", (Object) args);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(EmailUtility.CNAME, options, true);

        return;
    }

    try {
        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        URL xmlURL = null;
        JAXBContext context = null;
        Unmarshaller marshaller = null;
        CoreConfigurationData configData = null;

        xmlURL = FileUtils.getFile(commandLine.getOptionValue("config")).toURI().toURL();
        context = JAXBContext.newInstance(CoreConfigurationData.class);
        marshaller = context.createUnmarshaller();
        configData = (CoreConfigurationData) marshaller.unmarshal(xmlURL);

        EmailMessage message = new EmailMessage();
        message.setMessageTo(new ArrayList<String>(Arrays.asList(commandLine.getOptionValues("to"))));
        message.setMessageSubject(commandLine.getOptionValue("subject"));
        message.setMessageBody((String) commandLine.getArgList().get(0));
        message.setEmailAddr((StringUtils.isNotEmpty(commandLine.getOptionValue("from")))
                ? new ArrayList<String>(Arrays.asList(commandLine.getOptionValue("from")))
                : new ArrayList<String>(Arrays.asList(configData.getMailConfig().getMailFrom())));

        if (DEBUG) {
            DEBUGGER.debug("EmailMessage: {}", message);
        }

        try {
            EmailUtils.sendEmailMessage(configData.getMailConfig(), message, false);
        } catch (MessagingException mx) {
            System.err.println(
                    "An error occurred while sending the requested message. Exception: " + mx.getMessage());
        }
    } catch (ParseException px) {
        px.printStackTrace();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(EmailUtility.CNAME, options, true);
    } catch (MalformedURLException mx) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(EmailUtility.CNAME, options, true);
    } catch (JAXBException jx) {
        jx.printStackTrace();
        System.err.println("An error occurred while loading the provided configuration file. Cannot continue.");
    }
}

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) {/*  ww  w.ja va 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:frankhassanabad.com.github.Jasperize.java

/**
 * Main method to call through Java in order to take a LinkedInProfile on disk and load it.
 *
 * @param args command line arguments where the options are stored
 * @throws FileNotFoundException Thrown if any file its expecting cannot be found.
 * @throws JRException  If there's generic overall Jasper issues.
 * @throws ParseException If there's command line parsing issues.
 *///from   w w w . ja v  a2  s.  c  om
public static void main(String[] args) throws IOException, JRException, ParseException {

    Options options = new Options();
    options.addOption("h", "help", false, "Shows the help documentation");
    options.addOption("v", "version", false, "Shows the help documentation");
    options.addOption("cl", "coverLetter", false, "Utilizes a cover letter defined in coverletter.xml");
    options.addOption("sig", true, "Picture of your signature to add to the cover letter.");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Jasperize [OPTIONS] [InputJrxmlFile] [OutputExportFile]", options);
        System.exit(0);
    }
    if (cmd.hasOption("v")) {
        System.out.println("Version:" + version);
        System.exit(0);
    }
    boolean useCoverLetter = cmd.hasOption("cl");
    String signatureLocation = cmd.getOptionValue("sig");
    BufferedImage signatureImage = null;
    if (signatureLocation != null) {
        signatureImage = ImageIO.read(new File(signatureLocation));
        ;
    }

    @SuppressWarnings("unchecked")
    List<String> arguments = cmd.getArgList();

    final String jrxmlFile;
    final String jasperOutput;
    if (arguments.size() == 2) {
        jrxmlFile = arguments.get(0);
        jasperOutput = arguments.get(1);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else if (arguments.size() == 3) {
        jrxmlFile = arguments.get(1);
        jasperOutput = arguments.get(2);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else {
        System.out.println("Using the default arguments of:");
        jrxmlFile = "data/jasperTemplates/resume1.jrxml";
        jasperOutput = "data/jasperOutput/linkedInResume.pdf";
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    }

    final String compiledMasterFile;
    final String outputType;
    final String jrPrintFile;
    //Split the inputFile
    final String[] inputSplit = jrxmlFile.split("\\.");
    if (inputSplit.length != 2 || !(inputSplit[1].equalsIgnoreCase("jrxml"))) {
        //Error
        System.out.println("Your [InputjrxmlFile] (1st argument) should have a jrxml extension like such:");
        System.out.println("    data/jasperTemplates/resume1.jrxml");
        System.exit(1);
    }
    //Split the outputFile
    final String[] outputSplit = jasperOutput.split("\\.");
    if (outputSplit.length != 2) {
        //Error
        System.out.println("Your [OutputExportFile] (2nd argument) should have a file extension like such:");
        System.out.println("    data/jasperOutput/linkedInResume.pdf");
        System.exit(1);
    }

    File inputFile = new File(inputSplit[0]);
    String inputFileName = inputFile.getName();
    String inputFileParentPath = inputFile.getParent();

    File outputFile = new File(outputSplit[0]);
    String outputFileParentPath = outputFile.getParent();

    System.out.println("Compiling report(s)");
    compileAllJrxmlTemplateFiles(inputFileParentPath, outputFileParentPath);
    System.out.println("Done compiling report(s)");

    compiledMasterFile = outputFileParentPath + File.separator + inputFileName + ".jasper";
    jrPrintFile = outputFileParentPath + File.separator + inputFileName + ".jrprint";

    System.out.println("Filling report: " + compiledMasterFile);
    Reporting.fill(compiledMasterFile, useCoverLetter, signatureImage);
    System.out.println("Done filling reports");
    outputType = outputSplit[1];
    System.out.println("Creating output export file of: " + jasperOutput);
    if (outputType.equalsIgnoreCase("pdf")) {
        Reporting.pdf(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("pptx")) {
        Reporting.pptx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("docx")) {
        Reporting.docx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("odt")) {
        Reporting.odt(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("xhtml")) {
        Reporting.xhtml(jrPrintFile, jasperOutput);
    }
    System.out.println("Done creating output export file of: " + jasperOutput);
}

From source file:glacierpipe.GlacierPipeMain.java

public static void main(String[] args) throws IOException, ParseException {
    CommandLineParser parser = new GnuParser();

    CommandLine cmd = parser.parse(OPTIONS, args);

    if (cmd.hasOption("help")) {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            printHelp(writer);// w w w  .  j a  v a2s. com
        }

        System.exit(0);
    } else if (cmd.hasOption("upload")) {

        // Turn the CommandLine into Properties
        Properties cliProperties = new Properties();
        for (Iterator<?> i = cmd.iterator(); i.hasNext();) {
            Option o = (Option) i.next();

            String opt = o.getLongOpt();
            opt = opt != null ? opt : o.getOpt();

            String value = o.getValue();
            value = value != null ? value : "";

            cliProperties.setProperty(opt, value);
        }

        // Build up a configuration
        ConfigBuilder configBuilder = new ConfigBuilder();

        // Archive name
        List<?> archiveList = cmd.getArgList();
        if (archiveList.size() > 1) {
            throw new ParseException("Too many arguments");
        } else if (archiveList.isEmpty()) {
            throw new ParseException("No archive name provided");
        }

        configBuilder.setArchive(archiveList.get(0).toString());

        // All other arguments on the command line
        configBuilder.setFromProperties(cliProperties);

        // Load any config from the properties file
        Properties fileProperties = new Properties();
        try (InputStream in = new FileInputStream(configBuilder.propertiesFile)) {
            fileProperties.load(in);
        } catch (IOException e) {
            System.err.printf("Warning: unable to read properties file %s; %s%n", configBuilder.propertiesFile,
                    e);
        }

        configBuilder.setFromProperties(fileProperties);

        // ...
        Config config = new Config(configBuilder);

        IOBuffer buffer = new MemoryIOBuffer(config.partSize);

        AmazonGlacierClient client = new AmazonGlacierClient(
                new BasicAWSCredentials(config.accessKey, config.secretKey));
        client.setEndpoint(config.endpoint);

        // Actual upload
        try (InputStream in = new BufferedInputStream(System.in, 4096);
                PrintWriter writer = new PrintWriter(System.err);
                ObservableProperties configMonitor = config.reloadProperties
                        ? new ObservableProperties(config.propertiesFile)
                        : null;
                ProxyingThrottlingStrategy throttlingStrategy = new ProxyingThrottlingStrategy(config);) {
            TerminalGlacierPipeObserver observer = new TerminalGlacierPipeObserver(writer);

            if (configMonitor != null) {
                configMonitor.registerObserver(throttlingStrategy);
            }

            GlacierPipe pipe = new GlacierPipe(buffer, observer, config.maxRetries, throttlingStrategy);
            pipe.pipe(client, config.vault, config.archive, in);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }

        System.exit(0);
    } else {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            writer.println("No action specified.");
            printHelp(writer);
        }

        System.exit(-1);
    }
}

From source file:com.fluidops.iwb.tools.RepositoryTool.java

public static void main(String[] args) throws IOException {

    // Configure logging
    Log4JHandler.initLogging();//from w w  w .  jav  a  2 s . com
    Config.getConfigWithOverride();

    try {

        CommandLineParser parser = new BasicParser();
        Options options = buildOptions();

        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        // print the help
        if (line.getOptions().length == 0 || line.hasOption("help")) {
            printHelp(options);
            return;
        }

        @SuppressWarnings("unchecked")
        List<String> lArgs = line.getArgList();
        File source = null, target = null;
        if (lArgs.size() == 0) {
            source = IWBFileUtil.getFileInDataFolder(Config.getConfig().getRepositoryName());
            target = source;
        } else if (lArgs.size() == 1) {
            source = new File(lArgs.get(0));
            target = source;
        } else if (lArgs.size() == 2) {
            source = new File(lArgs.get(0));
            target = new File(lArgs.get(1));
        } else {
            System.out.println("Unrecognized arguments.");
            printHelp(options);
            System.exit(1);
        }

        // handle different options
        boolean checkGhosts = line.hasOption("g");
        String indices = line.hasOption("i") ? line.getOptionValue("i") : getDefaultNativeStoreIndices();
        if (line.hasOption("a")) {
            analyze(source, checkGhosts, indices);
            System.exit(0);
        }

        if (line.hasOption("f")) {
            analyzeAndFix(source, target, checkGhosts, indices);
            System.exit(0);
        }

        if (line.hasOption("c")) {
            cleanupRepository(source, target, indices);
            System.exit(0);
        }

        if (line.hasOption("u")) {
            copyUserData(source, target, indices);
            System.exit(0);
        }

    } catch (Exception exp) {
        System.out.println("Unexpected error: " + exp.getMessage());
        System.exit(1);
    }

}