Example usage for java.lang String format

List of usage examples for java.lang String format

Introduction

In this page you can find the example usage for java.lang String format.

Prototype

public static String format(String format, Object... args) 

Source Link

Document

Returns a formatted string using the specified format string and arguments.

Usage

From source file:br.com.autonomiccs.cloudTraces.main.GoogleTracesToCloudTracesParser.java

public static void main(String[] args) {
    validateArguments(args);/*ww  w.  j  a v a  2s .c o m*/
    List<GoogleTrace> googleTraces = readAllGoogleTracesFromDataset(args[0]);

    logger.info(String.format("#Google traces loaded [%d]", googleTraces.size()));
    Collection<GoogleJob> googleJobs = buildTasksHierachyAndCreateJobList(googleTraces);
    buildJobsTaksByTimeMap(googleJobs);
    fillOutStartAndEndTimeOfJobs(googleJobs);
    calculateThePeakJobResourceUsage(googleJobs);

    GoogleJob biggestCpuUsageJob = googleJobs.iterator().next();
    GoogleJob biggestMemoryUsageJob = biggestCpuUsageJob;

    GoogleJob lowestCpuUsageJob = googleJobs.iterator().next();
    GoogleJob lowestMemoryUsageJob = lowestCpuUsageJob;

    for (GoogleJob googleJob : googleJobs) {
        if (biggestCpuUsageJob.getMaximumCpuUsageAtTime() < googleJob.getMaximumCpuUsageAtTime()) {
            biggestCpuUsageJob = googleJob;
        }
        if (biggestMemoryUsageJob.getMaximumMemoryUsageAtTime() < googleJob.getMaximumMemoryUsageAtTime()) {
            biggestMemoryUsageJob = googleJob;
        }

        if (lowestCpuUsageJob.getMaximumCpuUsageAtTime() > googleJob.getMaximumCpuUsageAtTime()) {
            lowestCpuUsageJob = googleJob;
        }
        if (lowestMemoryUsageJob.getMaximumMemoryUsageAtTime() > googleJob.getMaximumMemoryUsageAtTime()) {
            lowestMemoryUsageJob = googleJob;
        }
    }
    logger.info("Max job cpu usage: " + biggestCpuUsageJob);
    logger.info("Max job memory usage: " + biggestMemoryUsageJob);
    logger.info("Min job cpu usage: " + lowestCpuUsageJob);
    logger.info("Min job memory usage: " + lowestMemoryUsageJob);

    List<VirtualMachine> virtualMachines = createVmsToExecuteJobs(googleJobs);
    writeVmTracesToFile(virtualMachines);
}

From source file:com.twentyn.chemicalClassifier.Runner.java

public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new FileReader(args[0]));
    BufferedWriter writer = new BufferedWriter(new FileWriter(args[1]));

    try {/*from   w w  w  .  ja v a 2s .  c om*/
        Oscar oscar = new Oscar();

        String line = null;
        /* NOTE: this is exactly the wrong way to write a TSV reader.  Caveat emptor.
         * See http://tburette.github.io/blog/2014/05/25/so-you-want-to-write-your-own-CSV-code/
         * and then use org.apache.commons.csv.CSVParser instead.
         */
        while ((line = reader.readLine()) != null) {
            // TSV means split on tabs!  Nothing else will do.
            List<String> fields = Arrays.asList(line.split("\t"));
            // Choke if our invariants aren't satisfied.  We expect ever line to have a name and an InChI.
            if (fields.size() != 2) {
                throw new RuntimeException(
                        String.format("Found malformed line (all lines must have two fields: %s", line));
            }
            String name = fields.get(1);
            List<ResolvedNamedEntity> entities = oscar.findAndResolveNamedEntities(name);

            System.out.println("**********");
            System.out.println("Name: " + name);
            List<String> outputFields = new ArrayList<>(fields.size() + 1);
            outputFields.addAll(fields);
            if (entities.size() == 0) {
                System.out.println("No match");
                outputFields.add("noMatch");
            } else if (entities.size() == 1) {
                ResolvedNamedEntity entity = entities.get(0);
                NamedEntity ne = entity.getNamedEntity();
                if (ne.getStart() != 0 || ne.getEnd() != name.length()) {
                    System.out.println("Partial match");
                    printEntity(entity);
                    outputFields.add("partialMatch");
                } else {
                    System.out.println("Exact match");
                    printEntity(entity);
                    outputFields.add("exactMatch");
                    List<ChemicalStructure> structures = entity.getChemicalStructures(FormatType.STD_INCHI);
                    for (ChemicalStructure s : structures) {
                        outputFields.add(s.getValue());
                    }
                }
            } else { // Multiple matches found!
                System.out.println("Multiple matches");
                for (ResolvedNamedEntity e : entities) {
                    printEntity(e);
                }
                outputFields.add("multipleMatches");
            }

            writer.write(String.join("\t", outputFields));
            writer.newLine();
        }
    } finally {
        writer.flush();
        writer.close();
    }
}

