Example usage for org.apache.commons.cli GnuParser GnuParser

List of usage examples for org.apache.commons.cli GnuParser GnuParser

Introduction

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

Prototype

GnuParser

Source Link

Usage

From source file:com.mindquarry.jcr.change.ChangeClient.java

public static void main(String[] args) {
    log = LogFactory.getLog(ChangeClient.class);
    log.info("Starting persistence client...");

    // parse command line arguments
    CommandLine line = null;//from  w w  w.j  a v a2s  .c o m
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException e) {
        // oops, something went wrong
        log.error("Parsing of command line failed.");
        printUsage();
        return;
    }
    // check debug option
    boolean debug = false;
    if (line.hasOption(O_DRY)) {
        log.info("Running in 'dry' mode.");
        debug = true;
    }
    // start change client
    ChangeClient cl = new ChangeClient();
    try {
        cl.run(line.getOptionValue(O_REPO), line.getOptionValue(O_USER), line.getOptionValue(O_PWD),
                line.getOptionValue(O_XSLT), line.getOptionValue(O_FOLDER), debug);
    } catch (Exception e) {
        log.error("Error while applying changes.", e);
    }
    log.info("Changes applied.");
}

From source file:apps.quantification.LearnQuantificationSVMLight.java

public static void main(String[] args) throws IOException {
    String cmdLineSyntax = LearnQuantificationSVMLight.class.getName()
            + " [OPTIONS] <path to svm_light_learn> <path to svm_light_classify> <trainingIndexDirectory> <outputDirectory>";

    Options options = new Options();

    OptionBuilder.withArgName("f");
    OptionBuilder.withDescription("Number of folds");
    OptionBuilder.withLongOpt("f");
    OptionBuilder.isRequired(true);/*  www . j a  va  2s .  c  o  m*/
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("c");
    OptionBuilder.withDescription("The c value for svm_light (default 1)");
    OptionBuilder.withLongOpt("c");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("k");
    OptionBuilder.withDescription("Kernel type (default 0: linear, 1: polynomial, 2: RBF, 3: sigmoid)");
    OptionBuilder.withLongOpt("k");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("t");
    OptionBuilder.withDescription("Path for temporary files");
    OptionBuilder.withLongOpt("t");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("v");
    OptionBuilder.withDescription("Verbose output");
    OptionBuilder.withLongOpt("v");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("s");
    OptionBuilder.withDescription("Don't delete temporary training file in svm_light format (default: delete)");
    OptionBuilder.withLongOpt("s");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    SvmLightLearnerCustomizer classificationLearnerCustomizer = null;
    SvmLightClassifierCustomizer classificationCustomizer = null;

    int folds = -1;

    GnuParser parser = new GnuParser();
    String[] remainingArgs = null;
    try {
        CommandLine line = parser.parse(options, args);

        remainingArgs = line.getArgs();

        classificationLearnerCustomizer = new SvmLightLearnerCustomizer(remainingArgs[0]);
        classificationCustomizer = new SvmLightClassifierCustomizer(remainingArgs[1]);

        folds = Integer.parseInt(line.getOptionValue("f"));

        if (line.hasOption("c"))
            classificationLearnerCustomizer.setC(Float.parseFloat(line.getOptionValue("c")));

        if (line.hasOption("k")) {
            System.out.println("Kernel type: " + line.getOptionValue("k"));
            classificationLearnerCustomizer.setKernelType(Integer.parseInt(line.getOptionValue("k")));
        }

        if (line.hasOption("v"))
            classificationLearnerCustomizer.printSvmLightOutput(true);

        if (line.hasOption("s"))
            classificationLearnerCustomizer.setDeleteTrainingFiles(false);

        if (line.hasOption("t")) {
            classificationLearnerCustomizer.setTempPath(line.getOptionValue("t"));
            classificationCustomizer.setTempPath(line.getOptionValue("t"));
        }

    } catch (Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    assert (classificationLearnerCustomizer != null);

    if (remainingArgs.length != 4) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    String indexFile = remainingArgs[2];

    File file = new File(indexFile);

    String indexName = file.getName();
    String indexPath = file.getParent();

    String outputPath = remainingArgs[3];

    SvmLightLearner classificationLearner = new SvmLightLearner();

    classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer);

    FileSystemStorageManager fssm = new FileSystemStorageManager(indexPath, false);
    fssm.open();

    IIndex training = TroveReadWriteHelper.readIndex(fssm, indexName, TroveContentDBType.Full,
            TroveClassificationDBType.Full);

    final TextualProgressBar progressBar = new TextualProgressBar("Learning the quantifiers");

    IOperationStatusListener status = new IOperationStatusListener() {

        @Override
        public void operationStatus(double percentage) {
            progressBar.signal((int) percentage);
        }
    };

    QuantificationLearner quantificationLearner = new QuantificationLearner(folds, classificationLearner,
            classificationLearnerCustomizer, classificationCustomizer, ClassificationMode.PER_CATEGORY,
            new LogisticFunction(), status);

    IQuantifier[] quantifiers = quantificationLearner.learn(training);

    File executableFile = new File(classificationLearnerCustomizer.getSvmLightLearnPath());
    IDataManager classifierDataManager = new SvmLightDataManager(new SvmLightClassifierCustomizer(
            executableFile.getParentFile().getAbsolutePath() + Os.pathSeparator() + "svm_light_classify"));
    String description = "_SVMLight_C-" + classificationLearnerCustomizer.getC() + "_K-"
            + classificationLearnerCustomizer.getKernelType();
    if (classificationLearnerCustomizer.getAdditionalParameters().length() > 0)
        description += "_" + classificationLearnerCustomizer.getAdditionalParameters();
    String quantifierPrefix = indexName + "_Quantifier-" + folds + description;

    FileSystemStorageManager fssmo = new FileSystemStorageManager(
            outputPath + File.separatorChar + quantifierPrefix, true);
    fssmo.open();
    QuantificationLearner.write(quantifiers, fssmo, classifierDataManager);
    fssmo.close();

    BufferedWriter bfs = new BufferedWriter(
            new FileWriter(outputPath + File.separatorChar + quantifierPrefix + "_rates.txt"));
    TShortDoubleHashMap simpleTPRs = quantificationLearner.getSimpleTPRs();
    TShortDoubleHashMap simpleFPRs = quantificationLearner.getSimpleFPRs();
    TShortDoubleHashMap scaledTPRs = quantificationLearner.getScaledTPRs();
    TShortDoubleHashMap scaledFPRs = quantificationLearner.getScaledFPRs();

    ContingencyTableSet contingencyTableSet = quantificationLearner.getContingencyTableSet();

    short[] cats = simpleTPRs.keys();
    for (int i = 0; i < cats.length; ++i) {
        short cat = cats[i];
        String catName = training.getCategoryDB().getCategoryName(cat);
        ContingencyTable contingencyTable = contingencyTableSet.getCategoryContingencyTable(cat);
        double simpleTPR = simpleTPRs.get(cat);
        double simpleFPR = simpleFPRs.get(cat);
        double scaledTPR = scaledTPRs.get(cat);
        double scaledFPR = scaledFPRs.get(cat);
        String line = quantifierPrefix + "\ttrain\tsimple\t" + catName + "\t" + cat + "\t"
                + contingencyTable.tp() + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t"
                + contingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n";
        bfs.write(line);
        line = quantifierPrefix + "\ttrain\tscaled\t" + catName + "\t" + cat + "\t" + contingencyTable.tp()
                + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t" + contingencyTable.tn()
                + "\t" + scaledTPR + "\t" + scaledFPR + "\n";
        bfs.write(line);
    }
    bfs.close();
}

