Example usage for org.apache.commons.cli UnrecognizedOptionException printStackTrace

List of usage examples for org.apache.commons.cli UnrecognizedOptionException printStackTrace

Introduction

In this page you can find the example usage for org.apache.commons.cli UnrecognizedOptionException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:Cresendo.java

public static void main(String[] args) {
    String cfgFileReceiver = null; // Path to config file for eif receiver agent
    String cfgFileEngine = null; // Path to config file for xml event engine
    Options opts = null; // Command line options
    HelpFormatter hf = null; // Command line help formatter

    // Setup the message record which will contain text written to the log file
    ///*from  www.  jav a2 s. co  m*/
    // The message logger object is created when the "-l" is processed
    // as this object need to be associated with a log file
    //
    LogRecord msg = new LogRecord(LogRecord.TYPE_INFO, "Cresendo", "main", "", "", "", "", "");

    // Get the directory separator (defaults to "/")
    //
    dirSep = System.getProperty("file.separator", "/");

    // Initialise the structure containing the event handler objects
    //
    Vector<IEventHandler> eventHandler = new Vector<IEventHandler>(10, 10);

    // Process the command line arguments
    //
    try {
        opts = new Options();
        hf = new HelpFormatter();

        opts.addOption("h", "help", false, "Command line arguments help");
        opts.addOption("i", "instance name", true, "Name of cresendo instance");
        opts.addOption("l", "log dir", true, "Path to log file directory");
        opts.addOption("c", "config dir", true, "Path to configuarion file directory");

        opts.getOption("l").setRequired(true);
        opts.getOption("c").setRequired(true);

        BasicParser parser = new BasicParser();
        CommandLine cl = parser.parse(opts, args);

        // Print out some help and exit
        //
        if (cl.hasOption('h')) {
            hf.printHelp("Options", opts);
            System.exit(0);
        }

        // Set the instance name
        //
        if (cl.hasOption('i')) {
            instanceName = cl.getOptionValue('i'); // Set to something other than "default"
        }

        // Setup the message and trace logging objects for the EventEngine
        //
        if (cl.hasOption('l')) {
            // Setup the the paths to the message, trace and status log files
            //
            logDir = cl.getOptionValue("l");

            logPath = logDir + dirSep + instanceName + "-engine.log";
            tracePath = logDir + dirSep + instanceName + "-engine.trace";
            statusPath = logDir + dirSep + instanceName + "-engine.status";
        } else {
            // NOTE:  This should be picked up by the MissingOptionException catch below
            //        but I couldn't get this to work so I added the following code:
            //
            hf.printHelp("Option 'l' is a required option", opts);
            System.exit(1);
        }

        // Read the receiver and engine config files in the config directory
        //
        if (cl.hasOption('c')) {
            // Setup and check path to eif config file for TECAgent receiver object
            //
            configDir = cl.getOptionValue("c");
            cfgFileReceiver = configDir + dirSep + instanceName + ".conf";
            checkConfigFile(cfgFileReceiver);

            // Setup and check path to xml config file for the EventEngine
            //
            cfgFileEngine = cl.getOptionValue("c") + dirSep + instanceName + ".xml";
            checkConfigFile(cfgFileEngine);

        } else {
            // NOTE:  This should be picked up by the MissingOptionException catch below
            //        but I couldn't get this to work so I added the following code:
            //
            hf.printHelp("Option 'c' is a required option", opts);
            System.exit(1);
        }
    } catch (UnrecognizedOptionException e) {
        hf.printHelp(e.toString(), opts);
        System.exit(1);
    } catch (MissingOptionException e) {
        hf.printHelp(e.toString(), opts);
        System.exit(1);
    } catch (MissingArgumentException e) {
        hf.printHelp(e.toString(), opts);
        System.exit(1);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(1);
    } catch (Exception e) {
        System.err.println(e.toString());
        System.exit(1);
    }

    // Main program
    //
    try {
        // =====================================================================
        // Setup the message, trace and status logger objects
        //
        try {
            msgHandler = new FileHandler("cresendo", "message handler", logPath);
            msgHandler.openDevice();

            msgLogger = new MessageLogger("cresendo", "message log");
            msgLogger.addHandler(msgHandler);

            trcHandler = new FileHandler("cresendo", "trace handler", tracePath);
            trcHandler.openDevice();

            trcLogger = new TraceLogger("cresendo", "trace log");
            trcLogger.addHandler(trcHandler);

            statLogger = new StatusLogger(statusPath);
        } catch (Exception e) {
            System.err.println(e.toString());
            System.exit(1);
        }

        // Add the shutdown hook
        //
        Runtime.getRuntime().addShutdownHook(new ShutdownThread(msgLogger, instanceName));

        // ---------------------------------------------------------------------
        // =====================================================================
        // Load and parse the xml event engine configuration file
        //
        //
        msg.setText("Loading xml engine from: '" + cfgFileEngine + "'");

        try {
            XMLConfiguration xmlProcessor = new XMLConfiguration();
            xmlProcessor.setFileName(cfgFileEngine);

            // Validate the xml against a document type declaration
            //
            xmlProcessor.setValidating(true);

            // Don't interpolate the tag contents by splitting them on a delimiter
            // (ie by default a comma)
            //
            xmlProcessor.setDelimiterParsingDisabled(true);

            // This will throw a ConfigurationException if the xml document does not
            // conform to its dtd.  By doing this we hopefully catch any errors left
            // behind after the xml configuration file has been edited.
            //
            xmlProcessor.load();

            // Setup the trace flag
            //
            ConfigurationNode engine = xmlProcessor.getRootNode();
            List rootAttribute = engine.getAttributes();

            for (Iterator it = rootAttribute.iterator(); it.hasNext();) {
                ConfigurationNode attr = (ConfigurationNode) it.next();

                String attrName = attr.getName();
                String attrValue = (String) attr.getValue();

                if (attrValue == null || attrValue == "") {
                    System.err.println("\n  Error: The value of the attribute '" + attrName + "'"
                            + "\n         in the xml file '" + cfgFileEngine + "'" + "\n         is not set");
                    System.exit(1);
                }

                if (attrName.matches("trace")) {
                    if (attrValue.matches("true") || attrValue.matches("on")) {
                        trcLogger.setLogging(true);
                    }
                }

                if (attrName.matches("status")) {
                    if (attrValue.matches("true") || attrValue.matches("on")) {
                        statLogger.setLogging(true);
                    } else {
                        statLogger.setLogging(false);
                    }
                }

                if (attrName.matches("interval")) {
                    if (!attrValue.matches("[0-9]+")) {
                        System.err.println("\n  Error: The value of the interval attribute in: '"
                                + cfgFileEngine + "'" + "\n         should only contain digits from 0 to 9."
                                + "\n         It currently contains: '" + attrValue + "'");
                        System.exit(1);
                    }

                    statLogger.setInterval(Integer.parseInt(attrValue));
                }
            }

            // Now build and instantiate the list of classes that will process events
            // received by the TECAgent receiver in a chain like manner.
            //
            List classes = xmlProcessor.configurationsAt("class");

            for (Iterator it = classes.iterator(); it.hasNext();) {
                HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next();

                // sub contains now all data contained in a single <class></class> tag set
                //
                String className = sub.getString("name");

                // Log message
                //
                msg.setText(msg.getText() + "\n  Instantiated event handler class: '" + className + "'");

                // The angle brackets describing the class of object held by the
                // Vector are implemented by Java 1.5 and have 2 effects.
                //
                // 1. The list accepts only elements of that class and nothing else
                // (Of course thanks to Auto-Wrap you can also add double-values)
                //
                // 2. the get(), firstElement() ... Methods don't return a Object, but
                //    they deliver an element of the class.
                //
                Vector<Class> optTypes = new Vector<Class>(10, 10);
                Vector<Object> optValues = new Vector<Object>(10, 10);

                for (int i = 0; i <= sub.getMaxIndex("option"); i++) {
                    Object optValue = null;
                    String optVarName = sub.getString("option(" + i + ")[@varname]");
                    String optJavaType = sub.getString("option(" + i + ")[@javatype]");

                    // Use the specified java type in order to make the method call
                    // to the heirarchical sub object [painful :-((]
                    //
                    if (optJavaType.matches("byte")) {
                        optTypes.addElement(byte.class);
                        optValue = sub.getByte("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("short")) {
                        optTypes.addElement(byte.class);
                        optValue = sub.getShort("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("int")) {
                        optTypes.addElement(int.class);
                        optValue = sub.getInt("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("long")) {
                        optTypes.addElement(long.class);
                        optValue = sub.getLong("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("float")) {
                        optTypes.addElement(float.class);
                        optValue = sub.getFloat("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0.0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("double")) {
                        optTypes.addElement(double.class);
                        optValue = sub.getDouble("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0.0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("boolean")) {
                        optTypes.addElement(boolean.class);
                        optValue = sub.getBoolean("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = false; // Set to something nullish
                        }
                    } else if (optJavaType.matches("String")) {
                        optTypes.addElement(String.class);
                        optValue = sub.getString("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = ""; // Set it to something nullish
                        }
                    } else {
                        System.err.println(
                                "Error: Unsupported java type found in xml config: '" + optJavaType + "'");
                        System.exit(1);
                    }

                    // Add option value element
                    //
                    //              System.out.println("Option value is: '" + optValue.toString() + "'\n");
                    //
                    optValues.addElement(optValue);

                    // Append to message text
                    //
                    String msgTemp = msg.getText();
                    msgTemp += "\n      option name: '" + optVarName + "'";
                    msgTemp += "\n      option type: '" + optJavaType + "'";
                    msgTemp += "\n     option value: '" + optValues.lastElement().toString() + "'";
                    msg.setText(msgTemp);
                }

                try {
                    // Instantiate the class with the java reflection api
                    //
                    Class klass = Class.forName(className);

                    // Setup an array of paramater types in order to retrieve the matching constructor
                    //
                    Class[] types = optTypes.toArray(new Class[optTypes.size()]);

                    // Get the constructor for the class which matches the parameter types
                    //
                    Constructor konstruct = klass.getConstructor(types);

                    // Create an instance of the event handler
                    //
                    IEventHandler eventProcessor = (IEventHandler) konstruct.newInstance(optValues.toArray());

                    // Add the instance to the list of event handlers
                    //
                    eventHandler.addElement(eventProcessor);

                } catch (InvocationTargetException e) {
                    System.err.println("Error: " + e.toString());
                    System.exit(1);
                } catch (ClassNotFoundException e) {
                    System.err.println("Error: class name not found: '" + className + "' \n" + e.toString());
                    System.exit(1);
                } catch (Exception e) {
                    System.err.println(
                            "Error: failed to instantiate class: '" + className + "' \n" + e.toString());
                    System.exit(1);
                }
            }
        } catch (ConfigurationException cex) // Something went wrong loading the xml file
        {
            System.err.println("\n" + "Error loading XML file: " + cfgFileEngine + "\n" + cex.toString());
            System.exit(1);
        } catch (Exception e) {
            System.err.println(e.toString());
            System.exit(1);
        }

        // ---------------------------------------------------------------------
        // =====================================================================
        // Setup the TECAgent receiver 
        // 
        Reader cfgIn = null;

        try {
            cfgIn = new FileReader(cfgFileReceiver);
        } catch (Exception e) {
            System.err.println(e.toString());
            System.exit(1);
        }

        // Start the TECAgent receiver and register the event engine handler
        //
        TECAgent receiver = new TECAgent(cfgIn, TECAgent.RECEIVER_MODE, false);

        EventEngine ee = new EventEngine(eventHandler, msgLogger, trcLogger);

        receiver.registerListener(ee);

        // Construct message and send it to the message log
        //
        String text = "\n  Cresendo instance '" + instanceName + "' listening for events on port '"
                + receiver.getConfigVal("ServerPort") + "'";

        msg.setText(msg.getText() + text);
        msgLogger.log(msg); // Send message to log

        // ---------------------------------------------------------------------
        // =====================================================================
        // Initiate status logging
        //
        if (statLogger.isLogging()) {
            int seconds = statLogger.getInterval();

            while (true) {
                try {
                    statLogger.log();
                } catch (Exception ex) {
                    System.err.println("\n  An error occurred while writing to '" + statusPath + "'" + "\n  '"
                            + ex.toString() + "'");
                }

                Thread.sleep(seconds * 1000); // Convert sleep time to milliseconds
            }
        }

        // ---------------------------------------------------------------------
    } catch (Exception e) {
        System.err.println(e.toString());
        System.exit(1);
    }
}

From source file:com.github.jmabuin.blaspark.examples.options.GeneralOptions.java

public GeneralOptions(String[] args) {

    this.options = this.initOptions();

    //Parse the given arguments
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;//www . ja va2s  . c o  m

    try {
        cmd = parser.parse(this.options, args, true);

        //We look for the operation mode
        if (cmd.hasOption('h') || cmd.hasOption("help")) {
            //Case of showing the help
            this.mode = Mode.HELP;
        } else if (cmd.hasOption('d') || cmd.hasOption("dmxv")) {
            // Case of query
            this.mode = Mode.DMXV;
        } else if (cmd.hasOption('s') || cmd.hasOption("smxv")) {
            // Case of build
            this.mode = Mode.SMXV;
        } else if (cmd.hasOption('c') || cmd.hasOption("conjGrad")) {
            // Case of add
            this.mode = Mode.CG;
        } else if (cmd.hasOption('j') || cmd.hasOption("jacobi")) {
            this.mode = Mode.JACOBI;
        } else if (cmd.hasOption('m') || cmd.hasOption("dmxdm")) {
            this.mode = Mode.DMXDM;
        } else {
            // Default case. Help
            LOG.warn("[" + this.getClass().getName() + "] :: No operation mode selected. Using help.");
            this.mode = Mode.HELP;
        }

        if (cmd.hasOption('l') || cmd.hasOption("pairLine")) {
            this.matrixFormat = MatrixFormat.PAIRLINE;
        } else if (cmd.hasOption('o') || cmd.hasOption("coordinate")) {
            this.matrixFormat = MatrixFormat.COORDINATE;
        } else if (cmd.hasOption('b') || cmd.hasOption("blocked")) {
            this.matrixFormat = MatrixFormat.BLOCK;

            if (!cmd.hasOption("rows") || !cmd.hasOption("cols")) {
                LOG.error("[" + this.getClass().getName()
                        + "] :: The number of rows or cols has not been specified.");
                this.printHelp();
                System.exit(1);
            } else {
                this.colsPerBlock = Integer.parseInt(cmd.getOptionValue("cols"));
                this.rowsPerlBlock = Integer.parseInt(cmd.getOptionValue("rows"));
            }

        } else {
            this.matrixFormat = MatrixFormat.PAIRLINE;
        }

        if (cmd.hasOption('i') || cmd.hasOption("iteration")) {

            this.iterationNumber = Long.parseLong(cmd.getOptionValue("iteration"));
        }

        if (cmd.hasOption('p') || cmd.hasOption("partitions")) {
            this.numPartitions = Long.parseLong(cmd.getOptionValue("partitions"));

        }

        if (cmd.hasOption("alpha")) {
            this.alpha = Double.parseDouble(cmd.getOptionValue("alpha"));
        } else {
            this.alpha = 1.0;
        }

        if (cmd.hasOption("beta")) {
            this.beta = Double.parseDouble(cmd.getOptionValue("beta"));
        } else {
            this.beta = 0.0;
        }

        // Get and parse the rest of the arguments
        this.otherOptions = cmd.getArgs(); //With this we get the rest of the arguments

        if (this.otherOptions.length != 3) {
            LOG.error("Input and output parameters not specified.");
            this.printHelp();
            System.exit(1);
        } else {
            this.inputMatrixPath = this.otherOptions[0];
            this.inputVectorPath = this.otherOptions[1];
            this.outputVectorPath = this.otherOptions[2];
        }

    } catch (UnrecognizedOptionException e) {
        e.printStackTrace();
        //formatter.printHelp(correctUse, header, options, footer, true);

        System.exit(1);

    } catch (MissingOptionException e) {
        //formatter.printHelp(correctUse, header, options, footer, true);
        System.exit(1);
    } catch (ParseException e) {
        //formatter.printHelp( correctUse,header, options,footer , true);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:BwaOptions.java

/**
 * Constructor to use from within SparkBWA from the Linux console
 * @param args The arguments that the user is going to provide from the Linux console
 *///from w  w w .j a v a2  s  .  c  o m
public BwaOptions(String[] args) {

    //Parse arguments
    for (String argumento : args) {
        LOG.info("JMAbuin:: Received argument: " + argumento);
    }

    //Algorithm options
    Options options = this.initOptions();

    //To print the help
    HelpFormatter formatter = new HelpFormatter();
    //formatter.printHelp( correctUse,header, options,footer , true);

    //Parse the given arguments
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);

        //We look for the algorithm
        if (cmd.hasOption("algorithm")) {

            if (cmd.getOptionValue("algorithm").equals("mem")) {
                //Case of the mem algorithm
                memAlgorithm = true;
                alnAlgorithm = false;
                bwaswAlgorithm = false;
            }

            else if (cmd.getOptionValue("algorithm").equals("aln")) {
                // Case of aln algorithm
                alnAlgorithm = true;
                memAlgorithm = false;
                bwaswAlgorithm = false;
            }

            else if (cmd.getOptionValue("algorithm").equals("bwasw")) {
                // Case of bwasw algorithm
                bwaswAlgorithm = true;
                memAlgorithm = false;
                alnAlgorithm = false;
            }

            else {
                LOG.warn("The algorithm " + cmd.getOptionValue("algorithm")
                        + " could not be found\nSetting to default mem algorithm\n");
                memAlgorithm = true;
                alnAlgorithm = false;
                bwaswAlgorithm = false;

            }

        }

        //We look for the index
        if (cmd.hasOption("index")) {
            indexPath = cmd.getOptionValue("index");
        } else {
            LOG.error("No index has been found. Aborting.");
            formatter.printHelp(correctUse, header, options, footer, true);
            System.exit(1);
        }

        //Partition number
        if (cmd.hasOption("partitions")) {
            partitionNumber = Integer.parseInt(cmd.getOptionValue("partitions"));
        }

        if (cmd.hasOption("bwaArgs")) {
            bwaArgs = cmd.getOptionValue("bwaArgs");
        }

        //We look if we want the paired or single algorithm
        if (cmd.hasOption("reads")) {
            if (cmd.getOptionValue("reads").equals("single")) {
                pairedReads = false;
                singleReads = true;
            }

            else if (cmd.getOptionValue("reads").equals("paired")) {
                pairedReads = true;
                singleReads = false;
            }

            else {
                LOG.warn("Reads argument could not be found\nSetting it to default paired reads\n");
                pairedReads = true;
                singleReads = false;
            }
        }

        //We look if the user wants to use a reducer or not
        if (cmd.hasOption("r")) {
            useReducer = true;
        } else {
            useReducer = false;
        }

        //Sorting input reads
        if (cmd.hasOption("sorting")) {
            if (cmd.getOptionValue("sorting").equals("hdfs")) {
                this.sortFastqReadsHdfs = true;
                this.sortFastqReads = false;
            } else if (cmd.getOptionValue("sorting").equals("spark")) {
                this.sortFastqReadsHdfs = false;
                this.sortFastqReads = true;
            }
        }

        //Input and output paths
        String otherArguments[] = cmd.getArgs(); //With this we get the rest of the arguments

        if ((otherArguments.length != 2) && (otherArguments.length != 3)) {
            LOG.error("No input and output has been found. Aborting.");

            for (String tmpString : otherArguments) {
                LOG.error("Other args:: " + tmpString);
            }

            formatter.printHelp(correctUse, header, options, footer, true);
            System.exit(1);
        }

        else if (otherArguments.length == 2) {
            inputPath = otherArguments[0];
            outputPath = otherArguments[1];
        } else if (otherArguments.length == 3) {
            inputPath = otherArguments[0];
            inputPath2 = otherArguments[1];
            outputPath = otherArguments[2];
        }

    } catch (UnrecognizedOptionException e) {
        e.printStackTrace();
        formatter.printHelp(correctUse, header, options, footer, true);
        System.exit(1);

    } catch (ParseException e) {
        //formatter.printHelp( correctUse,header, options,footer , true);
        e.printStackTrace();
        System.exit(1);
    }

}

From source file:net.timbusproject.extractors.debiansoftwareextractor.CLI.java

public void parse(String... args) throws ParseException {
    try {//from   w  ww .  j  a v a  2 s .  c o m
        cmd = new PosixParser().parse(options, args);
    } catch (UnrecognizedOptionException e) {
        log.error(e.getLocalizedMessage());
        throw e;
    } catch (MissingOptionException e) {
        log.error(e.getLocalizedMessage());
        throw e;
    } catch (MissingArgumentException e) {
        log.error(e.getLocalizedMessage());
        throw e;
    } catch (AlreadySelectedException e) {
        log.error(e.getLocalizedMessage());
        throw e;
    } catch (ParseException e) {
        log.error(e.getLocalizedMessage());
        e.printStackTrace();
        throw e;
    }
}

From source file:org.apache.nutch.indexer.filter.MimeTypeIndexingFilter.java

/**
 * Main method for invoking this tool/*from  w  w w  .  j a v a  2 s . com*/
 *
 * @throws IOException
 * @throws IndexingException
 */
public static void main(String[] args) throws IOException, IndexingException {
    Option helpOpt = new Option("h", "help", false, "show this help message");
    Option rulesOpt = OptionBuilder.withArgName("file").hasArg()
            .withDescription("Rules file to be used in the tests relative to the conf directory").isRequired()
            .create("rules");

    Options options = new Options();
    options.addOption(helpOpt).addOption(rulesOpt);

    CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    String rulesFile;

    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help") || !line.hasOption("rules")) {
            formatter.printHelp("org.apache.nutch.indexer.filter.MimeTypeIndexingFilter", options, true);
            return;
        }

        rulesFile = line.getOptionValue("rules");
    } catch (UnrecognizedOptionException e) {
        formatter.printHelp("org.apache.nutch.indexer.filter.MimeTypeIndexingFilter", options, true);
        return;
    } catch (Exception e) {
        LOG.error(StringUtils.stringifyException(e));
        e.printStackTrace();
        return;
    }

    MimeTypeIndexingFilter filter = new MimeTypeIndexingFilter();
    Configuration conf = NutchConfiguration.create();
    conf.set(MimeTypeIndexingFilter.MIMEFILTER_REGEX_FILE, rulesFile);
    filter.setConf(conf);

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line;

    while ((line = in.readLine()) != null && !line.isEmpty()) {
        Metadata metadata = new Metadata();
        metadata.set(Response.CONTENT_TYPE, line);
        ParseImpl parse = new ParseImpl("text",
                new ParseData(new ParseStatus(), "title", new Outlink[0], metadata));

        NutchDocument doc = filter.filter(new NutchDocument(), parse, new Text("http://www.example.com/"),
                new CrawlDatum(), new Inlinks());

        if (doc != null) {
            System.out.print("+ ");
            System.out.println(line);
        } else {
            System.out.print("- ");
            System.out.println(line);
        }
    }
}

From source file:org.ihtsdo.otf.snomed.loader.GraphLoader.java

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

    DefaultParser p = new DefaultParser();

    CommandLine cli = null;/*w w w. j a va  2s  .  c  om*/
    try {

        cli = p.parse(DefaultParser.options, args);

    } catch (UnrecognizedOptionException e) {

        System.out.println(USAGE);
    }

    String dbConfig = cli.getOptionValue("config");

    validate(dbConfig, "Titan db configuration is required to initialize database");

    String type = cli.getOptionValue("type");
    validateType(type, "Data load type is required. Specify either SNAPSHOT or FULL or RDF or DELTA");

    //validate file format and type

    //validateFiles(cli, "No data file specified");

    TitanGraph g = null;
    try {

        g = openGraph(dbConfig);

        if (g == null) {

            throw new IllegalArgumentException("Could not get graph instance");
        }

        switch (LoadType.valueOf(type)) {

        case full:
            Rf2FullFeedLoader fLoader = new Rf2FullFeedLoader(g);
            if (!StringUtils.isBlank(cli.getOptionValue("bSize"))) {

                fLoader.setBufferSize(Integer.parseInt(cli.getOptionValue("bSize")));

            }

            FileType[] ffTypes = FileType.values();

            for (int i = 0; i < ffTypes.length; i++) {

                if (!ffTypes[i].equals(FileType.nt)) {

                    FileType fType = ffTypes[i];
                    LOGGER.info("Loading file type {}", fType.toString());
                    String file = cli.getOptionValue(fType.toString());
                    LOGGER.info("Loading file  {}", file);

                    if (!StringUtils.isBlank(file)) {

                        fLoader.load(file);

                    }

                }
            }

            break;

        case snapshot:
            Rf2SnapshotLoader loader = new Rf2SnapshotLoader(g);
            if (!StringUtils.isBlank(cli.getOptionValue("bSize"))) {

                loader.setBufferSize(Integer.parseInt(cli.getOptionValue("bSize")));

            }
            if (!StringUtils.isBlank(cli.getOptionValue("reload"))) {

                loader.setReload(Boolean.parseBoolean(cli.getOptionValue("reload")));

            }

            FileType[] fTypes = FileType.values();

            for (int i = 0; i < fTypes.length; i++) {

                if (!fTypes[i].equals(FileType.nt)) {

                    FileType fType = fTypes[i];
                    LOGGER.info("Loading file type {}", fType.toString());
                    String file = cli.getOptionValue(fType.toString());
                    LOGGER.info("Loading file  {}", file);

                    if (!StringUtils.isBlank(file)) {

                        loader.load(file);

                    }

                }
            }

            break;

        case audit:
            Rf2SnapshotAuditor auditor = new Rf2SnapshotAuditor(g);
            if (!StringUtils.isBlank(cli.getOptionValue("bSize"))) {

                auditor.setBufferSize(Integer.parseInt(cli.getOptionValue("bSize")));

            }

            if (!StringUtils.isBlank(cli.getOptionValue("reload"))) {

                auditor.setReload(Boolean.parseBoolean(cli.getOptionValue("reload")));

            }

            FileType[] afTypes = FileType.values();

            for (int i = 0; i < afTypes.length; i++) {

                if (!afTypes[i].equals(FileType.nt)) {

                    FileType fType = afTypes[i];
                    LOGGER.info("Auditing file type {}", fType.toString());
                    String file = cli.getOptionValue(fType.toString());
                    LOGGER.info("Auditing file  {}", file);

                    if (!StringUtils.isBlank(file)) {

                        auditor.setSubType(cli.getOptionValue("subType"));
                        auditor.audit(file);

                    }

                }
            }

            break;

        default:
            LOGGER.info("Nothing to load");
            break;
        }

        LOGGER.info("Finished loading");

    } catch (Exception e) {

        e.printStackTrace();

    } finally {

        if (g != null) {

            g.shutdown();

        }
    }

}

From source file:org.kawanfw.sql.WebServer.java

/**
 * Starts or stops the AceQL Web Server.
 * //from   w w w.  ja  va2s .  c  om
 * @param args   the arguments of Web Server start/stop.
 * 
 * @throws ParseException      if any Exception when parsing command line
 * @throws IOException      if any I/O Exception
 * @throws ConnectException      if server is unable to connect to specified or default 9090 port
 * @throws SqlConfigurationException if any error in configuration properties file
 */
public static void main(String[] args)
        throws ParseException, IOException, ConnectException, SqlConfigurationException {

    if (args.length > 0) {
        debug("args[0]: " + args[0] + ":");
    }

    if (args.length > 1) {
        debug("args[1]: " + args[1] + ":");
    }

    Options options = createOptions();
    CommandLineParser parser = new GnuParser();

    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (UnrecognizedOptionException e) {
        System.out.println(e.getMessage());
        System.out.println();
        printUsage(options);
        System.exit(-1);
    }

    if (cmd.hasOption("help")) {
        printUsage(options);
        System.exit(-1);
    }

    if (cmd.hasOption("version")) {
        System.out.println(Version.getServerVersion());
        System.out.println();
        System.exit(-1);
    }

    if (!cmd.hasOption("start") && !cmd.hasOption("stop")) {
        System.err.println("Missing start or stop option." + " " + SqlTag.PLEASE_CORRECT);
        System.out.println();
        printUsage(options);
        System.exit(-1);
    }

    int port = WebServerApi.DEFAULT_PORT;

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

        try {
            port = Integer.parseInt(portStr);
        } catch (Exception e) {
            displayErrorAndExit("The port parameter is not numeric: " + portStr + ".", options);
        }
    }

    if (cmd.hasOption("start")) {

        if (!cmd.hasOption("host")) {
            displayErrorAndExit("Missing host option.", options);
        }

        String host = cmd.getOptionValue("host");

        File propertiesFile = null;

        if (!cmd.hasOption("properties")) {

            String aceqlHome = System.getenv("ACEQL_HOME");

            if (aceqlHome != null) {

                // Remove surrounding " if present
                aceqlHome = aceqlHome.replaceAll("\"", "");

                if (aceqlHome.endsWith(File.separator)) {
                    aceqlHome = StringUtils.substringBeforeLast(aceqlHome, File.separator);
                }
                propertiesFile = new File(
                        aceqlHome + File.separator + "conf" + File.separator + "aceql-server.properties");
            } else {
                displayErrorAndExit("Missing properties option.", options);
            }

        } else {
            propertiesFile = new File(cmd.getOptionValue("properties"));
        }

        WebServerApi webServerApi = new WebServerApi();
        try {
            webServerApi.startServer(host, port, propertiesFile);
        } catch (SqlConfigurationException e) {
            System.err.println(SqlTag.SQL_PRODUCT_START_FAILURE + " " + SqlTag.USER_CONFIGURATION_FAILURE + " "
                    + e.getMessage());
            System.err.println();
            System.exit((-1));
        }

        catch (ConnectException e) {
            System.err.println(SqlTag.SQL_PRODUCT_START_FAILURE + " " + e.getMessage());
            System.err.println();
            System.exit((-1));
        }

        catch (IOException e) {

            if (e instanceof UnknownHostException) {
                System.err.println(SqlTag.SQL_PRODUCT_START_FAILURE + " " + "Unknow host: " + e.getMessage());
            } else {
                System.err.println(SqlTag.SQL_PRODUCT_START_FAILURE + " " + e.getMessage());
            }

            if (e.getCause() != null) {
                e.printStackTrace();
            }

            System.err.println();
            System.exit(-1);
        } catch (Exception e) {
            System.err.println(SqlTag.SQL_PRODUCT_START_FAILURE);
            e.printStackTrace();
            System.err.println();
            System.exit(-1);
        }

    } else {

        WebServerApi webServerApi = new WebServerApi();
        try {
            webServerApi.stopServer(port);

            System.out.println("SQL Web server running on port " + port + " successfully stopped!");
            System.out.println();
            System.exit(-1);
        } catch (IOException e) {

            if (e instanceof ConnectException) {
                System.err.println(e.getMessage());
            } else {
                System.err.println("Impossible to stop the SQL Web server running on port " + port);
                System.err.println(e.getMessage());

                if (e.getCause() != null) {
                    System.err.println("Java Exception Stack Trace:");
                    e.printStackTrace();
                }

            }

            System.err.println();
            System.exit(-1);
        }
    }

}