Example usage for org.apache.commons.cli HelpFormatter printHelp

List of usage examples for org.apache.commons.cli HelpFormatter printHelp

Introduction

In this page you can find the example usage for org.apache.commons.cli HelpFormatter printHelp.

Prototype

public void printHelp(String cmdLineSyntax, Options options, boolean autoUsage) 

Source Link

Document

Print the help for options with the specified command line syntax.

Usage

From source file:com.asakusafw.compiler.bootstrap.OperatorCompilerDriver.java

/**
 * // w ww.j  av  a  2 s  .c  o  m
 * @param args 
 */
public static void main(String... args) {
    try {
        start(args);
    } catch (Exception e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(Integer.MAX_VALUE);
        formatter.printHelp(MessageFormat.format("java -classpath ... {0}", //$NON-NLS-1$
                OperatorCompilerDriver.class.getName()), OPTIONS, true);
        e.printStackTrace(System.out);
        System.exit(1);
    }
}

From source file:at.newmedialab.ldpath.backend.linkeddata.LDQuery.java

public static void main(String[] args) {
    Options options = buildOptions();//  w w  w. ja v a  2  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:fr.inria.atlanmod.kyanos.benchmarks.KyanosGraphCreator.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);/*w  w  w .  j  a  v a  2s.  co m*/
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output directory");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);
    options.addOption(optFileOpt);

    CommandLineParser parser = new PosixParser();

    try {

        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(OUT)));

        Class<?> inClazz = KyanosGraphCreator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        Resource sourceResource = resourceSet.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);
        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        Resource targetResource = resourceSet.createResource(targetUri);

        Map<String, Object> saveOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                saveOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        storeOptions.add(BlueprintsResourceOptions.EStoreGraphOption.AUTOCOMMIT);
        saveOpts.put(BlueprintsResourceOptions.STORE_OPTIONS, storeOptions);
        targetResource.save(saveOpts);

        LOG.log(Level.INFO, "Start moving elements");
        targetResource.getContents().clear();
        targetResource.getContents().addAll(sourceResource.getContents());
        LOG.log(Level.INFO, "End moving elements");
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saved");

        if (targetResource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) targetResource);
        } else {
            targetResource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:eu.scape_project.pc.tika.cli.TifowaCli.java

public static void main(String[] args) {
    // Static for command line option parsing
    TifowaCli tc = new TifowaCli();
    detector = new DefaultDetector();
    CommandLineParser cmdParser = new PosixParser();
    try {/* ww  w.ja va2s  .  c  om*/
        CommandLine cmd = cmdParser.parse(OPTIONS, args);
        if ((args.length == 0) || (cmd.hasOption(HELP_OPT))) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(Constants.USAGE, OPTIONS, true);
            System.exit(0);
        } else {
            if (cmd.hasOption(DIR_OPT) && cmd.getOptionValue(DIR_OPT) != null) {
                String dirStr = cmd.getOptionValue(DIR_OPT);
                logger.info("Directory: " + dirStr);

                // *** start timer
                long startClock = System.currentTimeMillis();

                tc.processFiles(new File(dirStr));

                // *** stop timer
                long elapsedTimeMillis = System.currentTimeMillis() - startClock;

                //  *** display the TYPE collection
                displayMyTypes(myCollection, countAllCalls, countAllGoodItems, countAllFailedItems,
                        elapsedTimeMillis);

            } else {
                logger.error("No directory given.");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp(Constants.USAGE, OPTIONS, true);
                System.exit(1);
            }
        }
    } catch (ParseException ex) {
        logger.error("Problem parsing command line arguments.", ex);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Constants.USAGE, OPTIONS, true);
        System.exit(1);
    }
}

From source file:fr.inria.atlanmod.emf.graphs.Connectedness.java