From source file:at.alladin.rmbt.client.RMBTClientRunner.java

/**
 * @param args// w  w  w  .  jav  a 2  s.c o m
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static void main(final String[] args)
        throws IOException, InterruptedException, KeyManagementException, NoSuchAlgorithmException {
    final OptionParser parser = new OptionParser() {
        {
            acceptsAll(Arrays.asList("?", "help"), "show help");

            acceptsAll(Arrays.asList("h", "host"), "RMBT server IP or hostname (required)").withRequiredArg()
                    .ofType(String.class);

            acceptsAll(Arrays.asList("p", "port"), "RMBT server port (required)").withRequiredArg()
                    .ofType(Integer.class);

            acceptsAll(Arrays.asList("s", "ssl"), "use SSL/TLS");

            acceptsAll(Arrays.asList("ssl-no-verify"), "turn off SSL/TLS certificate validation");

            acceptsAll(Arrays.asList("t", "threads"), "number of threads (required when dev-mode)")
                    .withRequiredArg().ofType(Integer.class);

            acceptsAll(Arrays.asList("d", "duration"), "test duration in seconds (required when dev-mode)")
                    .withRequiredArg().ofType(Integer.class);

            acceptsAll(Arrays.asList("n", "ndt"), "run NDT after RMBT");

            acceptsAll(Arrays.asList("ndt-host"), "NDT host to use").withRequiredArg().ofType(String.class);

        }
    };

    System.out.println(String.format("=============== RMBTClient %s ===============",
            RevisionHelper.getVerboseRevision()));

    OptionSet options;
    try {
        options = parser.parse(args);
    } catch (final OptionException e) {
        System.out.println(
                String.format("error while parsing command line options: %s", e.getLocalizedMessage()));
        System.exit(1);
        return;
    }

    final String[] requiredArgs = { "h", "p" };

    if (options.has("ssl-no-verify"))
        SSLContext.setDefault(RMBTClient.getSSLContext(null, null));
    else
        SSLContext.setDefault(RMBTClient.getSSLContext("at/alladin/rmbt/crt/ca.pem",
                "at/alladin/rmbt/crt/controlserver.pem"));

    boolean reqArgMissing = false;
    if (!options.has("?"))
        for (final String arg : requiredArgs)
            if (!options.has(arg)) {
                reqArgMissing = true;
                System.out.println(String.format("ERROR: required argument '%s' is missing", arg));
            }
    if (options.has("?") || reqArgMissing) {
        System.out.println();
        parser.printHelpOn(System.out);
        System.exit(1);
        return;
    }

    final RMBTClient client;

    final String host = (String) options.valueOf("h");
    final int port = (Integer) options.valueOf("p");
    final boolean encryption = options.has("s") ? true : false;

    final ArrayList<String> geoInfo = null;

    final String uuid = "1cc2d6bb-2f07-4cb8-8fd6-fb5ffcf10cb0";

    final JSONObject additionalValues = new JSONObject();
    try {
        additionalValues.put("ndt", options.has("n"));
        additionalValues.put("plattform", "CLI");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    int numThreads = 0;
    int duration = 0;
    if (options.has("t"))
        numThreads = (Integer) options.valueOf("t");
    if (options.has("d"))
        duration = (Integer) options.valueOf("d");

    int numPings = 10;

    RMBTTestParameter overrideParams = null;
    if (numThreads > 0 || duration > 0)
        overrideParams = new RMBTTestParameter(null, 0, false, duration, numThreads, numPings);

    client = RMBTClient.getInstance(host, null, port, encryption, geoInfo, uuid, "DESKTOP",
            Config.RMBT_CLIENT_NAME, Config.RMBT_VERSION_NUMBER, overrideParams, null);

    if (client != null) {
        final TestResult result = client.runTest();

        if (result != null) {
            final JSONObject jsonResult = new JSONObject();
            try {
                jsonResult.put("network_type", "97");
                jsonResult.put("plattform", "CLI");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            client.sendResult(jsonResult);
        }

        client.shutdown();

        try {
            System.out.print("Starting QoS Test... ");
            TestSettings nnTestSettings = new TestSettings(client.getControlConnection().getStartTimeNs());
            QualityOfServiceTest nnTest = new QualityOfServiceTest(client, nnTestSettings);
            QoSResultCollector nnResult = nnTest.call();
            System.out.println("finished.");
            if (nnResult != null && nnTest.getStatus().equals(QoSTestEnum.QOS_FINISHED)) {
                System.out.print("Sending QoS results... ");
                client.sendQoSResult(nnResult);
                System.out.println("finished");
            } else {
                System.out.println("Error during QoS test.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (client.getStatus() != TestStatus.END)
            System.out.println("ERROR: " + client.getErrorMsg());
        else {
            if (options.has("n")) {
                System.out.println("\n\nStarting NDT...");

                String ndtHost = null;
                if (options.has("ndt-host"))
                    ndtHost = (String) options.valueOf("ndt-host");

                final NDTRunner ndtRunner = new NDTRunner(ndtHost);
                ndtRunner.runNDT(NdtTests.NETWORK_WIRED, ndtRunner.new UiServices() {
                    @Override
                    public void appendString(String str, int viewId) {
                        super.appendString(str, viewId);
                        //                            if (viewId == MAIN_VIEW)
                        System.out.println(str);
                    }

                    @Override
                    public void sendResults() {
                        System.out.println("sending NDT results...");
                        client.getControlConnection().sendNDTResult(this, null);
                    }
                });

                System.out.println("NDT finished.");
            }
        }
    }

}

From source file:com.google.infrastructuredmap.MapAndMarkdownExtractorMain.java

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

    Options options = new Options();
    options.addOption(ARG_KML, true, "path to KML input");
    options.addOption(ARG_MARKDOWN, true, "path to Markdown input");
    options.addOption(ARG_JSON_OUTPUT, true, "path to write json output");
    options.addOption(ARG_JSONP, true, "JSONP template to wrap output JSON data");

    CommandLineParser parser = new DefaultParser();
    CommandLine cli = parser.parse(options, args);

    // Extract map features from the input KML.
    MapData data = null;//  w w w  .j  av a 2  s. co  m
    try (InputStream in = openStream(cli.getOptionValue(ARG_KML))) {
        Kml kml = Kml.unmarshal(in);
        data = MapDataExtractor.extractMapData(kml);
    }

    // Extract project features from the input Markdown.
    Map<String, List<ProjectReference>> references = MarkdownReferenceExtractor
            .extractReferences(Paths.get(cli.getOptionValue(ARG_MARKDOWN)));
    for (MapFeature feature : data.features) {
        List<ProjectReference> referencesForId = references.get(feature.id);
        if (referencesForId == null) {
            throw new IllegalStateException("Unknown project reference: " + feature.id);
        }
        feature.projects = referencesForId;
    }

    // Write the resulting data to the output path.
    Gson gson = new Gson();
    try (FileWriter out = new FileWriter(cli.getOptionValue(ARG_JSON_OUTPUT))) {
        String json = gson.toJson(data);
        if (cli.hasOption(ARG_JSONP)) {
            json = String.format(cli.getOptionValue(ARG_JSONP), json);
        }
        out.write(json);
    }
}

From source file:com.basistech.rosette.dm.json.array.CompareJsons.java

public static void main(String[] args) throws Exception {
    File plenty = new File(args[0]);
    System.out.println(String.format("Original file length %d", plenty.length()));
    ObjectMapper inputMapper = AnnotatedDataModelModule.setupObjectMapper(new ObjectMapper());
    AnnotatedText[] texts = inputMapper.readValue(plenty, AnnotatedText[].class);
    System.out.println(String.format("%d documents", texts.length));
    runWithFormat(texts, new FactoryFactory() {
        @Override/*from w  ww  .  j  av  a 2  s  . co  m*/
        public JsonFactory newFactory() {
            return new JsonFactory();
        }
    }, "Plain");
    runWithFormat(texts, new FactoryFactory() {
        @Override
        public JsonFactory newFactory() {
            return new SmileFactory();
        }
    }, "SMILE");

    runWithFormat(texts, new FactoryFactory() {
        @Override
        public JsonFactory newFactory() {
            return new CBORFactory();
        }
    }, "CBOR");
}