From source file:net.mybox.mybox.ServerSetup.java

/**
 * Handle command line arguments//from   ww  w  .  j  ava2 s  .  co m
 * @param args
 */
public static void main(String[] args) {

    Options options = new Options();
    options.addOption("a", "apphome", true, "application home directory");
    options.addOption("h", "help", false, "show help screen");
    options.addOption("V", "version", false, "print the Mybox version");

    CommandLineParser line = new GnuParser();
    CommandLine cmd = null;

    try {
        cmd = line.parse(options, args);
    } catch (Exception exp) {
        System.err.println(exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Server.class.getName(), options);
        return;
    }

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Server.class.getName(), options);
        return;
    }

    if (cmd.hasOption("V")) {
        Server.printMessage("version " + Common.appVersion);
        return;
    }

    if (cmd.hasOption("a")) {
        String appHomeDir = cmd.getOptionValue("a");
        try {
            Common.updatePaths(appHomeDir);
        } catch (FileNotFoundException e) {
            Server.printErrorExit(e.getMessage());
        }

        Server.updatePaths();
    }

    ServerSetup setup = new ServerSetup();
}

From source file:fr.inria.atlanmod.instantiator.neoEMF.Launcher.java

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

    ResourceSetImpl resourceSet = new ResourceSetImpl();
    { // initializing the registry

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX,
                new EcoreResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME,
                NeoEMFResourceFactory.eINSTANCE);

    }// w w w  . ja  v  a 2s  . c o  m

    Options options = new Options();

    configureOptions(options);

    CommandLineParser parser = new GnuParser();

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

        String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS);

        LOGGER.info("Start loading the package");
        Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class);
        EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null);

        Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy"));
        metamodelResource.getContents().add(_package);
        LOGGER.info("Finish loading the package");

        int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE;
        if (commandLine.hasOption(SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(SIZE);
            size = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        float variation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION,
                        number.floatValue()));
            }
            variation = number.floatValue();
        }

        float propVariation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(PROP_VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}",
                        PROP_VARIATION, number.floatValue()));
            }
            propVariation = number.floatValue();
        }

        long seed = System.currentTimeMillis();
        if (commandLine.hasOption(SEED)) {
            seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue();
        }

        Range<Integer> range = Range.between(Math.round(size * (1 - variation)),
                Math.round(size * (1 + variation)));

        GenericMetamodelConfig config = new GenericMetamodelConfig(metamodelResource, range, seed);
        GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(config);

        if (commandLine.hasOption(OUTPUT_PATH)) {
            String outDir = commandLine.getOptionValue(OUTPUT_PATH);
            //java.net.URI intermediateURI = java.net.URI.create(outDir);
            modelGen.setSamplesPath(outDir);
        }

        int numberOfModels = 1;
        if (commandLine.hasOption(N_MODELS)) {
            numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue();
        }

        int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH;
        if (commandLine.hasOption(VALUES_SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE);
            valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE;
        if (commandLine.hasOption(VALUES_SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(DEGREE);
            referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        config.setValuesRange(Math.round(valuesSize * (1 - propVariation)),
                Math.round(valuesSize * (1 + propVariation)));

        config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        long start = System.currentTimeMillis();
        modelGen.runGeneration(resourceSet, numberOfModels, size, variation);
        long end = System.currentTimeMillis();
        LOGGER.info(
                MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000)));

        if (commandLine.hasOption(DIAGNOSE)) {
            for (Resource resource : resourceSet.getResources()) {
                LOGGER.info(
                        MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI()));
                BasicDiagnostic diagnosticChain = diagnoseResource(resource);
                if (!isFailed(diagnosticChain)) {
                    LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''",
                            resource.getURI()));
                } else {
                    LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''",
                            diagnosticChain.getChildren().size(), resource.getURI()));
                    for (Diagnostic diagnostic : diagnosticChain.getChildren()) {
                        LOGGER.fine(diagnostic.getMessage());
                    }
                }
            }
            LOGGER.info("Validation finished");
        }

    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new OptionComarator<Option>());
        try {
            formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80));
        } catch (Throwable t) {
            LOGGER.warning("Unable to get console information");
        }
        ;
        formatter.printHelp("java -jar <this-file.jar>", options, true);
        System.exit(ERROR);
    } catch (ClassNotFoundException t) {
        System.err.println("ERROR: Unable to load class" + t.getLocalizedMessage());
        StringWriter stringWriter = new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter));
        System.err.println(stringWriter.toString());
    } catch (Throwable t) {
        System.err.println("ERROR: " + t.getLocalizedMessage());
        StringWriter stringWriter = new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter));
        System.err.println(t);
        LOGGER.severe(stringWriter.toString());
        System.exit(ERROR);
    }
}