public static void main(String[] args) {

    Options options = createOptions();/* w  w w.j a  va 2 s  . co m*/

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        String inputMetamodel = commandLine.getOptionValue(INPUT_METAMODEL);
        String inputModel = commandLine.getOptionValue(INPUT_MODEL);
        Boolean logUnreachable = commandLine.hasOption(LOG_UNREACHABLE);

        ResourceSet resourceSet = new ResourceSetImpl();
        Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());

        {
            LOG.log(Level.INFO, "Loading input metamodel");
            URI uri = URI.createFileURI(inputMetamodel);
            Resource resource = resourceSet.getResource(uri, true);
            registerEPackages(resource);
        }

        URI uri = URI.createFileURI(inputModel);

        LOG.log(Level.INFO, "Loading input model");
        Resource resource = resourceSet.getResource(uri, true);

        LOG.log(Level.INFO, "Getting input model contents");
        Set<EObject> resourceContents = getResourceContents(resource);
        int totalCount = resourceContents.size();

        LOG.log(Level.INFO, MessageFormat.format("Input model contains {0} elements", totalCount));

        List<EClassifier> candidateEClassifiers = buildCandidateEClassifiers();

        for (Iterator<EObject> it = resource.getAllContents(); it.hasNext();) {
            EObject eObject = it.next();
            if (candidateEClassifiers.contains(eObject.eClass())) {
                Set<EObject> reachableEObjects = getReachableEObjects(eObject);
                int i = reachableEObjects.size();
                LOG.log(Level.INFO, MessageFormat.format("Found {0} reachable objects from {1} (EClass {2})", i,
                        EcoreUtil.getURI(eObject), eObject.eClass().getName()));
                if (logUnreachable) {
                    Set<EObject> unreachableEObjects = new HashSet<>(resourceContents);
                    unreachableEObjects.removeAll(reachableEObjects);
                    LOG.log(Level.INFO,
                            MessageFormat.format("{0} elements are unreachable from {1} (EClass {2})",
                                    unreachableEObjects.size(), EcoreUtil.getURI(eObject),
                                    eObject.eClass().getName()));
                    for (EObject unreachableEObject : unreachableEObjects) {
                        LOG.log(Level.INFO, MessageFormat.format("Unreachable EObject {0} is of type {1}",
                                EcoreUtil.getURI(unreachableEObject), unreachableEObject.eClass()));
                    }
                }
            }
        }

    } catch (ParseException e) {
        LOG.log(Level.SEVERE, e.getLocalizedMessage(), e);
        LOG.log(Level.INFO, "Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        LOG.log(Level.SEVERE, e.getLocalizedMessage(), e);
        MessageUtil.showError(e.toString());
    }
}

From source file:net.sf.mpaxs.test.ImpaxsExecution.java

/**
 *
 * @param args/*from   w  ww.  jav a2s .com*/
 */