From source file:com.github.fritaly.graphml4j.samples.GradleDependencies.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println(String.format("%s <output-file>", GradleDependencies.class.getSimpleName()));
        System.exit(1);//from   w  w  w .ja v a 2  s  . co m
    }

    final File file = new File(args[0]);

    System.out.println("Writing GraphML file to " + file.getAbsolutePath() + " ...");

    FileWriter fileWriter = null;
    GraphMLWriter graphWriter = null;
    Reader reader = null;
    LineNumberReader lineReader = null;

    try {
        fileWriter = new FileWriter(file);
        graphWriter = new GraphMLWriter(fileWriter);

        // Customize the rendering of nodes
        final NodeStyle nodeStyle = graphWriter.getNodeStyle();
        nodeStyle.setWidth(250.0f);

        graphWriter.setNodeStyle(nodeStyle);

        // The dependency graph has been generated by Gradle with the
        // command "gradle dependencies". The output of this command has
        // been saved to a text file which will be parsed to rebuild the
        // dependency graph
        reader = new InputStreamReader(GradleDependencies.class.getResourceAsStream("gradle-dependencies.txt"));
        lineReader = new LineNumberReader(reader);

        String line = null;

        // Stack containing the node identifiers per depth inside the
        // dependency graph (the topmost dependency is the first one in the
        // stack)
        final Stack<String> parentIds = new Stack<String>();

        // Open the graph
        graphWriter.graph();

        // Map storing the node identifiers per label
        final Map<String, String> nodeIdsByLabel = new TreeMap<String, String>();

        while ((line = lineReader.readLine()) != null) {
            // Determine the depth of the current dependency inside the
            // graph. The depth can be inferred from the indentation used by
            // Gradle. Each level of depth adds 5 more characters of
            // indentation
            final int initialLength = line.length();

            // Remove the strings used by Gradle to indent dependencies
            line = StringUtils.replace(line, "+--- ", "");
            line = StringUtils.replace(line, "|    ", "");
            line = StringUtils.replace(line, "\\--- ", "");
            line = StringUtils.replace(line, "     ", "");

            // The depth can easily be inferred now
            final int depth = (initialLength - line.length()) / 5;

            // Remove unnecessary node ids
            while (depth <= parentIds.size()) {
                parentIds.pop();
            }

            // Compute a nice label from the dependency (group, artifact,
            // version) tuple
            final String label = computeLabel(line);

            // Has this dependency already been added to the graph ?
            if (!nodeIdsByLabel.containsKey(label)) {
                // No, add the node
                nodeIdsByLabel.put(label, graphWriter.node(label));
            }

            final String nodeId = nodeIdsByLabel.get(label);

            parentIds.push(nodeId);

            if (parentIds.size() > 1) {
                // Generate an edge between the current node and its parent
                graphWriter.edge(parentIds.get(parentIds.size() - 2), nodeId);
            }
        }

        // Close the graph
        graphWriter.closeGraph();

        System.out.println("Done");
    } finally {
        // Calling GraphMLWriter.close() is necessary to dispose the underlying resources
        graphWriter.close();
        fileWriter.close();
        lineReader.close();
        reader.close();
    }
}

