Example usage for org.apache.commons.cli ParseException getLocalizedMessage

List of usage examples for org.apache.commons.cli ParseException getLocalizedMessage

Introduction

In this page you can find the example usage for org.apache.commons.cli ParseException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:net.forkwait.imageautomator.ImageAutomator.java

public static void main(String[] args) throws IOException {
    String inputImage = "";

    Options options = new Options();
    options.addOption("o", true, "output file name (e.g. thumb.jpg), default thumbnail.filename.ext");
    options.addOption("q", true, "jpeg quality (e.g. 0.9, max 1.0), default 0.97");
    options.addOption("s", true, "output max side length in px (e.g. 800), default 1200");
    options.addOption("w", true, "watermark image file");
    options.addOption("wt", true, "watermark transparency (e.g. 0.5, max 1.0), default 1.0");
    options.addOption("wp", true, "watermark position (e.g. 0.9, max 1.0), default BOTTOM_RIGHT");

    /*/*from  w w w  . j a v a2  s  .  co  m*/
    TOP_LEFT
    TOP_CENTER
    TOP_RIGHT
    CENTER_LEFT
    CENTER
    CENTER_RIGHT
    BOTTOM_LEFT
    BOTTOM_CENTER
    BOTTOM_RIGHT
     */

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
        if (cmd.getArgs().length < 1) {
            throw new ParseException("Too few arguments");
        } else if (cmd.getArgs().length > 1) {
            throw new ParseException("Too many arguments");
        }
        inputImage = cmd.getArgs()[0];
    } catch (ParseException e) {
        showHelp(options, e.getLocalizedMessage());
        System.exit(-1);
    }

    Thumbnails.Builder<File> st = Thumbnails.of(inputImage);

    if (cmd.hasOption("q")) {
        st.outputQuality(Double.parseDouble(cmd.getOptionValue("q")));
    } else {
        st.outputQuality(0.97f);
    }

    if (cmd.hasOption("s")) {
        st.size(Integer.parseInt(cmd.getOptionValue("s")), Integer.parseInt(cmd.getOptionValue("s")));
    } else {
        st.size(1200, 1200);
    }
    if (cmd.hasOption("w")) {
        Positions position = Positions.BOTTOM_RIGHT;
        float trans = 0.5f;
        if (cmd.hasOption("wp")) {
            position = Positions.valueOf(cmd.getOptionValue("wp"));
        }
        if (cmd.hasOption("wt")) {
            trans = Float.parseFloat(cmd.getOptionValue("wt"));
        }

        st.watermark(position, ImageIO.read(new File(cmd.getOptionValue("w"))), trans);
    }
    if (cmd.hasOption("o")) {
        st.toFile(new File(cmd.getOptionValue("o")));
    } else {
        st.toFiles(Rename.PREFIX_DOT_THUMBNAIL);
    }

    //.outputFormat("jpg")
    System.exit(0);
}

From source file:edu.cmu.tetrad.cli.data.sim.DiscreteTabularData.java

/**
 * @param args the command line arguments
 *///w  ww .  ja  v  a  2 s  .  c o  m