From source file:de.unisb.cs.st.javaslicer.jung.ShowJungGraph.java

public static void main(String[] args) throws InterruptedException {
    Options options = createOptions();/*  w w  w  . j  ava  2  s  . c om*/
    CommandLineParser parser = new GnuParser();
    CommandLine cmdLine;

    try {
        cmdLine = parser.parse(options, args, true);
    } catch (ParseException e) {
        System.err.println("Error parsing the command line arguments: " + e.getMessage());
        return;
    }

    if (cmdLine.hasOption('h')) {
        printHelp(options, System.out);
        System.exit(0);
    }

    String[] additionalArgs = cmdLine.getArgs();
    if (additionalArgs.length != 2) {
        printHelp(options, System.err);
        System.exit(-1);
    }
    File traceFile = new File(additionalArgs[0]);
    String slicingCriterionString = additionalArgs[1];

    Long threadId = null;
    if (cmdLine.hasOption('t')) {
        try {
            threadId = Long.parseLong(cmdLine.getOptionValue('t'));
        } catch (NumberFormatException e) {
            System.err.println("Illegal thread id: " + cmdLine.getOptionValue('t'));
            System.exit(-1);
        }
    }

    TraceResult trace;
    try {
        trace = TraceResult.readFrom(traceFile);
    } catch (IOException e) {
        System.err.format("Could not read the trace file \"%s\": %s%n", traceFile, e);
        System.exit(-1);
        return;
    }

    List<SlicingCriterion> sc = null;
    try {
        sc = StaticSlicingCriterion.parseAll(slicingCriterionString, trace.getReadClasses());
    } catch (IllegalArgumentException e) {
        System.err.println("Error parsing slicing criterion: " + e.getMessage());
        System.exit(-1);
        return;
    }

    List<ThreadId> threads = trace.getThreads();
    if (threads.size() == 0) {
        System.err.println("The trace file contains no tracing information.");
        System.exit(-1);
    }

    ThreadId tracing = null;
    for (ThreadId t : threads) {
        if (threadId == null) {
            if ("main".equals(t.getThreadName())
                    && (tracing == null || t.getJavaThreadId() < tracing.getJavaThreadId()))
                tracing = t;
        } else if (t.getJavaThreadId() == threadId.longValue()) {
            tracing = t;
        }
    }

    if (tracing == null) {
        System.err.println(threadId == null ? "Couldn't find the main thread."
                : "The thread you specified was not found.");
        System.exit(-1);
        return;
    }

    Transformer<InstructionInstance, Object> transformer;
    Transformer<Object, String> vertexLabelTransformer;
    Transformer<Object, String> vertexTooltipTransformer;

    String granularity = cmdLine.getOptionValue("granularity");
    if (granularity == null || "instance".equals(granularity)) {
        transformer = new Transformer<InstructionInstance, Object>() {
            @Override
            public InstructionInstance transform(InstructionInstance inst) {
                return inst;
            }
        };
        vertexLabelTransformer = new Transformer<Object, String>() {
            @Override
            public String transform(Object inst) {
                return getShortInstructionText(((InstructionInstance) inst).getInstruction());
            }
        };
        vertexTooltipTransformer = new Transformer<Object, String>() {
            @Override
            public String transform(Object inst) {
                return getInstructionTooltip(((InstructionInstance) inst).getInstruction());
            }
        };
    } else if ("instruction".equals(granularity)) {
        transformer = new Transformer<InstructionInstance, Object>() {
            @Override
            public Instruction transform(InstructionInstance inst) {
                return inst.getInstruction();
            }
        };
        vertexLabelTransformer = new Transformer<Object, String>() {
            @Override
            public String transform(Object inst) {
                return getShortInstructionText(((Instruction) inst));
            }
        };
        vertexTooltipTransformer = new Transformer<Object, String>() {
            @Override
            public String transform(Object inst) {
                return getInstructionTooltip(((Instruction) inst));
            }
        };
    } else if ("line".equals(granularity)) {
        transformer = new Transformer<InstructionInstance, Object>() {
            @Override
            public Line transform(InstructionInstance inst) {
                return new Line(inst.getInstruction().getMethod(), inst.getInstruction().getLineNumber());
            }
        };
        vertexLabelTransformer = new Transformer<Object, String>() {
            @Override
            public String transform(Object inst) {
                Line line = (Line) inst;
                return line.getMethod().getName() + ":" + line.getLineNr();
            }
        };
        vertexTooltipTransformer = new Transformer<Object, String>() {
            @Override
            public String transform(Object inst) {
                Line line = (Line) inst;
                return "Line " + line.getLineNr() + " in method " + line.getMethod().getReadClass().getName()
                        + "." + line.getMethod();
            }
        };
    } else {
        System.err.println("Illegal granularity specification: " + granularity);
        System.exit(-1);
        return;
    }

    int maxLevel = Integer.MAX_VALUE;
    if (cmdLine.hasOption("maxlevel")) {
        try {
            maxLevel = Integer.parseInt(cmdLine.getOptionValue("maxlevel"));
        } catch (NumberFormatException e) {
            System.err.println("Argument to \"maxlevel\" must be an integer.");
            System.exit(-1);
            return;
        }
    }

    long startTime = System.nanoTime();
    ShowJungGraph<Object> showGraph = new ShowJungGraph<Object>(trace, transformer);
    showGraph.setMaxLevel(maxLevel);
    showGraph.setVertexLabelTransformer(vertexLabelTransformer);
    showGraph.setVertexTooltipTransformer(vertexTooltipTransformer);
    if (cmdLine.hasOption("progress"))
        showGraph.addProgressMonitor(new ConsoleProgressMonitor());
    boolean multithreaded;
    if (cmdLine.hasOption("multithreaded")) {
        String multithreadedStr = cmdLine.getOptionValue("multithreaded");
        multithreaded = ("1".equals(multithreadedStr) || "true".equals(multithreadedStr));
    } else {
        multithreaded = Runtime.getRuntime().availableProcessors() > 1;
    }

    DirectedGraph<Object, SliceEdge<Object>> graph = showGraph.getGraph(tracing, sc, multithreaded);
    long endTime = System.nanoTime();

    System.out.format((Locale) null, "%nSlice graph consists of %d nodes.%n", graph.getVertexCount());
    System.out.format((Locale) null, "Computation took %.2f seconds.%n", 1e-9 * (endTime - startTime));

    showGraph.displayGraph(graph);
}