From source file:com.act.lcms.db.io.ExportPlateCompositionFromDB.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption(Option.builder("b").argName("barcode").desc("The barcode of the plate to print").hasArg()
            .longOpt("barcode").build());
    opts.addOption(Option.builder("n").argName("name").desc("The name of the plate to print").hasArg()
            .longOpt("name").build());

    opts.addOption(Option.builder("o").argName("output file").desc(
            "An output file to which to write this plate's composition table (writes to stdout if omitted")
            .hasArg().longOpt("output-file").build());

    // DB connection options.
    opts.addOption(Option.builder().argName("database url")
            .desc("The url to use when connecting to the LCMS db").hasArg().longOpt("db-url").build());
    opts.addOption(Option.builder("u").argName("database user").desc("The LCMS DB user").hasArg()
            .longOpt("db-user").build());
    opts.addOption(Option.builder("p").argName("database password").desc("The LCMS DB password").hasArg()
            .longOpt("db-pass").build());
    opts.addOption(Option.builder("H").argName("database host")
            .desc(String.format("The LCMS DB host (default = %s)", DB.DEFAULT_HOST)).hasArg().longOpt("db-host")
            .build());/*from w  ww .jav a 2s  .c  o m*/
    opts.addOption(Option.builder("P").argName("database port")
            .desc(String.format("The LCMS DB port (default = %d)", DB.DEFAULT_PORT)).hasArg().longOpt("db-port")
            .build());
    opts.addOption(Option.builder("N").argName("database name")
            .desc(String.format("The LCMS DB name (default = %s)", DB.DEFAULT_DB_NAME)).hasArg()
            .longOpt("db-name").build());

    // Everybody needs a little help from their friends.
    opts.addOption(
            Option.builder("h").argName("help").desc("Prints this help message").longOpt("help").build());

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        new HelpFormatter().printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        new HelpFormatter().printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), opts, true);
        return;
    }

    if (!cl.hasOption("b") && !cl.hasOption("n")) {
        System.err.format("Must specify either plate barcode or plate name.");
        new HelpFormatter().printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    DB db = null;
    try {
        if (cl.hasOption("db-url")) {
            db = new DB().connectToDB(cl.getOptionValue("db-url"));
        } else {
            Integer port = null;
            if (cl.getOptionValue("P") != null) {
                port = Integer.parseInt(cl.getOptionValue("P"));
            }
            db = new DB().connectToDB(cl.getOptionValue("H"), port, cl.getOptionValue("N"),
                    cl.getOptionValue("u"), cl.getOptionValue("p"));
        }

        Writer writer = null;
        if (cl.hasOption("o")) {
            writer = new FileWriter(cl.getOptionValue("o"));
        } else {
            writer = new OutputStreamWriter(System.out);
        }

        PlateCompositionWriter cw = new PlateCompositionWriter();
        if (cl.hasOption("b")) {
            cw.writePlateCompositionByBarcode(db, cl.getOptionValue("b"), writer);
        } else if (cl.hasOption("n")) {
            cw.writePlateCompositionByName(db, cl.getOptionValue("n"), writer);
        }

        writer.close();
    } finally {
        if (db != null) {
            db.close();
        }
    }
}

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

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

    options.addOption("i1", null, true, "Input file 1");
    options.addOption("i2", null, true, "Input file 2");
    options.addOption("o", null, true, "Output file");

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

    try {//from   www . j  a  va  2  s.  c o m
        CommandLine cmd = parser.parse(options, args);

        InputStream input1 = null, input2 = null;

        if (cmd.hasOption("i1")) {
            input1 = CompressUtils.createInputStream(cmd.getOptionValue("i1"));
        } else {
            Usage("Specify 'Input file 1'");
        }
        if (cmd.hasOption("i2")) {
            input2 = CompressUtils.createInputStream(cmd.getOptionValue("i2"));
        } else {
            Usage("Specify 'Input file 2'");
        }

        HashSet<String> hSubj = new HashSet<String>();

        BufferedWriter out = null;

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

            out = new BufferedWriter(new OutputStreamWriter(CompressUtils.createOutputStream(outFile)));
        } else {
            Usage("Specify 'Output file'");
        }

        XmlIterator inpIter2 = new XmlIterator(input2, YahooAnswersReader.DOCUMENT_TAG);

        int docNum = 1;
        for (String oneRec = inpIter2.readNext(); !oneRec.isEmpty(); oneRec = inpIter2.readNext(), ++docNum) {
            if (docNum % 10000 == 0) {
                System.out.println(String.format(
                        "Loaded and memorized questions for %d documents from the second input file", docNum));
            }
            ParsedQuestion q = YahooAnswersParser.parse(oneRec, false);
            hSubj.add(q.mQuestion);
        }

        XmlIterator inpIter1 = new XmlIterator(input1, YahooAnswersReader.DOCUMENT_TAG);

        System.out.println("=============================================");
        System.out.println("Memoization is done... now let's diff!!!");
        System.out.println("=============================================");

        docNum = 1;
        int skipOverlapQty = 0, skipErrorQty = 0;
        for (String oneRec = inpIter1.readNext(); !oneRec.isEmpty(); ++docNum, oneRec = inpIter1.readNext()) {
            if (docNum % 10000 == 0) {
                System.out.println(String.format("Processed %d documents from the first input file", docNum));
            }

            oneRec = oneRec.trim() + System.getProperty("line.separator");

            ParsedQuestion q = null;
            try {
                q = YahooAnswersParser.parse(oneRec, false);
            } catch (Exception e) {
                // If <bestanswer>...</bestanswer> is missing we may end up here...
                // This is a bit funny, because this element is supposed to be mandatory,
                // but it's not.
                System.err.println("Skipping due to parsing error, exception: " + e);
                skipErrorQty++;
                continue;
            }
            if (hSubj.contains(q.mQuestion.trim())) {
                //System.out.println(String.format("Skipping uri='%s', question='%s'", q.mQuestUri, q.mQuestion));
                skipOverlapQty++;
                continue;
            }

            out.write(oneRec);
        }
        System.out.println(
                String.format("Processed %d documents, skipped because of overlap/errors %d/%d documents",
                        docNum - 1, skipOverlapQty, skipErrorQty));
        out.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:com.incapture.rapgen.persistence.GenPersistence.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("o", true, "Output root folder for kernel files");

    options.addOption("g", true, "The type of grammar to generate, current options are 'SDK' or 'API'");

    options.addOption("mainApiFile", true, "FileName specifying the api");

    CommandLineParser cparser = new PosixParser();
    try {//from w ww .ja  va 2  s. co m
        CommandLine cmd = cparser.parse(options, args);
        String mainApiFile = cmd.getOptionValue("mainApiFile");
        String outputFolder = cmd.getOptionValue('o');
        GenType genType = GenType.valueOf(cmd.getOptionValue('g'));
        StringTemplateGroup templateLib = loadTemplates(genType);

        List<StorableAttributes> storableAttributes = parseApiFiles(cmd, mainApiFile, templateLib, genType);
        StorableSerDeserRepo mappersRepo = StorableMappersLoader.loadSerDeserHelpers();
        log.info(String.format("Got %s storable mapper(s)", mappersRepo.getAll().size()));

        Generator generator = new Generator(templateLib);
        Map<String, StringTemplate> pathToTemplate = generator.generatePersistenceFiles(storableAttributes,
                mappersRepo);

        log.info(String.format("Writing persistence files in [%s]", outputFolder));
        OutputWriter.writeTemplates(outputFolder, pathToTemplate);

    } catch (ParseException e) {
        System.err.println("Error parsing command line - " + e.getMessage());
        System.out.println("Usage: " + options.toString());
    } catch (IOException | RecognitionException e) {
        System.err.println("Error running GenApi: " + ExceptionToString.format(e));
    }
}