public static void main(String[] args) {
    if (args == null || args.length == 0 || Args.hasLongOption(args, "help")) {
        Args.showHelp("simulate-discrete-data", MAIN_OPTIONS);
        return;
    }

    try {
        CommandLineParser cmdParser = new DefaultParser();
        CommandLine cmd = cmdParser.parse(MAIN_OPTIONS, args);

        numOfVars = Args.getIntegerMin(cmd.getOptionValue("variable"), 0);
        numOfCases = Args.getIntegerMin(cmd.getOptionValue("case"), 0);
        edgeFactor = Args.getDoubleMin(cmd.getOptionValue("edge"), 1.0);
    } catch (ParseException exception) {
        System.err.println(exception.getLocalizedMessage());
        Args.showHelp("simulate-discrete-data", MAIN_OPTIONS);
        System.exit(-127);
    }

    List<Node> vars = new ArrayList<>();
    for (int i = 0; i < numOfVars; i++) {
        vars.add(new ContinuousVariable("X" + i));
    }
    Graph graph = GraphUtils.randomGraphRandomForwardEdges(vars, 0, (int) (numOfVars * edgeFactor), 30, 12, 15,
            false, true);
    BayesPm pm = new BayesPm(graph, 3, 3);
    BayesIm im = new MlBayesIm(pm, MlBayesIm.RANDOM);
    DataSet data = im.simulateData(numOfCases, false);

    String[] variables = data.getVariableNames().toArray(new String[0]);
    int lastIndex = variables.length - 1;
    for (int i = 0; i < lastIndex; i++) {
        System.out.printf("%s,", variables[i]);
    }
    System.out.printf("%s%n", variables[lastIndex]);

    DataBox dataBox = ((BoxDataSet) data).getDataBox();
    VerticalIntDataBox box = (VerticalIntDataBox) dataBox;
    //        int[][] matrix = box.getVariableVectors();
    //        int numOfColumns = matrix.length;
    //        int numOfRows = matrix[0].length;
    //        int[][] dataset = new int[numOfRows][numOfColumns];
    //        for (int i = 0; i < matrix.length; i++) {
    //            for (int j = 0; j < matrix[i].length; j++) {
    //                dataset[j][i] = matrix[i][j];
    //            }
    //        }
    //        for (int[] rowData : dataset) {
    //            lastIndex = rowData.length - 1;
    //            for (int i = 0; i < lastIndex; i++) {
    //                System.out.printf("%d,", rowData[i]);
    //            }
    //            System.out.printf("%s%n", rowData[lastIndex]);
    //        }
}

From source file:de.dominicscheurer.passwords.Main.java