From source file:fr.inria.atlanmod.dag.instantiator.Launcher.java

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

    ResourceSetImpl resourceSet = new ResourceSetImpl();
    { // initializing the registry

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX,
                new EcoreResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME,
                NeoEMFResourceFactory.eINSTANCE);

    }//from www.jav  a  2  s  . c  o m

    Options options = new Options();

    configureOptions(options);

    CommandLineParser parser = new GnuParser();

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

        //         String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS);
        //         
        //         LOGGER.info("Start loading the package");
        //         Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class);
        //         EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null);
        //         
        //         Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy"));
        //          metamodelResource.getContents().add(_package);
        //          LOGGER.info("Finish loading the package");

        int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE;
        if (commandLine.hasOption(SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(SIZE);
            size = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        float variation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION,
                        number.floatValue()));
            }
            variation = number.floatValue();
        }

        float propVariation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(PROP_VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}",
                        PROP_VARIATION, number.floatValue()));
            }
            propVariation = number.floatValue();
        }

        long seed = System.currentTimeMillis();
        if (commandLine.hasOption(SEED)) {
            seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue();
        }

        Range<Integer> range = Range.between(Math.round(size * (1 - variation)),
                Math.round(size * (1 + variation)));

        ISpecimenConfiguration config = new DagMetamodelConfig(range, seed);
        IGenerator generator = new DagGenerator(config, config.getSeed());

        GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(generator);

        if (commandLine.hasOption(OUTPUT_PATH)) {
            String outDir = commandLine.getOptionValue(OUTPUT_PATH);
            //java.net.URI intermediateURI = java.net.URI.create(outDir);
            modelGen.setSamplesPath(outDir);
        }

        int numberOfModels = 1;
        if (commandLine.hasOption(N_MODELS)) {
            numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue();
        }

        int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH;
        if (commandLine.hasOption(VALUES_SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE);
            valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE;
        if (commandLine.hasOption(DEGREE)) {
            Number number = (Number) commandLine.getParsedOptionValue(DEGREE);
            referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        config.setValuesRange(Math.round(valuesSize * (1 - propVariation)),
                Math.round(valuesSize * (1 + propVariation)));

        config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        long start = System.currentTimeMillis();
        modelGen.runGeneration(resourceSet, numberOfModels, size, variation);
        long end = System.currentTimeMillis();
        LOGGER.info(
                MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000)));

        //         for (Resource rsc : resourceSet.getResources()) {
        //            if (rsc.getContents().get(0) instanceof DAG) {
        //               
        //            }
        //               
        //         }

        if (commandLine.hasOption(DIAGNOSE)) {
            for (Resource resource : resourceSet.getResources()) {
                LOGGER.info(
                        MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI()));
                BasicDiagnostic diagnosticChain = diagnoseResource(resource);
                if (!isFailed(diagnosticChain)) {
                    LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''",
                            resource.getURI()));
                } else {
                    LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''",
                            diagnosticChain.getChildren().size(), resource.getURI()));
                    for (Diagnostic diagnostic : diagnosticChain.getChildren()) {
                        LOGGER.fine(diagnostic.getMessage());
                    }
                }
            }
            LOGGER.info("Validation finished");
        }

    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new OptionComarator<Option>());
        try {
            formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80));
        } catch (Throwable t) {
            LOGGER.warning("Unable to get console information");
        }
        ;
        formatter.printHelp("java -jar <this-file.jar>", options, true);
        System.exit(ERROR);
    } catch (Throwable t) {
        System.err.println("ERROR: " + t.getLocalizedMessage());
        StringWriter stringWriter = new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter));
        System.err.println(t);
        LOGGER.severe(stringWriter.toString());
        System.exit(ERROR);
    }
}