From source file:de.zazaz.iot.bosch.indego.util.IndegoMqttAdapter.java

public static void main(String[] args) {
    System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-normal.xml");

    Options options = new Options();

    StringBuilder commandList = new StringBuilder();
    for (DeviceCommand cmd : DeviceCommand.values()) {
        if (commandList.length() > 0) {
            commandList.append(", ");
        }/*from w  w w. j ava 2s . co  m*/
        commandList.append(cmd.toString());
    }

    options.addOption(Option //
            .builder("c") //
            .longOpt("config") //
            .desc("The configuration file to use") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("d") //
            .longOpt("debug") //
            .desc("Logs more details") //
            .build());
    options.addOption(Option //
            .builder("?") //
            .longOpt("help") //
            .desc("Prints this help") //
            .build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmds = null;
    try {
        cmds = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        System.err.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(IndegoMqttAdapter.class.getName(), options);
        System.exit(1);
        return;
    }

    if (cmds.hasOption("?")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CmdLineTool.class.getName(), options);
        return;
    }

    if (cmds.hasOption("d")) {
        System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-debug.xml");
    }

    String configFileName = cmds.getOptionValue('c');
    File configFile = new File(configFileName);

    if (!configFile.exists()) {
        System.err.println(String.format("The specified config file (%s) does not exist", configFileName));
        System.err.println();
        System.exit(2);
        return;
    }

    Properties properties = new Properties();
    try (InputStream in = new FileInputStream(configFile)) {
        properties.load(in);
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
        System.err.println(String.format("Was not able to load the properties file (%s)", configFileName));
        System.err.println();
    }

    MqttIndegoAdapterConfiguration config = new MqttIndegoAdapterConfiguration();
    config.setIndegoBaseUrl(properties.getProperty("indego.mqtt.device.base-url"));
    config.setIndegoUsername(properties.getProperty("indego.mqtt.device.username"));
    config.setIndegoPassword(properties.getProperty("indego.mqtt.device.password"));
    config.setMqttBroker(properties.getProperty("indego.mqtt.broker.connection"));
    config.setMqttClientId(properties.getProperty("indego.mqtt.broker.client-id"));
    config.setMqttUsername(properties.getProperty("indego.mqtt.broker.username"));
    config.setMqttPassword(properties.getProperty("indego.mqtt.broker.password"));
    config.setMqttTopicRoot(properties.getProperty("indego.mqtt.broker.topic-root"));
    config.setPollingIntervalMs(Integer.parseInt(properties.getProperty("indego.mqtt.polling-interval-ms")));

    MqttIndegoAdapter adapter = new MqttIndegoAdapter(config);
    adapter.startup();
}