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

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

Introduction

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

Prototype

public boolean hasOption(char opt) 

Source Link

Document

Query to see if an option has been set.

Usage

From source file:boa.BoaMain.java

public static void main(final String[] args) throws IOException {
    final Options options = new Options();

    options.addOption("p", "parse", false, "parse and semantic check a Boa program (don't generate code)");
    options.addOption("c", "compile", false, "compile a Boa program");
    options.addOption("e", "execute", false, "execute a Boa program locally");
    options.addOption("g", "generate", false, "generate a Boa dataset");

    try {//from   ww  w. j a v  a 2s .  c o m
        if (args.length == 0) {
            printHelp(options, null);
            return;
        } else {
            final CommandLine cl = new PosixParser().parse(options, new String[] { args[0] });
            final String[] tempargs = new String[args.length - 1];
            System.arraycopy(args, 1, tempargs, 0, args.length - 1);

            if (cl.hasOption("c")) {
                boa.compiler.BoaCompiler.main(tempargs);
            } else if (cl.hasOption("p")) {
                boa.compiler.BoaCompiler.parseOnly(tempargs);
            } else if (cl.hasOption("e")) {
                boa.evaluator.BoaEvaluator.main(tempargs);
            } else if (cl.hasOption("g")) {
                boa.datagen.BoaGenerator.main(tempargs);
            }
        }
    } catch (final org.apache.commons.cli.ParseException e) {
        printHelp(options, e.getMessage());
    }
}

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 ww w .j av a  2 s .  com*/
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:at.newmedialab.ldpath.backend.linkeddata.LDQuery.java

public static void main(String[] args) {
    Options options = buildOptions();/*from w ww  . ja va2  s. c  o  m*/

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

        Level logLevel = Level.WARN;

        if (cmd.hasOption("loglevel")) {
            String logLevelName = cmd.getOptionValue("loglevel");
            if ("DEBUG".equals(logLevelName.toUpperCase())) {
                logLevel = Level.DEBUG;
            } else if ("INFO".equals(logLevelName.toUpperCase())) {
                logLevel = Level.INFO;
            } else if ("WARN".equals(logLevelName.toUpperCase())) {
                logLevel = Level.WARN;
            } else if ("ERROR".equals(logLevelName.toUpperCase())) {
                logLevel = Level.ERROR;
            } else {
                log.error("unsupported log level: {}", logLevelName);
            }
        }

        if (logLevel != null) {
            for (String logname : new String[] { "at", "org", "net", "com" }) {

                ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
                        .getLogger(logname);
                logger.setLevel(logLevel);
            }
        }

        String format = null;
        if (cmd.hasOption("format")) {
            format = cmd.getOptionValue("format");
        }

        GenericSesameBackend backend;
        if (cmd.hasOption("store")) {
            backend = new LDPersistentBackend(new File(cmd.getOptionValue("store")));
        } else {
            backend = new LDMemoryBackend();
        }

        Resource context = null;
        if (cmd.hasOption("context")) {
            context = backend.getRepository().getValueFactory().createURI(cmd.getOptionValue("context"));
        }

        if (backend != null && context != null) {
            LDPath<Value> ldpath = new LDPath<Value>(backend);

            if (cmd.hasOption("path")) {
                String path = cmd.getOptionValue("path");

                for (Value v : ldpath.pathQuery(context, path, null)) {
                    System.out.println(v.stringValue());
                }
            } else if (cmd.hasOption("program")) {
                File file = new File(cmd.getOptionValue("program"));

                Map<String, Collection<?>> result = ldpath.programQuery(context, new FileReader(file));

                for (String field : result.keySet()) {
                    StringBuilder line = new StringBuilder();
                    line.append(field);
                    line.append(" = ");
                    line.append("{");
                    for (Iterator it = result.get(field).iterator(); it.hasNext();) {
                        line.append(it.next().toString());
                        if (it.hasNext()) {
                            line.append(", ");
                        }
                    }
                    line.append("}");
                    System.out.println(line);

                }
            }
        }

        if (backend instanceof LDPersistentBackend) {
            ((LDPersistentBackend) backend).shutdown();
        }

    } catch (ParseException e) {
        System.err.println("invalid arguments");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    } catch (LDPathParseException e) {
        System.err.println("path or program could not be parsed");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        System.err.println("file or program could not be found");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    } catch (IOException e) {
        System.err.println("could not access cache data directory");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    }

}

From source file:eu.itesla_project.offline.mpi.Master.java