From source file:com.ibm.watson.app.qaclassifier.AddQuestionsToMockClassifier.java

public static void main(String[] args) throws IOException {
    Option urlOption = CliUtils.createOption(URL_OPTION, URL_OPTION_LONG, true,
            "The root URL of the application to connect to. If omitted, the default will be used ("
                    + DEFAULT_URL + ")",
            false, URL_OPTION_LONG);
    Option pathOption = CliUtils.createOption(FILE_OPTION, FILE_OPTION_LONG, true,
            "The file to be used as training data, can point to the file system or the class path", true,
            FILE_OPTION_LONG);//from www.  j a v a  2s . c  o m
    Option userOption = CliUtils.createOption(USER_OPTION, USER_OPTION_LONG, true,
            "The username for the manage API", true, USER_OPTION_LONG);
    Option passwordOption = CliUtils.createOption(PASSWORD_OPTION, PASSWORD_OPTION_LONG, true,
            "The password for the manage API", true, PASSWORD_OPTION_LONG);

    final Options options = CliUtils.buildOptions(urlOption, pathOption, userOption, passwordOption);

    CommandLine cmd;
    try {
        CommandLineParser parser = new GnuParser();
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Could not parse cmd line arguments.\n" + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(120, "java " + AddQuestionsToMockClassifier.class.getName(), null, options, null);
        return;
    }

    final String url = cmd.getOptionValue(URL_OPTION, DEFAULT_URL);
    final String path = cmd.getOptionValue(FILE_OPTION);
    final String user = cmd.getOptionValue(USER_OPTION);
    final String password = cmd.getOptionValue(PASSWORD_OPTION);

    AddQuestionsToMockClassifier mockSetup = new AddQuestionsToMockClassifier(url, path, user, password);

    System.out.println("Creating mock responses for the questions in " + path + "...");
    mockSetup.mockResponsesForTrainingData();

    System.out.println("Creating mock responses for the sample questions...");
    mockSetup.mockResponse(SampleQuestions.HIGH_CONFIDENCE, "mock_one_answer", HIGH_CONFIDENCE,
            "This is a question that will be answered by the mock classifier with high confidence");
    mockSetup.mockResponse(SampleQuestions.LOW_CONFIDENCE, "mock_multiple_answers", LOW_CONFIDENCE,
            "This is a question that will be answered by the mock classifier with low confidence");
    mockSetup.mockResponse(SampleQuestions.NO_ANSWERS, "mock_no_answers", NO_ANSWER_CONFIDENCE,
            "This is a question that will be answered by the mock classifier with very low confidence");
    System.out.println("Done.");
}