/**
 * @param args//w ww . j  a v a2s. c  om
 *            Command line arguments (see code or output of program when
 *            started with no arguments).
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();

    Option seedPwdOpt = OptionBuilder.withArgName("Seed Password").isRequired().hasArg()
            .withDescription("Password used as a seed").withLongOpt("seed-password").create("s");

    Option serviceIdOpt = OptionBuilder.withArgName("Service Identifier").isRequired().hasArg()
            .withDescription("The service that the password is created for, e.g. facebook.com")
            .withLongOpt("service-identifier").create("i");

    Option pwdLengthOpt = OptionBuilder.withArgName("Password Length").withType(Integer.class).hasArg()
            .withDescription("Length of the password in characters").withLongOpt("pwd-length").create("l");

    Option specialChars = OptionBuilder.withArgName("With special chars (TRUE|false)").withType(Boolean.class)
            .hasArg().withDescription("Set to true if special chars !-_?=@/+* are desired, else false")
            .withLongOpt("special-chars").create("c");

    Option suppressPwdOutpOpt = OptionBuilder
            .withDescription("Suppress password output (copy to clipboard only)").withLongOpt("hide-password")
            .hasArg(false).create("x");

    Option helpOpt = OptionBuilder.withDescription("Prints this help message").withLongOpt("help").create("h");

    options.addOption(seedPwdOpt);
    options.addOption(serviceIdOpt);
    options.addOption(pwdLengthOpt);
    options.addOption(specialChars);
    options.addOption(suppressPwdOutpOpt);
    options.addOption(helpOpt);

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

        if (cmd.hasOption("h")) {
            SafePwdGen.printHelp(options);
            System.exit(0);
        }

        int pwdLength = STD_PWD_LENGTH;
        if (cmd.hasOption("l")) {
            pwdLength = new Integer(cmd.getOptionValue("l"));
        }

        boolean useSpecialChars = true;
        if (cmd.hasOption("c")) {
            useSpecialChars = new Boolean(cmd.getOptionValue("c"));
        }

        if (pwdLength > MAX_PWD_LENGTH_64 && !useSpecialChars) {
            System.out.println(PASSWORD_SIZE_TOO_BIG + MAX_PWD_LENGTH_64);
        }

        if (pwdLength > MAX_PWD_LENGTH_71 && useSpecialChars) {
            System.out.println(PASSWORD_SIZE_TOO_BIG + MAX_PWD_LENGTH_71);
        }

        boolean suppressPwdOutput = cmd.hasOption('x');

        String pwd = SafePwdGen.createPwd(cmd.getOptionValue("s"), cmd.getOptionValue("i"), pwdLength,
                useSpecialChars);

        if (!suppressPwdOutput) {
            System.out.print(GENERATED_PASSWORD);
            System.out.println(pwd);
        }
        System.out.println(CLIPBOARD_COPIED_MSG);
        SystemClipboardInterface.copy(pwd);

        System.in.read();
    } catch (ParseException e) {
        System.out.println(e.getLocalizedMessage());
        SafePwdGen.printHelp(options);
    } catch (UnsupportedEncodingException e) {
        System.out.println(e.getLocalizedMessage());
    } catch (NoSuchAlgorithmException e) {
        System.out.println(e.getLocalizedMessage());
    } catch (IOException e) {
        System.out.println(e.getLocalizedMessage());
    }
}

From source file:jrrombaldo.pset.PSETMain.java

public static void main(String[] args) {

    Options options = prepareOptions();/*w  ww .  j  av  a2 s .  com*/
    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine line = parser.parse(options, args);

        String domain = line.getOptionValue("d");

        // print help
        if (line.hasOption("h")) {
            printHelp(options);
            return;
        }

        // start gui e do nothing else
        if (!line.hasOption("c")) {
            startGuiVersion(domain);
            return;
        }

        // start gui e do nothing else
        if (!line.hasOption("d")) {
            System.out.println("a target domain is required, none was specified!");
            printHelp(options);
            return;
        }

        if (!line.hasOption("g") && !line.hasOption("b")) {
            System.out.println("No search engine selected, at least one should be present");
            printHelp(options);
            return;
        }

        if (line.hasOption("p")) {
            String proxy = line.getOptionValue("p");
            System.out.println(proxy);
        }

        Set<String> results = new HashSet<>();

        if (line.hasOption("g")) {
            results.addAll(new GoogleSearch(domain).listSubdomains());
        }

        if (line.hasOption("b")) {
            results.addAll(new BingSearch(domain).listSubdomains());
        }

        List<String> sortedResult = new ArrayList<String>(results);
        Collections.sort(sortedResult);
        int q = 1;
        for (String subDomain : sortedResult) {
            if (q == 1) {
                System.out.println("\nResults:");
            }
            System.out.println(q + ": " + subDomain);
            q++;
        }

    } catch (ParseException exp) {
        System.out.println(exp.getLocalizedMessage());
        printHelp(options);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:io.s4.adapter.Adapter.java

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

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(//from w  w w. j  a  v a2s .com
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    options.addOption(OptionBuilder.withArgName("userconfig").hasArg()
            .withDescription("user-defined legacy data adapter configuration file").create("d"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    String userConfigFilename = null;
    if (commandLine.hasOption("d")) {
        userConfigFilename = commandLine.getOptionValue("d");
    }

    File userConfigFile = new File(userConfigFilename);
    if (!userConfigFile.isFile()) {
        System.err.println("Bad user configuration file: " + userConfigFilename);
        System.exit(1);
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = configBase + File.separatorChar + "adapter-conf.xml";
    File configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("adapter config file %s does not exist\n", configPath);
        System.exit(1);
    }

    // load adapter config xml
    ApplicationContext coreContext;
    coreContext = new FileSystemXmlApplicationContext("file:" + configPath);
    ApplicationContext context = coreContext;

    Adapter adapter = (Adapter) context.getBean("adapter");

    ApplicationContext appContext = new FileSystemXmlApplicationContext(
            new String[] { "file:" + userConfigFilename }, context);
    Map listenerBeanMap = appContext.getBeansOfType(EventProducer.class);
    if (listenerBeanMap.size() == 0) {
        System.err.println("No user-defined listener beans");
        System.exit(1);
    }
    EventProducer[] eventListeners = new EventProducer[listenerBeanMap.size()];

    int index = 0;
    for (Iterator it = listenerBeanMap.keySet().iterator(); it.hasNext(); index++) {
        String beanName = (String) it.next();
        System.out.println("Adding producer " + beanName);
        eventListeners[index] = (EventProducer) listenerBeanMap.get(beanName);
    }

    adapter.setEventListeners(eventListeners);
}

From source file:com.jcwhatever.resourcepackermc.Main.java

public static void main(String[] args) {

    if (args.length == 0) {
        launch(args);/*from  w ww  .  j  av  a 2  s  . c o  m*/
        return;
    }

    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(_options, args);
    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        showHelp();
        System.exit(-1);
        return;
    }

    // show help if requested
    if (cmd.hasOption("help")) {
        showHelp();
        return;
    }

    File folder;

    if (cmd.hasOption("folder")) {
        // use specified folder
        String foldername = cmd.getOptionValue("folder");
        folder = new File(foldername);
    } else {
        // use folder jar file is in.
        folder = Utils.getJarFolder();
    }

    // make sure folder exists
    if (!folder.exists()) {
        System.err.println("Folder not found: " + folder);
        System.exit(-1);
        return;
    }

    ResourcePackFiles files = new ResourcePackFiles(folder);
    Collection<OggSound> sounds = files.getSounds();
    Collection<OggSound> extraSounds = MinecraftSounds.removeMinecraft(sounds);

    // generate/update sounds.json file
    if (cmd.hasOption("sounds")) {

        SoundsJSONGenerator generator = new SoundsJSONGenerator();

        generator.generate(files, SoundsJSONGenerator.getFile(folder));

        // add newly generated sounds.json files to files collection
        if (files.getSoundsJson() == null) {
            File file = SoundsJSONGenerator.getFile(folder);
            files.getFiles().add(file);
        }
    }

    // Generate resource-sounds.yml
    if (cmd.hasOption("nucleus")) {
        NucleusGenerator generator = new NucleusGenerator();
        generator.generate(files, new File(Utils.getJarFolder(), "resource-sounds.yml"));
    }

    // Generate SOUNDS.TXT and SOUNDS_EXTRA.TXT
    if (cmd.hasOption("soundtxt")) {
        SoundsTxtGenerator generator = new SoundsTxtGenerator();

        File tracksFile = new File(Utils.getJarFolder(), "SOUNDS.TXT");

        generator.generate(files, tracksFile);
        System.out.println("Generated SOUNDS.TXT");

        if (!files.getFiles().contains(tracksFile)) {
            files.getFiles().add(tracksFile);
            System.out.println("Packed SOUNDS.TXT");
        }

        if (!extraSounds.isEmpty()) {

            SoundsExtraTxtGenerator extraGen = new SoundsExtraTxtGenerator();
            File extraTracksFile = new File(Utils.getJarFolder(), "SOUNDS_EXTRA.TXT");

            extraGen.generate(files, extraTracksFile);
            System.out.println("Generated SOUNDS_EXTRA.TXT");

            if (!files.getFiles().contains(extraTracksFile)) {
                files.getFiles().add(extraTracksFile);
                System.out.println("Packed SOUNDS_EXTRA.TXT");
            }
        }
    }

    // Generate Zip file
    if (cmd.hasOption("zip")) {
        String filename = cmd.getOptionValue("zip");
        File file = new File(Utils.getJarFolder(), filename);

        PackGenerator generator = new PackGenerator();
        generator.generate(files, file);
    }
}

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

public static void main(String[] args) {

    Options options = createOptions();/*w  ww .ja v  a2  s  .  c  o 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:main.RankerOCR.java

/**
 * Command line interface for RankerOCR.
 * <p>/* ww  w.  j a v a 2  s .  c  o m*/
 * <b>Command line input:</b>
 * <ul>
 * usage: java -jar Ranker-OCR [options]
 * </ul>
 * <b>Options list:</b>
 * <ul>
 * <li>-gui Launch a graphical user interface</li>
 * <li>-help Show the help</li>
 * <li>-indoc1 [arg] Set the file name of the original document</li>
 * <li>-indoc2 [arg] Set the file name of the document to compare</li>
 * <li>-ranker [arg] Set the ranker used for the comparison</li>
 * <li>-outdoc [arg] Set the document where write the results</li>
 * <li>-separator [arg] Set the delimiter char use in the CSV out file</li>
 * </ul>
 * <b>Return values are if error:</b>
 * <ul>
 * <li>(-1) The precision parameter is not a number.</li>
 * <li>(-2) The precision parameter is lower than 0.</li>
 * <li>(-3) The precision parameter is greater than 10.</li>
 * <li>(-11) The ranker name is wrong</li>
 * <li>(-21) The separator char is empty</li>
 * <li>(-22) The separator is not a char</li>
 * <li>(-31) File name doesn't exist</li>
 * <li>(-32) File name is not a file</li>
 * <li>(-33) Error when access to documents files</li>
 * <li>(-34) Output file can not be write</li>
 * <li>(-35) Output file can not be created</li>
 * <li>(-41) Error when parsing parameters</li>
 * <li>(-100) Internal error when creating the ranker. Please report a
 * bug</li>
 * <li>(-101) Internal error when get the ranker list. Please report a
 * bug.</li>
 * <li>(-102) Error when access to help file. Please report a bug.</li>
 * </ul>
 * <p>
 * @param args Argument array which can have the values from options list
 */
public static void main(String[] args) {
    //Parse command line
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("help")) {
            showHelp(hf, options);
        } else if (cmd.hasOption("gui")) {
            display.DispalyRankerOCR.main(new String[] {});
        } else if (cmd.hasOption("indoc1") && cmd.hasOption("indoc2") && cmd.hasOption("outdoc")) {
            //<editor-fold defaultstate="collapsed" desc="Rank documents">
            //Prepare parameter
            Class ranker = evalRanker(cmd.getOptionValue("ranker", "SimpleRanker"));
            char separator = evalSeparator(cmd.getOptionValue("separator", "\t"));
            File f1 = evalInputFile(cmd.getOptionValue("indoc1", ""));
            File f2 = evalInputFile(cmd.getOptionValue("indoc2", ""));
            File f3 = evalOutputFile(cmd.getOptionValue("outdoc", ""), separator);
            //Read file
            String s1 = readInputDocText(f1);
            String s2 = readInputDocText(f2);
            //Compare file
            double percent = rankDocuments(s1, s2, ranker);
            //Write result
            String[] s = { Double.toString(percent), ranker.getSimpleName(), f1.getName(), f2.getName(),
                    f1.getParent(), f2.getParent(), new Date().toString() };
            writeOutpuDocCsv(f3, separator, s);
            //</editor-fold>
        } else {
            printFormated("java -jar Ranker-OCR [options]  please type " + "-help for more info");
        }
    } catch (ParseException ex) {
        printFormated(ex.getLocalizedMessage());
        System.exit(-41);
    }
}

From source file:io.s4.MainApp.java

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

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(/*from  w  ww . ja  v a2s .c o m*/
            OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a"));

    options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d"));

    options.addOption(OptionBuilder.withArgName("seedtime").hasArg()
            .withDescription("event clock initialization time").create("s"));

    options.addOption(
            OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e"));

    options.addOption(
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;
    String clockType = "wall";

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    if (commandLine.hasOption("a")) {
        appsHome = commandLine.getOptionValue("a");
    }

    if (commandLine.hasOption("d")) {
        clockType = commandLine.getOptionValue("d");
    }

    if (commandLine.hasOption("e")) {
        extsHome = commandLine.getOptionValue("e");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    long seedTime = 0;
    if (commandLine.hasOption("s")) {
        seedTime = Long.parseLong(commandLine.getOptionValue("s"));
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    File appsHomeFile = new File(appsHome);
    if (!appsHomeFile.isDirectory()) {
        System.err.println("Bad applications home: " + appsHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    List loArgs = commandLine.getArgList();

    if (loArgs.size() < 1) {
        // System.err.println("No bean configuration file specified");
        // System.exit(1);
    }

    // String s4ConfigXml = (String) loArgs.get(0);
    // System.out.println("s4ConfigXml is " + s4ConfigXml);

    ClassPathResource propResource = new ClassPathResource("s4-core.properties");
    Properties prop = new Properties();
    if (propResource.exists()) {
        prop.load(propResource.getInputStream());
    } else {
        System.err.println("Unable to find s4-core.properties. It must be available in classpath");
        System.exit(1);
    }

    ApplicationContext coreContext = null;
    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = "";
    List<String> coreConfigUrls = new ArrayList<String>();
    File configFile = null;

    // load clock configuration
    configPath = configBase + File.separatorChar + clockType + "-clock.xml";
    coreConfigUrls.add(configPath);

    // load core config xml
    configPath = configBase + File.separatorChar + "s4-core-conf.xml";
    configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("S4 core config file %s does not exist\n", configPath);
        System.exit(1);
    }

    coreConfigUrls.add(configPath);
    String[] coreConfigFiles = new String[coreConfigUrls.size()];
    coreConfigUrls.toArray(coreConfigFiles);

    String[] coreConfigFileUrls = new String[coreConfigFiles.length];
    for (int i = 0; i < coreConfigFiles.length; i++) {
        coreConfigFileUrls[i] = "file:" + coreConfigFiles[i];
    }

    coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext);
    ApplicationContext context = coreContext;

    Clock s4Clock = (Clock) context.getBean("clock");
    if (s4Clock instanceof EventClock && seedTime > 0) {
        EventClock s4EventClock = (EventClock) s4Clock;
        s4EventClock.updateTime(seedTime);
        System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime());
    }

    PEContainer peContainer = (PEContainer) context.getBean("peContainer");

    Watcher w = (Watcher) context.getBean("watcher");
    w.setConfigFilename(configPath);

    // load extension modules
    String[] configFileNames = getModuleConfigFiles(extsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
    }

    // load application modules
    configFileNames = getModuleConfigFiles(appsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
        // attach any beans that implement ProcessingElement to the PE
        // Container
        String[] processingElementBeanNames = context.getBeanNamesForType(ProcessingElement.class);
        for (String processingElementBeanName : processingElementBeanNames) {
            Object bean = context.getBean(processingElementBeanName);
            try {
                Method getS4ClockMethod = bean.getClass().getMethod("getS4Clock");

                if (getS4ClockMethod.getReturnType().equals(Clock.class)) {
                    if (getS4ClockMethod.invoke(bean) == null) {
                        Method setS4ClockMethod = bean.getClass().getMethod("setS4Clock", Clock.class);
                        setS4ClockMethod.invoke(bean, coreContext.getBean("clock"));
                    }
                }
            } catch (NoSuchMethodException mnfe) {
                // acceptable
            }
            System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id "
                    + ((ProcessingElement) bean).getId());
            peContainer.addProcessor((ProcessingElement) bean, processingElementBeanName);
        }
    }
}

From source file:illarion.compile.Compiler.java

public static void main(final String[] args) {
    ByteArrayOutputStream stdOutBuffer = new ByteArrayOutputStream();
    PrintStream orgStdOut = System.out;
    System.setOut(new PrintStream(stdOutBuffer));

    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();/*from   w  ww  . j  a v a  2 s.  co  m*/

    Options options = new Options();

    final Option npcDir = new Option("n", "npc-dir", true,
            "The place where the compiled NPC files are stored.");
    npcDir.setArgs(1);
    npcDir.setArgName("directory");
    npcDir.setRequired(false);
    options.addOption(npcDir);

    final Option questDir = new Option("q", "quest-dir", true,
            "The place where the compiled Quest files are stored.");
    questDir.setArgs(1);
    questDir.setArgName("directory");
    questDir.setRequired(false);
    options.addOption(questDir);

    final Option type = new Option("t", "type", true,
            "This option is used to set what kind of parser is supposed to be used in case"
                    + " the content of standard input is processed.");
    type.setArgs(1);
    type.setArgName("type");
    type.setRequired(false);
    options.addOption(type);

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

        String[] files = cmd.getArgs();
        if (files.length > 0) {
            System.setOut(orgStdOut);
            stdOutBuffer.writeTo(orgStdOut);

            processFileMode(cmd);
        } else {
            System.setOut(orgStdOut);
            processStdIn(cmd);
        }
    } catch (final ParseException e) {
        final HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar compiler.jar [Options] File", options, true);
        System.exit(-1);
    } catch (final IOException e) {
        LOGGER.error(e.getLocalizedMessage());
        System.exit(-1);
    }
}