public static void main(String[] args) throws Exception {
    try {//w w  w  .j  a  va 2  s. com
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(OPTIONS, args);

        Mode mode = Mode.valueOf(line.getOptionValue("mode"));
        String simulationDbName = line.hasOption("simulation-db-name")
                ? line.getOptionValue("simulation-db-name")
                : OfflineConfig.DEFAULT_SIMULATION_DB_NAME;
        String rulesDbName = line.hasOption("rules-db-name") ? line.getOptionValue("rules-db-name")
                : OfflineConfig.DEFAULT_RULES_DB_NAME;
        String metricsDbName = line.hasOption("metrics-db-name") ? line.getOptionValue("metrics-db-name")
                : OfflineConfig.DEFAULT_METRICS_DB_NAME;
        Path tmpDir = Paths.get(line.getOptionValue("tmp-dir"));
        Class<?> statisticsFactoryClass = Class.forName(line.getOptionValue("statistics-factory-class"));
        Path statisticsDbDir = Paths.get(line.getOptionValue("statistics-db-dir"));
        String statisticsDbName = line.getOptionValue("statistics-db-name");
        int coresPerRank = Integer.parseInt(line.getOptionValue("cores"));
        Path stdOutArchive = line.hasOption("stdout-archive") ? Paths.get(line.getOptionValue("stdout-archive"))
                : null;
        String workflowId = line.hasOption("workflow") ? line.getOptionValue("workflow") : null;

        MpiExecutorContext mpiExecutorContext = new MultiStateNetworkAwareMpiExecutorContext();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        ExecutorService offlineExecutorService = MultiStateNetworkAwareExecutors
                .newSizeLimitedThreadPool("OFFLINE_POOL", 100);
        try {
            MpiStatisticsFactory statisticsFactory = statisticsFactoryClass
                    .asSubclass(MpiStatisticsFactory.class).newInstance();
            try (MpiStatistics statistics = statisticsFactory.create(statisticsDbDir, statisticsDbName)) {
                try (ComputationManager computationManager = new MpiComputationManager(tmpDir, statistics,
                        mpiExecutorContext, coresPerRank, false, stdOutArchive)) {
                    OfflineConfig config = OfflineConfig.load();
                    try (LocalOfflineApplication application = new LocalOfflineApplication(config,
                            computationManager, simulationDbName, rulesDbName, metricsDbName,
                            scheduledExecutorService, offlineExecutorService)) {
                        switch (mode) {
                        case ui:
                            application.await();
                            break;

                        case simulations: {
                            if (workflowId == null) {
                                workflowId = application.createWorkflow(null,
                                        OfflineWorkflowCreationParameters.load());
                            }
                            application.startWorkflowAndWait(workflowId, OfflineWorkflowStartParameters.load());
                        }
                            break;

                        case rules: {
                            if (workflowId == null) {
                                throw new RuntimeException("Workflow '" + workflowId + "' not found");
                            }
                            application.computeSecurityRulesAndWait(workflowId);
                        }
                            break;

                        default:
                            throw new IllegalArgumentException("Invalid mode " + mode);
                        }
                    }
                }
            }
        } finally {
            mpiExecutorContext.shutdown();
            offlineExecutorService.shutdown();
            scheduledExecutorService.shutdown();
            offlineExecutorService.awaitTermination(15, TimeUnit.MINUTES);
            scheduledExecutorService.awaitTermination(15, TimeUnit.MINUTES);
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("master", OPTIONS, true);
        System.exit(-1);
    } catch (Throwable t) {
        LOGGER.error(t.toString(), t);
        System.exit(-1);
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.QueryGenNMSLIB.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption(CommonParams.QUERY_FILE_PARAM, null, true, CommonParams.QUERY_FILE_DESC);
    options.addOption(CommonParams.MEMINDEX_PARAM, null, true, CommonParams.MEMINDEX_DESC);
    options.addOption(CommonParams.KNN_QUERIES_PARAM, null, true, CommonParams.KNN_QUERIES_DESC);
    options.addOption(CommonParams.NMSLIB_FIELDS_PARAM, null, true, CommonParams.NMSLIB_FIELDS_DESC);
    options.addOption(CommonParams.MAX_NUM_QUERY_PARAM, null, true, CommonParams.MAX_NUM_QUERY_DESC);
    options.addOption(CommonParams.SEL_PROB_PARAM, null, true, CommonParams.SEL_PROB_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    BufferedWriter knnQueries = null;

    int maxNumQuery = Integer.MAX_VALUE;

    Float selProb = null;/*from  w ww. ja v a 2 s. com*/

    try {
        CommandLine cmd = parser.parse(options, args);
        String queryFile = null;

        if (cmd.hasOption(CommonParams.QUERY_FILE_PARAM)) {
            queryFile = cmd.getOptionValue(CommonParams.QUERY_FILE_PARAM);
        } else {
            Usage("Specify 'query file'", options);
        }

        String knnQueriesFile = cmd.getOptionValue(CommonParams.KNN_QUERIES_PARAM);

        if (null == knnQueriesFile)
            Usage("Specify '" + CommonParams.KNN_QUERIES_DESC + "'", options);

        String tmpn = cmd.getOptionValue(CommonParams.MAX_NUM_QUERY_PARAM);
        if (tmpn != null) {
            try {
                maxNumQuery = Integer.parseInt(tmpn);
            } catch (NumberFormatException e) {
                Usage("Maximum number of queries isn't integer: '" + tmpn + "'", options);
            }
        }

        String tmps = cmd.getOptionValue(CommonParams.NMSLIB_FIELDS_PARAM);
        if (null == tmps)
            Usage("Specify '" + CommonParams.NMSLIB_FIELDS_DESC + "'", options);
        String nmslibFieldList[] = tmps.split(",");

        knnQueries = new BufferedWriter(new FileWriter(knnQueriesFile));
        knnQueries.write("isQueryFile=1");
        knnQueries.newLine();
        knnQueries.newLine();

        String memIndexPref = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM);

        if (null == memIndexPref) {
            Usage("Specify '" + CommonParams.MEMINDEX_DESC + "'", options);
        }

        String tmpf = cmd.getOptionValue(CommonParams.SEL_PROB_PARAM);

        if (tmpf != null) {
            try {
                selProb = Float.parseFloat(tmpf);
            } catch (NumberFormatException e) {
                Usage("A selection probability isn't a number in the range (0,1)'" + tmpf + "'", options);
            }
            if (selProb < Float.MIN_NORMAL || selProb + Float.MIN_NORMAL >= 1)
                Usage("A selection probability isn't a number in the range (0,1)'" + tmpf + "'", options);
        }

        BufferedReader inpText = new BufferedReader(
                new InputStreamReader(CompressUtils.createInputStream(queryFile)));

        String docText = XmlHelper.readNextXMLIndexEntry(inpText);

        NmslibQueryGenerator queryGen = new NmslibQueryGenerator(nmslibFieldList, memIndexPref);

        Random rnd = new Random();

        for (int docNum = 1; docNum <= maxNumQuery
                && docText != null; ++docNum, docText = XmlHelper.readNextXMLIndexEntry(inpText)) {
            if (selProb != null) {
                if (rnd.nextFloat() > selProb)
                    continue;
            }

            Map<String, String> docFields = null;

            try {
                docFields = XmlHelper.parseXMLIndexEntry(docText);

                String queryObjStr = queryGen.getStrObjForKNNService(docFields);

                knnQueries.append(queryObjStr);
                knnQueries.newLine();
            } catch (SAXException e) {
                System.err.println("Parsing error, offending DOC:" + NL + docText + " doc # " + docNum);
                throw new Exception("Parsing error.");
            }
        }

        knnQueries.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
        if (null != knnQueries)
            try {
                knnQueries.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        try {
            if (knnQueries != null)
                knnQueries.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        System.exit(1);
    }

    System.out.println("Terminated successfully!");
}

From source file:it.iit.genomics.cru.genomics.misc.apps.Vcf2tabApp.java

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

    Options options = new Options();

    Option helpOpt = new Option("help", "print this message.");
    options.addOption(helpOpt);/*from  w  w  w .j  a  va2s . c om*/

    Option option1 = new Option("f", "filename", true, "VCF file to load");
    option1.setRequired(true);
    options.addOption(option1);

    option1 = new Option("o", "outputfile", true, "outputfilene");
    option1.setRequired(true);
    options.addOption(option1);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;

    try {
        // parse the command line arguments
        cmd = parser.parse(options, args, true);
    } catch (ParseException exp) {
        displayUsage("vcf2tab", options);
        System.exit(1);
    }
    if (cmd.hasOption("help")) {
        displayUsage("vcf2tab", options);
        System.exit(0);
    }

    String filename = cmd.getOptionValue("f");
    String outputfilename = cmd.getOptionValue("o");

    Vcf2tab loader = new Vcf2tab();

    loader.file2tab(filename, outputfilename); //(args[0]);

}

From source file:com.fatwire.dta.sscrawler.App.java

/**
 * @param args/*from w ww .j a  va 2s .  c om*/
 * @throws Exception
 */
public static void main(final String[] args) throws Exception {

    if (args.length < 1) {
        printUsage();
        System.exit(1);
    }
    DOMConfigurator.configure("conf/log4j.xml");
    final Options o = App.setUpCmd();
    final CommandLineParser p = new BasicParser();
    try {
        final CommandLine s = p.parse(o, args);
        if (s.hasOption('h')) {
            printUsage();
        } else if (s.getArgList().contains("crawler") && s.getArgList().size() > 1) {
            new App().doWork(s);
        } else if (s.getArgList().contains("warmer") && s.getArgList().size() > 1) {
            new CacheWarmer().doWork(s);
        } else {
            System.err.println("no subcommand and/or URI found on " + s.getArgList());
            printUsage();
            System.exit(1);
        }

    } catch (final ParseException e) {
        System.err.println(e.getMessage());
        printUsage();
        System.exit(1);
    }

}

From source file:com.rabbitmq.examples.PerfTest.java

public static void main(String[] args) {
    Options options = getOptions();//from   w  w w  . j  a  v  a 2s .  c om
    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', "");
        String routingKey = strArg(cmd, 'k', null);
        boolean randomRoutingKey = cmd.hasOption('K');
        int samplingInterval = intArg(cmd, 'i', 1);
        float producerRateLimit = floatArg(cmd, 'r', 0.0f);
        float consumerRateLimit = floatArg(cmd, 'R', 0.0f);
        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 multiAckEvery = intArg(cmd, 'A', 0);
        int channelPrefetch = intArg(cmd, 'Q', 0);
        int consumerPrefetch = intArg(cmd, 'q', 0);
        int minMsgSize = intArg(cmd, 's', 0);
        int timeLimit = intArg(cmd, 'z', 0);
        int producerMsgCount = intArg(cmd, 'C', 0);
        int consumerMsgCount = intArg(cmd, 'D', 0);
        List<?> flags = lstArg(cmd, 'f');
        int frameMax = intArg(cmd, 'M', 0);
        int heartbeat = intArg(cmd, 'b', 0);
        boolean predeclared = cmd.hasOption('p');

        String uri = strArg(cmd, 'h', "amqp://localhost");

        //setup
        PrintlnStats stats = new PrintlnStats(1000L * samplingInterval, producerCount > 0, consumerCount > 0,
                (flags.contains("mandatory") || flags.contains("immediate")), confirm != -1);

        ConnectionFactory factory = new ConnectionFactory();
        factory.setShutdownTimeout(0); // So we still shut down even with slow consumers
        factory.setUri(uri);
        factory.setRequestedFrameMax(frameMax);
        factory.setRequestedHeartbeat(heartbeat);

        MulticastParams p = new MulticastParams();
        p.setAutoAck(autoAck);
        p.setAutoDelete(true);
        p.setConfirm(confirm);
        p.setConsumerCount(consumerCount);
        p.setConsumerMsgCount(consumerMsgCount);
        p.setConsumerRateLimit(consumerRateLimit);
        p.setConsumerTxSize(consumerTxSize);
        p.setExchangeName(exchangeName);
        p.setExchangeType(exchangeType);
        p.setFlags(flags);
        p.setMultiAckEvery(multiAckEvery);
        p.setMinMsgSize(minMsgSize);
        p.setPredeclared(predeclared);
        p.setConsumerPrefetch(consumerPrefetch);
        p.setChannelPrefetch(channelPrefetch);
        p.setProducerCount(producerCount);
        p.setProducerMsgCount(producerMsgCount);
        p.setProducerTxSize(producerTxSize);
        p.setQueueName(queueName);
        p.setRoutingKey(routingKey);
        p.setRandomRoutingKey(randomRoutingKey);
        p.setProducerRateLimit(producerRateLimit);
        p.setTimeLimit(timeLimit);

        MulticastSet set = new MulticastSet(stats, factory, p);
        set.run(true);

        stats.printFinal();
    } 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:com.zimbra.cs.util.SmtpInject.java

public static void main(String[] args) {
    CliUtil.toolSetup();//from  w  ww.  j av a 2  s  .  co m
    CommandLine cl = parseArgs(args);

    if (cl.hasOption("h")) {
        usage(null);
    }

    String file = null;
    if (!cl.hasOption("f")) {
        usage("no file specified");
    } else {
        file = cl.getOptionValue("f");
    }
    try {
        ByteUtil.getContent(new File(file));
    } catch (IOException ioe) {
        usage(ioe.getMessage());
    }

    String host = null;
    if (!cl.hasOption("a")) {
        usage("no smtp server specified");
    } else {
        host = cl.getOptionValue("a");
    }

    String sender = null;
    if (!cl.hasOption("s")) {
        usage("no sender specified");
    } else {
        sender = cl.getOptionValue("s");
    }

    String recipient = null;
    if (!cl.hasOption("r")) {
        usage("no recipient specified");
    } else {
        recipient = cl.getOptionValue("r");
    }

    boolean trace = false;
    if (cl.hasOption("T")) {
        trace = true;
    }

    boolean tls = false;
    if (cl.hasOption("t")) {
        tls = true;
    }

    boolean auth = false;
    String user = null;
    String password = null;
    if (cl.hasOption("A")) {
        auth = true;
        if (!cl.hasOption("u")) {
            usage("auth enabled, no user specified");
        } else {
            user = cl.getOptionValue("u");
        }
        if (!cl.hasOption("p")) {
            usage("auth enabled, no password specified");
        } else {
            password = cl.getOptionValue("p");
        }
    }

    if (cl.hasOption("v")) {
        mLog.info("SMTP server: " + host);
        mLog.info("Sender: " + sender);
        mLog.info("Recipient: " + recipient);
        mLog.info("File: " + file);
        mLog.info("TLS: " + tls);
        mLog.info("Auth: " + auth);
        if (auth) {
            mLog.info("User: " + user);
            char[] dummyPassword = new char[password.length()];
            Arrays.fill(dummyPassword, '*');
            mLog.info("Password: " + new String(dummyPassword));
        }
    }

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host);

    if (auth) {
        props.put("mail.smtp.auth", "true");
    } else {
        props.put("mail.smtp.auth", "false");
    }

    if (tls) {
        props.put("mail.smtp.starttls.enable", "true");
    } else {
        props.put("mail.smtp.starttls.enable", "false");
    }

    // Disable certificate checking so we can test against
    // self-signed certificates
    props.put("mail.smtp.ssl.socketFactory", SocketFactories.dummySSLSocketFactory());

    Session session = Session.getInstance(props, null);
    session.setDebug(trace);

    try {
        // create a message
        MimeMessage msg = new ZMimeMessage(session, new ZSharedFileInputStream(file));
        InternetAddress[] address = { new JavaMailInternetAddress(recipient) };
        msg.setFrom(new JavaMailInternetAddress(sender));

        // attach the file to the message
        Transport transport = session.getTransport("smtp");
        transport.connect(null, user, password);
        transport.sendMessage(msg, address);

    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
        System.exit(1);
    }
}

From source file:ca.uqac.info.tag.Counter.TagCounter.java

public static void main(final String[] args) {
    // Parse command line arguments
    Options options = setupOptions();//from  www .j av  a 2  s. c o  m
    CommandLine c_line = setupCommandLine(args, options);

    String redirectionFile = "";
    String tagAnalyse = "";
    String inputFile = "";

    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }

    //Contains a redirection file for the output
    if (c_line.hasOption("redirection")) {
        try {
            redirectionFile = c_line.getOptionValue("redirection");
            PrintStream ps;
            ps = new PrintStream(redirectionFile);
            System.setOut(ps);
        } catch (FileNotFoundException e) {
            System.out.println("Redirection error !!!");
            e.printStackTrace();
        }
    }

    //Contains a tag
    if (c_line.hasOption("Tag")) {
        tagAnalyse = c_line.getOptionValue("t");
    } else {
        System.err.println("No Tag in Arguments");
        System.exit(ERR_ARGUMENTS);
    }

    //Contains a InputFile 
    if (c_line.hasOption("InputFile")) {
        inputFile = c_line.getOptionValue("i");
    } else {
        System.err.println("No Input File in Arguments");
        System.exit(ERR_ARGUMENTS);
    }

    //Start of the program
    System.out.println("-----------------------------------------------");
    System.out.println("The count of the Tag is start !!!");

    // Throw the Sax parsing for the file 
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser;
        parser = factory.newSAXParser();

        File Tagfile = new File(inputFile);
        DefaultHandler manager = new SaxTagHandlers(tagAnalyse);
        parser.parse(Tagfile, manager);
    } catch (ParserConfigurationException e) {
        System.out.println("Parser Configuration Exception for Sax !!!");
        e.printStackTrace();

    } catch (SAXException e) {
        System.out.println("Sax Exception during the parsing !!!");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("Input/Ouput Exception during the Sax parsing !!!");
        e.printStackTrace();
    }
}