public static void main(String[] args) {
    Options options = new Options();
    Option[] optionArray = new Option[] {
            OptionBuilder.withArgName("nhosts").hasArg()
                    .withDescription("Number of hosts for parallel processing").create("n"),
            OptionBuilder.withArgName("mjobs").hasArg().withDescription("Number of jobs to run in parallel")
                    .create("m"),
            OptionBuilder.withArgName("runmode").hasArg()
                    .withDescription("The mode in which to operate: one of <ALL,LOCAL,DISTRIBUTED>")
                    .create("r"), //            OptionBuilder.withArgName("gui").
            //            withDescription("Create gui for distributed execution").create("g")
    };
    for (Option opt : optionArray) {
        options.addOption(opt);
    }
    if (args.length == 0) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }
    GnuParser gp = new GnuParser();
    int nhosts = 1;
    int mjobs = 10;
    boolean gui = false;
    Mode mode = Mode.ALL;
    try {
        CommandLine cl = gp.parse(options, args);
        if (cl.hasOption("n")) {
            nhosts = Integer.parseInt(cl.getOptionValue("n"));
        }
        if (cl.hasOption("m")) {
            mjobs = Integer.parseInt(cl.getOptionValue("m"));
        }
        if (cl.hasOption("r")) {
            mode = Mode.valueOf(cl.getOptionValue("r"));
        }
        //            if (cl.hasOption("g")) {
        //                gui = true;
        //            }
    } catch (Exception ex) {
        Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }

    String version;
    try {
        version = net.sf.mpaxs.api.Version.getVersion();
        System.out.println("Running mpaxs " + version);
        File computeHostJarLocation = new File(System.getProperty("user.dir"), "mpaxs.jar");
        if (!computeHostJarLocation.exists() || !computeHostJarLocation.isFile()) {
            throw new IOException("Could not locate mpaxs.jar in " + System.getProperty("user.dir"));
        }
        final PropertiesConfiguration cfg = new PropertiesConfiguration();
        //set default execution type
        cfg.setProperty(ConfigurationKeys.KEY_EXECUTION_MODE, ExecutionType.DRMAA);
        //set location of compute host jar
        cfg.setProperty(ConfigurationKeys.KEY_PATH_TO_COMPUTEHOST_JAR, computeHostJarLocation);
        //do not exit to console when master server shuts down
        cfg.setProperty(ConfigurationKeys.KEY_MASTER_SERVER_EXIT_ON_SHUTDOWN, false);
        //limit the number of used compute hosts
        cfg.setProperty(ConfigurationKeys.KEY_MAX_NUMBER_OF_CHOSTS, nhosts);
        cfg.setProperty(ConfigurationKeys.KEY_NATIVE_SPEC, "");
        cfg.setProperty(ConfigurationKeys.KEY_GUI_MODE, gui);
        cfg.setProperty(ConfigurationKeys.KEY_SILENT_MODE, true);
        cfg.setProperty(ConfigurationKeys.KEY_SCHEDULE_WAIT_TIME, "500");
        final int maxJobs = mjobs;
        final int maxThreads = nhosts;
        final Mode runMode = mode;
        printMessage("Run mode: " + runMode);
        Executors.newSingleThreadExecutor().submit(new Runnable() {
            @Override
            public void run() {
                if (runMode == Mode.ALL || runMode == Mode.LOCAL) {
                    printMessage("Running Within VM Execution");
                    /*
                     * LOCAL within VM execution
                     */
                    WithinVmExecution lhe = new WithinVmExecution(maxJobs, maxThreads);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + lhe.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                if (runMode == Mode.ALL || runMode == Mode.DISTRIBUTED) {
                    printMessage("Running Distributed Host RMI Execution");
                    /*
                     * Grid Engine (DRMAA API) or local host distributed RMI execution
                     */
                    DistributedRmiExecution de = new DistributedRmiExecution(cfg, maxJobs);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + de.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                System.exit(0);
            }
        });
    } catch (IOException ex) {
        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:di.uniba.it.tee2.gui.TEEgui.java

/**
 * @param args the command line arguments
 *///from  w  ww  .j av a2 s  . c om
public static void main(String args[]) {

    try {
        CommandLine cmd = cmdParser.parse(options, args);
        if (cmd.hasOption("l") && cmd.hasOption("d")) {
            language = cmd.getOptionValue("l");
            maindir = cmd.getOptionValue("d");
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
                 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
                 */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
                        .getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(TEEgui.class.getName()).log(java.util.logging.Level.SEVERE,
                        null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(TEEgui.class.getName()).log(java.util.logging.Level.SEVERE,
                        null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(TEEgui.class.getName()).log(java.util.logging.Level.SEVERE,
                        null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(TEEgui.class.getName()).log(java.util.logging.Level.SEVERE,
                        null, ex);
            }
            //</editor-fold>

            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        new TEEgui().setVisible(true);
                    } catch (IOException ex) {
                        Logger.getLogger(TEEgui.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
        } else {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Run GUI", options, true);
        }
    } catch (ParseException ex) {
        Logger.getLogger(TEEgui.class.getName()).log(Level.SEVERE, null, ex);
    }
    //</editor-fold>
}

From source file:eu.impact_project.iif.tw.cli.ToolWrapper.java

/**
 * Main method of the command line application
 *
 * @param args/*from   w w  w.j ava2s.  c  o  m*/
 *        Arguments of the command line application
 * @throws GeneratorException
 *         Exception if project generation fails
 */
public static void main(String[] args) throws GeneratorException {

    CommandLineParser cmdParser = new PosixParser();
    try {
        // Parse the command line arguments
        CommandLine cmd = cmdParser.parse(OPTIONS, args);
        // If no args or help selected
        if ((args.length == 0) || (cmd.hasOption(HELP_OPT))) {
            // OK help needed
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(Constants.PROJECT_NAME, OPTIONS, true);

            if (args.length == 0)
                logger.info("Reading default configuration files from working " + "directory ...");
            else
                System.exit(0);
        }

        String toolspecPath = cmd.getOptionValue(TOOLSPEC_OPT, Constants.DEFAULT_TOOLSPEC);
        File toolspecFile = new File(toolspecPath);
        String propertiesPath = cmd.getOptionValue(PROPERTIES_OPT, Constants.DEFAULT_PROJECT_PROPERTIES);
        File propertiesFile = new File(propertiesPath);
        ioc.setXmlConf(toolspecFile);
        ioc.setProjConf(propertiesFile);

    } catch (ParseException excep) {
        // Problem parsing the command line args, just print the message and help
        logger.error("Problem parsing command line arguments.", excep);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Constants.PROJECT_NAME, OPTIONS, true);
        System.exit(1);
    }

    if (!ioc.hasConfig()) {
        throw new GeneratorException("No configuration available.");
    }
    JAXBContext context;
    try {
        context = JAXBContext.newInstance("eu.impact_project.iif.tw.toolspec");
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Toolspec toolspec = (Toolspec) unmarshaller.unmarshal(new File(ioc.getXmlConf()));
        // general tool specification properties
        logger.info("Toolspec model: " + toolspec.getModel());
        logger.info("Tool id: " + toolspec.getId());
        logger.info("Tool name: " + toolspec.getName());
        logger.info("Tool version: " + toolspec.getVersion());

        // List of services for the tool
        List<Service> services = toolspec.getServices().getService();
        // For each service a different maven project will be generated
        for (Service service : services) {
            createService(service, toolspec.getVersion());
        }
    } catch (IOException ex) {
        logger.error("An IOException occurred", ex);
    } catch (JAXBException ex) {
        logger.error("JAXBException", ex);
        throw new GeneratorException("Unable to create XML binding for toolspec");
    }
}

From source file:di.uniba.it.tee2.shell.TEEShell.java

/**
 * language maindir encoding//from   ww  w. java 2  s.  co  m
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    try {
        CommandLine cmd = cmdParser.parse(options, args);
        if (cmd.hasOption("l") && cmd.hasOption("d")) {
            TEEShell shell = new TEEShell(cmd.getOptionValue("l"), cmd.getOptionValue("d"),
                    cmd.getOptionValue("e", DEFAULT_CHARSET));
            shell.promptLoop();
        } else {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Run TEE2 shell", options, true);
        }
    } catch (ParseException | IOException ex) {
        Logger.getLogger(TEEShell.class.getName()).log(Level.SEVERE, "General error", ex);
    }
}

From source file:ch.epfl.leb.sass.commandline.CommandLineInterface.java

/**
 * Shows help, launches the interpreter and executes scripts according to input args.
 * @param args input arguments//from   w ww  . jav  a  2  s  .  c o  m
 */
public static void main(String args[]) {
    // parse input arguments
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println("Parsing of arguments failed. Reason: " + ex.getMessage());
        System.err.println("Use -help for usage.");
        System.exit(1);
    }

    // decide how do we make the interpreter available based on options
    Interpreter interpreter = null;
    // show help and exit
    if (line.hasOption("help")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar <jar-name>", options, true);
        System.exit(0);
        // launch interpreter inside current terminal
    } else if (line.hasOption("interpreter")) {
        // assign in, out and err streams to the interpreter
        interpreter = new Interpreter(new InputStreamReader(System.in), System.out, System.err, true);
        interpreter.setShowResults(true);
        // if a script was given, execute it before giving access to user
        if (line.hasOption("script")) {
            try {
                interpreter.source(line.getOptionValue("script"));
            } catch (IOException ex) {
                Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE,
                        "IOException while executing shell script.", ex);
            } catch (EvalError ex) {
                Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE,
                        "EvalError while executing shell script.", ex);
            }
        }
        // give access to user
        new Thread(interpreter).start();
        // only execute script and exit
    } else if (line.hasOption("script")) {
        interpreter = new Interpreter();
        try {
            interpreter.source(line.getOptionValue("script"));
            System.exit(0);
        } catch (IOException ex) {
            Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE,
                    "IOException while executing shell script.", ex);
            System.exit(1);
        } catch (EvalError ex) {
            Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE,
                    "EvalError while executing shell script.", ex);
            System.exit(1);
        }

        // Launches the RPC server with the model contained in the file whose
        // filename was passed by argument.
    } else if (line.hasOption("rpc_server")) {

        IJPluginModel model = new IJPluginModel();
        File file = new File(line.getOptionValue("rpc_server"));
        try {
            FileInputStream stream = new FileInputStream(file);
            model = IJPluginModel.read(stream);
        } catch (FileNotFoundException ex) {
            System.out.println("Error: " + file.getName() + " not found.");
            System.exit(1);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // Check whether a port number was specified.
        if (line.hasOption("port")) {
            try {
                port = Integer.valueOf(line.getOptionValue("port"));
                System.out.println("Using port: " + String.valueOf(port));
            } catch (java.lang.NumberFormatException ex) {
                System.out.println("Error: the port number argument is not a number.");
                System.exit(1);
            }
        } else {
            System.out.println("No port number provided. Using default port: " + String.valueOf(port));
        }

        RPCServer server = new RPCServer(model, port);

        System.out.println("Starting RPC server...");
        server.serve();

    } else if (line.hasOption("port") & !line.hasOption("rpc_server")) {
        System.out.println("Error: Port number provided without requesting the RPC server. Exiting...");
        System.exit(1);

        // if System.console() returns null, it means we were launched by
        // double-clicking the .jar, so launch own BeanShellConsole
        // if System.console() returns null, it means we were launched by
        // double-clicking the .jar, so launch own ConsoleFrame
    } else if (System.console() == null) {
        BeanShellConsole cframe = new BeanShellConsole("SASS BeanShell Prompt");
        interpreter = cframe.getInterpreter();
        cframe.setVisible(true);
        System.setOut(cframe.getInterpreter().getOut());
        System.setErr(cframe.getInterpreter().getErr());
        new Thread(cframe.getInterpreter()).start();
        // otherwise, show help
    } else {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar <jar-name>", options, true);
        System.exit(0);
    }

    if (interpreter != null) {
        printWelcomeText(interpreter.getOut());
    }
}