From source file:de.prozesskraft.pkraft.Perlcode.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try/*from  www  .  j a  va2 s.  co m*/
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/" + "../etc/pkraft-perlcode.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option ostep = OptionBuilder.withArgName("STEPNAME").hasArg().withDescription(
            "[optional] stepname of step to generate a script for. if this parameter is omitted, a script for the process will be generated.")
            //            .isRequired()
            .create("step");

    Option ooutput = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory] directory for generated files. must not exist when calling.")
            //            .isRequired()
            .create("output");

    Option odefinition = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] process definition file.")
            //            .isRequired()
            .create("definition");

    Option onolist = OptionBuilder.withArgName("")
            //            .hasArg()
            .withDescription(
                    "[optional] with this parameter the multiple use of multi-optionis is forced. otherwise it is possible to use an integrated comma-separeated list.")
            //            .isRequired()
            .create("nolist");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(ostep);
    options.addOption(ooutput);
    options.addOption(odefinition);
    options.addOption(onolist);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);
    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("perlcode", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     www.prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("definition"))) {
        System.err.println("option -definition is mandatory.");
        exiter();
    }

    if (!(commandline.hasOption("output"))) {
        System.err.println("option -output is mandatory.");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    Process p1 = new Process();
    java.io.File outputDir = new java.io.File(commandline.getOptionValue("output"));
    java.io.File outputDirProcessScript = new java.io.File(commandline.getOptionValue("output"));
    java.io.File outputDirBin = new java.io.File(commandline.getOptionValue("output") + "/bin");
    java.io.File outputDirLib = new java.io.File(commandline.getOptionValue("output") + "/lib");
    boolean nolist = false;
    if (commandline.hasOption("nolist")) {
        nolist = true;
    }

    if (outputDir.exists()) {
        System.err.println("fatal: directory already exists: " + outputDir.getCanonicalPath());
        exiter();
    } else {
        outputDir.mkdir();
    }

    p1.setInfilexml(commandline.getOptionValue("definition"));
    System.err.println("info: reading process definition " + commandline.getOptionValue("definition"));
    Process p2 = null;
    try {
        p2 = p1.readXml();
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.err.println("error");
        exiter();
    }

    // perlcode generieren fuer einen bestimmten step
    if (commandline.hasOption("step")) {
        outputDirBin.mkdir();
        String stepname = commandline.getOptionValue("step");
        writeStepAsPerlcode(p2, stepname, outputDirBin, nolist);
    }

    // perlcode generieren fuer den gesamten process
    else {
        outputDirBin.mkdir();
        writeProcessAsPerlcode(p2, outputDirProcessScript, outputDirBin, nolist);

        // copy all perllibs from the lib directory
        outputDirLib.mkdir();
        final Path source = Paths.get(WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/../perllib");
        final Path target = Paths.get(outputDirLib.toURI());

        copyDirectoryTree.copyDirectoryTree(source, target);
    }
}

From source file:de.topobyte.livecg.CreateImage.java

public static void main(String[] args) {
    EnumNameLookup<ExportFormat> exportSwitch = new EnumNameLookup<ExportFormat>(ExportFormat.class, true);

    EnumNameLookup<Visualization> visualizationSwitch = new EnumNameLookup<Visualization>(Visualization.class,
            true);/*  w  ww.  j av a 2  s. c  om*/

    // @formatter:off
    Options options = new Options();
    OptionHelper.add(options, OPTION_CONFIG, true, false, "path", "config file");
    OptionHelper.add(options, OPTION_INPUT, true, true, "file", "input geometry file");
    OptionHelper.add(options, OPTION_OUTPUT, true, true, "file", "output file");
    OptionHelper.add(options, OPTION_OUTPUT_FORMAT, true, true, "type",
            "type of output. one of <png,svg,tikz,ipe>");
    OptionHelper.add(options, OPTION_VISUALIZATION, true, true, "type",
            "type of visualization. one of <" + VisualizationUtil.getListOfAvailableVisualizations() + ">");
    OptionHelper.add(options, OPTION_STATUS, true, false,
            "status to " + "set the algorithm to. The format depends on the algorithm");
    // @formatter:on

    Option propertyOption = new Option(OPTION_PROPERTIES, "set a special property");
    propertyOption.setArgName("property=value");
    propertyOption.setArgs(2);
    propertyOption.setValueSeparator('=');
    options.addOption(propertyOption);

    CommandLineParser clp = new GnuParser();

    CommandLine line = null;
    try {
        line = clp.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Parsing command line failed: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    StringOption argConfig = ArgumentHelper.getString(line, OPTION_CONFIG);
    if (argConfig.hasValue()) {
        String configPath = argConfig.getValue();
        LiveConfig.setPath(configPath);
    }

    StringOption argInput = ArgumentHelper.getString(line, OPTION_INPUT);
    StringOption argOutput = ArgumentHelper.getString(line, OPTION_OUTPUT);
    StringOption argOutputFormat = ArgumentHelper.getString(line, OPTION_OUTPUT_FORMAT);
    StringOption argVisualization = ArgumentHelper.getString(line, OPTION_VISUALIZATION);
    StringOption argStatus = ArgumentHelper.getString(line, OPTION_STATUS);

    ExportFormat exportFormat = exportSwitch.find(argOutputFormat.getValue());
    if (exportFormat == null) {
        System.err.println("Unsupported output format '" + argOutputFormat.getValue() + "'");
        System.exit(1);
    }

    Visualization visualization = visualizationSwitch.find(argVisualization.getValue());
    if (visualization == null) {
        System.err.println("Unsupported visualization '" + argVisualization.getValue() + "'");
        System.exit(1);
    }

    System.out.println("Visualization: " + visualization);
    System.out.println("Output format: " + exportFormat);

    ContentReader contentReader = new ContentReader();
    Content content = null;
    try {
        content = contentReader.read(new File(argInput.getValue()));
    } catch (Exception e) {
        System.out.println("Error while reading input file '" + argInput.getValue() + "'. Exception type: "
                + e.getClass().getSimpleName() + ", message: " + e.getMessage());
        System.exit(1);
    }

    Properties properties = line.getOptionProperties(OPTION_PROPERTIES);

    double zoom = 1;

    String statusArgument = null;
    if (argStatus.hasValue()) {
        statusArgument = argStatus.getValue();
    }

    VisualizationSetup setup = null;

    switch (visualization) {
    case GEOMETRY: {
        setup = new ContentVisualizationSetup();
        break;
    }
    case DCEL: {
        setup = new DcelVisualizationSetup();
        break;
    }
    case FREESPACE: {
        setup = new FreeSpaceVisualizationSetup();
        break;
    }
    case DISTANCETERRAIN: {
        setup = new DistanceTerrainVisualizationSetup();
        break;
    }
    case CHAN: {
        setup = new ChanVisualizationSetup();
        break;
    }
    case MONOTONE_PIECES: {
        setup = new MonotonePiecesVisualizationSetup();
        break;
    }
    case MONOTONE_TRIANGULATION: {
        setup = new MonotoneTriangulationVisualizationSetup();
        break;
    }
    case TRIANGULATION: {
        setup = new MonotonePiecesTriangulationVisualizationSetup();
        break;
    }
    case BUFFER: {
        setup = new BufferVisualizationSetup();
        break;
    }
    case FORTUNE: {
        setup = new FortunesSweepVisualizationSetup();
        break;
    }
    case SPIP: {
        setup = new ShortestPathVisualizationSetup();
        break;
    }
    }

    if (setup == null) {
        System.err.println("Not yet implemented");
        System.exit(1);
    }

    SetupResult setupResult = setup.setup(content, statusArgument, properties, zoom);

    int width = setupResult.getWidth();
    int height = setupResult.getHeight();

    VisualizationPainter visualizationPainter = setupResult.getVisualizationPainter();

    File output = new File(argOutput.getValue());

    visualizationPainter.setZoom(zoom);

    switch (exportFormat) {
    case IPE: {
        try {
            IpeExporter.exportIpe(output, visualizationPainter, width, height);
        } catch (Exception e) {
            System.err.println("Error while exporting. Exception type: " + e.getClass().getSimpleName()
                    + ", message: " + e.getMessage());
            System.exit(1);
        }
        break;
    }
    case PNG: {
        try {
            GraphicsExporter.exportPNG(output, visualizationPainter, width, height);
        } catch (IOException e) {
            System.err.println("Error while exporting. Exception type: " + e.getClass().getSimpleName()
                    + ", message: " + e.getMessage());
            System.exit(1);
        }
        break;
    }
    case SVG: {
        try {
            SvgExporter.exportSVG(output, visualizationPainter, width, height);
        } catch (Exception e) {
            System.err.println("Error while exporting. Exception type: " + e.getClass().getSimpleName()
                    + ", message: " + e.getMessage());
            System.exit(1);
        }
        break;
    }
    case TIKZ: {
        try {
            TikzExporter.exportTikz(output, visualizationPainter, width, height);
        } catch (Exception e) {
            System.err.println("Error while exporting. Exception type: " + e.getClass().getSimpleName()
                    + ", message: " + e.getMessage());
            System.exit(1);
        }
        break;
    }
    }
}

From source file:backtype.storm.command.update_topology.java

/**
 * @param args/* ww  w  .j a  v  a  2 s  . c o  m*/
 */
public static void main(String[] args) {
    if (args == null || args.length < 3) {
        System.out.println("Invalid parameter");
        usage();
        return;
    }
    String topologyName = args[0];
    try {
        String[] str2 = Arrays.copyOfRange(args, 1, args.length);
        CommandLineParser parser = new GnuParser();
        Options r = buildGeneralOptions(new Options());
        CommandLine commandLine = parser.parse(r, str2, true);

        String pathConf = null;
        String pathJar = null;
        if (commandLine.hasOption("conf")) {
            pathConf = (commandLine.getOptionValues("conf"))[0];
        }
        if (commandLine.hasOption("jar")) {
            pathJar = (commandLine.getOptionValues("jar"))[0];
        }
        if (pathConf != null || pathJar != null)
            updateTopology(topologyName, pathJar, pathConf);
    } catch (Exception e) {
        e.printStackTrace();
    }
}