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:com.p2p.peercds.cli.TorrentMain.java

/**
 * Torrent reader and creator./*from ww  w .  j  av  a 2 s  .  c  o m*/
 *
 * <p>
 * You can use the {@code main()} function of this class to read or create
 * torrent files. See usage for details.
 * </p>
 *
 */
public static void main(String[] args) {
    BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n")));

    CmdLineParser parser = new CmdLineParser();
    CmdLineParser.Option help = parser.addBooleanOption('h', "help");
    CmdLineParser.Option filename = parser.addStringOption('t', "torrent");
    CmdLineParser.Option create = parser.addBooleanOption('c', "create");
    CmdLineParser.Option announce = parser.addStringOption('a', "announce");

    try {
        parser.parse(args);
    } catch (CmdLineParser.OptionException oe) {
        System.err.println(oe.getMessage());
        usage(System.err);
        System.exit(1);
    }

    // Display help and exit if requested
    if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) {
        usage(System.out);
        System.exit(0);
    }

    String filenameValue = (String) parser.getOptionValue(filename);
    if (filenameValue == null) {
        usage(System.err, "Torrent file must be provided!");
        System.exit(1);
    }

    Boolean createFlag = (Boolean) parser.getOptionValue(create);

    //For repeated announce urls
    @SuppressWarnings("unchecked")
    Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce);

    String[] otherArgs = parser.getRemainingArgs();

    if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) {
        usage(System.err,
                "Announce URL and a file or directory must be " + "provided to create a torrent file!");
        System.exit(1);
    }

    OutputStream fos = null;
    try {
        if (Boolean.TRUE.equals(createFlag)) {
            if (filenameValue != null) {
                fos = new FileOutputStream(filenameValue);
            } else {
                fos = System.out;
            }

            //Process the announce URLs into URIs
            List<URI> announceURIs = new ArrayList<URI>();
            for (String url : announceURLs) {
                announceURIs.add(new URI(url));
            }

            //Create the announce-list as a list of lists of URIs
            //Assume all the URI's are first tier trackers
            List<List<URI>> announceList = new ArrayList<List<URI>>();
            announceList.add(announceURIs);

            File source = new File(otherArgs[0]);
            if (!source.exists() || !source.canRead()) {
                throw new IllegalArgumentException(
                        "Cannot access source file or directory " + source.getName());
            }

            String creator = String.format("%s (ttorrent)", System.getProperty("user.name"));

            Torrent torrent = null;
            if (source.isDirectory()) {
                File[] files = source.listFiles(Constants.hiddenFilesFilter);
                Arrays.sort(files);
                torrent = Torrent.create(source, Arrays.asList(files), announceList, creator);
            } else {
                torrent = Torrent.create(source, announceList, creator);

            }

            torrent.save(fos);
        } else {
            Torrent.load(new File(filenameValue), true);
        }
    } catch (Exception e) {
        logger.error("{}", e.getMessage(), e);
        System.exit(2);
    } finally {
        if (fos != System.out) {
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:com.puppycrawl.tools.checkstyle.Main.java

/**
 * Loops over the files specified checking them for errors. The exit code
 * is the number of errors found in all the files.
 * @param args the command line arguments.
 * @throws FileNotFoundException if there is a problem with files access
 **///from  w ww  .j  ava  2s.  c o  m
public static void main(String... args) throws FileNotFoundException {
    int errorCounter = 0;
    boolean cliViolations = false;
    // provide proper exit code based on results.
    final int exitWithCliViolation = -1;
    int exitStatus = 0;

    try {
        //parse CLI arguments
        final CommandLine commandLine = parseCli(args);

        // show version and exit if it is requested
        if (commandLine.hasOption(OPTION_V_NAME)) {
            System.out.println("Checkstyle version: " + Main.class.getPackage().getImplementationVersion());
            exitStatus = 0;
        } else {
            // return error if something is wrong in arguments
            final List<String> messages = validateCli(commandLine);
            cliViolations = !messages.isEmpty();
            if (cliViolations) {
                exitStatus = exitWithCliViolation;
                errorCounter = 1;
                for (String message : messages) {
                    System.out.println(message);
                }
            } else {
                // create config helper object
                final CliOptions config = convertCliToPojo(commandLine);
                // run Checker
                errorCounter = runCheckstyle(config);
                exitStatus = errorCounter;
            }
        }
    } catch (ParseException pex) {
        // something wrong with arguments - print error and manual
        cliViolations = true;
        exitStatus = exitWithCliViolation;
        errorCounter = 1;
        System.out.println(pex.getMessage());
        printUsage();
    } catch (CheckstyleException e) {
        exitStatus = EXIT_WITH_CHECKSTYLE_EXCEPTION_CODE;
        errorCounter = 1;
        printMessageAndCause(e);
    } finally {
        // return exit code base on validation of Checker
        if (errorCounter != 0 && !cliViolations) {
            System.out.println(String.format("Checkstyle ends with %d errors.", errorCounter));
        }
        if (exitStatus != 0) {
            System.exit(exitStatus);
        }
    }
}

From source file:com.quest.orahive.HiveJdbcClient.java

public static void main(String[] args) {

    long mainStartTime = System.nanoTime();

    Configuration conf = new Configuration();
    Options options = new Options();

    parseGeneralOptions(options, conf, args); //<- log4j will now be configured.

    showWelcomeMessage();//from ww w  . ja v a2s.  c  om

    if (args.length == 0 || userWantsToSeeHelp(args)) {
        printCommandLineHelp(options);
        System.exit(0);
    }

    checkConfiguration(conf);

    OraHiveOptions opts = getOraHiveOptions(conf);
    OraHiveCounters counters = new OraHiveCounters();

    try {
        Connection hiveConnection = createHiveJdbcConnection(opts.hiveJdbcUrl, opts.hiveUserName,
                opts.hivePassword);
        try {
            Connection oracleConnection = createOracleJdbcConnection(opts.oracleJdbcUrl, opts.oracleUserName,
                    opts.oraclePassword);
            try {
                initializeOracleSession(oracleConnection, opts);

                Statement statement = hiveConnection.createStatement();

                LOG.info("Running: " + opts.hql);

                // Execute Hive Query...
                long start = System.nanoTime();
                ResultSet hiveResultSet = statement.executeQuery(opts.hql);
                counters.hiveQueryTimeNanoSec = System.nanoTime() - start;

                // Get column definitions from the Hive resultset...
                List<OracleTableColumn> oracleColumns = getOracleTableColumnsForHiveResults(hiveResultSet);

                if (opts.exportMode.equals(Constants.ExportMode.CREATE)) {
                    // Create an Oracle table based on the columns in the Hive resultset...
                    createOracleTableWithRetry(opts, oracleColumns, oracleConnection); //<- Lets the user retry this if it fails.
                }

                // Generate the Oracle insert statement...
                String insertSql = generateOracleInsertStatement(opts, oracleColumns);

                // Insert the Hive data into Oracle...
                insertHiveResultsIntoOracleTable(opts, insertSql, oracleColumns, oracleConnection,
                        hiveResultSet, counters);

                //hiveResultSet.close();   //<- Not required/supported
                statement.close();
            } finally {
                oracleConnection.close();
            }
        } finally {
            hiveConnection.close();
        }

    } catch (SQLException ex) {
        LOG.error(String.format("An error occurred in %s.", Constants.ORAHIVE_PRODUCT_NAME), ex);
    }

    LOG.info(String.format("\n\n********************************************************************\n"
            + "\tTotal time                        : %s sec.\n" + "\tNumber of records processed       : %s\n"
            + "\tTime spent executing HQL statement: %s sec.\n"
            + "\tTime spent fetching Hive data     : %s sec.\n"
            + "\tTime spent inserting into Oracle  : %s sec.",
            (System.nanoTime() - mainStartTime) / Math.pow(10, 9), counters.rowsProcessed,
            counters.hiveQueryTimeNanoSec / Math.pow(10, 9), counters.hiveFetchTimeNanoSec / Math.pow(10, 9),
            counters.oracleInsertTimeNanoSec / Math.pow(10, 9)));

}

From source file:com.github.jcustenborder.kafka.connect.spooldir.SchemaGenerator.java

public static void main(String... args) throws Exception {
    ArgumentParser parser = ArgumentParsers.newArgumentParser("CsvSchemaGenerator").defaultHelp(true)
            .description("Generate a schema based on a file.");
    parser.addArgument("-t", "--type").required(true).choices("csv", "json")
            .help("The type of generator to use.");
    parser.addArgument("-c", "--config").type(File.class);
    parser.addArgument("-f", "--file").type(File.class).required(true)
            .help("The data file to generate the schema from.");
    parser.addArgument("-i", "--id").nargs("*").help("Field(s) to use as an identifier.");
    parser.addArgument("-o", "--output").type(File.class)
            .help("Output location to write the configuration to. Stdout is default.");

    Namespace ns = null;/* ww  w .j  a va 2  s . c o m*/

    try {
        ns = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
        parser.handleError(ex);
        System.exit(1);
    }

    File inputFile = ns.get("file");
    List<String> ids = ns.getList("id");
    if (null == ids) {
        ids = ImmutableList.of();
    }

    Map<String, Object> settings = new LinkedHashMap<>();

    File inputPropertiesFile = ns.get("config");
    if (null != inputPropertiesFile) {
        Properties inputProperties = new Properties();

        try (FileInputStream inputStream = new FileInputStream(inputPropertiesFile)) {
            inputProperties.load(inputStream);
        }
        for (String s : inputProperties.stringPropertyNames()) {
            Object v = inputProperties.getProperty(s);
            settings.put(s, v);
        }
    }

    final SchemaGenerator generator;
    final String type = ns.getString("type");

    if ("csv".equalsIgnoreCase(type)) {
        generator = new CsvSchemaGenerator(settings);
    } else if ("json".equalsIgnoreCase(type)) {
        generator = new JsonSchemaGenerator(settings);
    } else {
        throw new UnsupportedOperationException(
                String.format("'%s' is not a supported schema generator type", type));
    }

    Map.Entry<Schema, Schema> kvp = generator.generate(inputFile, ids);

    Properties properties = new Properties();
    properties.putAll(settings);
    properties.setProperty(SpoolDirSourceConnectorConfig.KEY_SCHEMA_CONF,
            ObjectMapperFactory.INSTANCE.writeValueAsString(kvp.getKey()));
    properties.setProperty(SpoolDirSourceConnectorConfig.VALUE_SCHEMA_CONF,
            ObjectMapperFactory.INSTANCE.writeValueAsString(kvp.getValue()));

    String output = ns.getString("output");
    final String comment = "Configuration was dynamically generated. Please verify before submitting.";

    if (Strings.isNullOrEmpty(output)) {
        properties.store(System.out, comment);
    } else {
        try (FileOutputStream outputStream = new FileOutputStream(output)) {
            properties.store(outputStream, comment);
        }
    }
}

From source file:io.druid.server.sql.SQLRunner.java

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

    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("v", false, "verbose");
    options.addOption("e", "host", true, "endpoint [hostname:port]");

    CommandLine cmd = new GnuParser().parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SQLRunner", options);
        System.exit(2);//from ww w . j  a  v a 2 s .c  o m
    }

    String hostname = cmd.getOptionValue("e", "localhost:8080");
    String sql = cmd.getArgs().length > 0 ? cmd.getArgs()[0] : STATEMENT;

    ObjectMapper objectMapper = new DefaultObjectMapper();
    ObjectWriter jsonWriter = objectMapper.writerWithDefaultPrettyPrinter();

    CharStream stream = new ANTLRInputStream(sql);
    DruidSQLLexer lexer = new DruidSQLLexer(stream);
    TokenStream tokenStream = new CommonTokenStream(lexer);
    DruidSQLParser parser = new DruidSQLParser(tokenStream);
    lexer.removeErrorListeners();
    parser.removeErrorListeners();

    lexer.addErrorListener(ConsoleErrorListener.INSTANCE);
    parser.addErrorListener(ConsoleErrorListener.INSTANCE);

    try {
        DruidSQLParser.QueryContext queryContext = parser.query();
        if (parser.getNumberOfSyntaxErrors() > 0)
            throw new IllegalStateException();
        //      parser.setBuildParseTree(true);
        //      System.err.println(q.toStringTree(parser));
    } catch (Exception e) {
        String msg = e.getMessage();
        if (msg != null)
            System.err.println(e);
        System.exit(1);
    }

    final Query query;
    final TypeReference typeRef;
    boolean groupBy = false;
    if (parser.groupByDimensions.isEmpty()) {
        query = Druids.newTimeseriesQueryBuilder().dataSource(parser.getDataSource())
                .aggregators(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .postAggregators(parser.postAggregators).intervals(parser.intervals)
                .granularity(parser.granularity).filters(parser.filter).build();

        typeRef = new TypeReference<List<Result<TimeseriesResultValue>>>() {
        };
    } else {
        query = GroupByQuery.builder().setDataSource(parser.getDataSource())
                .setAggregatorSpecs(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .setPostAggregatorSpecs(parser.postAggregators).setInterval(parser.intervals)
                .setGranularity(parser.granularity).setDimFilter(parser.filter)
                .setDimensions(new ArrayList<DimensionSpec>(parser.groupByDimensions.values())).build();

        typeRef = new TypeReference<List<Row>>() {
        };
        groupBy = true;
    }

    String queryStr = jsonWriter.writeValueAsString(query);
    if (cmd.hasOption("v"))
        System.err.println(queryStr);

    URL url = new URL(String.format("http://%s/druid/v2/?pretty", hostname));
    final URLConnection urlConnection = url.openConnection();
    urlConnection.addRequestProperty("content-type", MediaType.APPLICATION_JSON);
    urlConnection.getOutputStream().write(StringUtils.toUtf8(queryStr));
    BufferedReader stdInput = new BufferedReader(
            new InputStreamReader(urlConnection.getInputStream(), Charsets.UTF_8));

    Object res = objectMapper.readValue(stdInput, typeRef);

    Joiner tabJoiner = Joiner.on("\t");

    if (groupBy) {
        List<Row> rows = (List<Row>) res;
        Iterable<String> dimensions = Iterables.transform(parser.groupByDimensions.values(),
                new Function<DimensionSpec, String>() {
                    @Override
                    public String apply(@Nullable DimensionSpec input) {
                        return input.getOutputName();
                    }
                });

        System.out.println(
                tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), dimensions, parser.fields)));
        for (final Row r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(
                    Lists.newArrayList(parser.granularity.toDateTime(r.getTimestampFromEpoch())),
                    Iterables.transform(parser.groupByDimensions.values(),
                            new Function<DimensionSpec, String>() {
                                @Override
                                public String apply(@Nullable DimensionSpec input) {
                                    return Joiner.on(",").join(r.getDimension(input.getOutputName()));
                                }
                            }),
                    Iterables.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getFloatMetric(input);
                        }
                    }))));
        }
    } else {
        List<Result<TimeseriesResultValue>> rows = (List<Result<TimeseriesResultValue>>) res;
        System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), parser.fields)));
        for (final Result<TimeseriesResultValue> r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList(r.getTimestamp()),
                    Lists.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getValue().getMetric(input);
                        }
                    }))));
        }
    }

    CloseQuietly.close(stdInput);
}

From source file:com.mmounirou.spotirss.SpotiRss.java

/**
 * @param args//from  w  ww  .j  av  a2s.co m
 * @throws IOException 
 * @throws ClassNotFoundException 
 * @throws IllegalAccessException 
 * @throws InstantiationException 
 * @throws SpotifyClientException 
 * @throws ChartRssException 
 * @throws SpotifyException 
 */
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException,
        ClassNotFoundException, SpotifyClientException {
    if (args.length == 0) {
        System.err.println("usage : java -jar spotiboard.jar <charts-folder>");
        return;
    }

    Properties connProperties = new Properties();
    InputStream inStream = SpotiRss.class.getResourceAsStream("/spotify-server.properties");
    try {
        connProperties.load(inStream);
    } finally {
        IOUtils.closeQuietly(inStream);
    }

    String host = connProperties.getProperty("host");
    int port = Integer.parseInt(connProperties.getProperty("port"));
    String user = connProperties.getProperty("user");

    final SpotifyClient spotifyClient = new SpotifyClient(host, port, user);
    final Map<String, Playlist> playlistsByTitle = getPlaylistsByTitle(spotifyClient);

    final File outputDir = new File(args[0]);
    outputDir.mkdirs();
    TrackCache cache = new TrackCache();
    try {

        for (String strProvider : PROVIDERS) {
            String providerClassName = EntryToTrackConverter.class.getPackage().getName() + "."
                    + StringUtils.capitalize(strProvider);
            final EntryToTrackConverter converter = (EntryToTrackConverter) SpotiRss.class.getClassLoader()
                    .loadClass(providerClassName).newInstance();
            Iterable<String> chartsRss = getCharts(strProvider);
            final File resultDir = new File(outputDir, strProvider);
            resultDir.mkdir();

            final SpotifyHrefQuery hrefQuery = new SpotifyHrefQuery(cache);
            Iterable<String> results = FluentIterable.from(chartsRss).transform(new Function<String, String>() {

                @Override
                @Nullable
                public String apply(@Nullable String chartRss) {

                    try {

                        long begin = System.currentTimeMillis();
                        ChartRss bilboardChartRss = ChartRss.getInstance(chartRss, converter);
                        Map<Track, String> trackHrefs = hrefQuery.getTrackHrefs(bilboardChartRss.getSongs());

                        String strTitle = bilboardChartRss.getTitle();
                        File resultFile = new File(resultDir, strTitle);
                        List<String> lines = Lists.newLinkedList(FluentIterable.from(trackHrefs.keySet())
                                .transform(Functions.toStringFunction()));
                        lines.addAll(trackHrefs.values());
                        FileUtils.writeLines(resultFile, Charsets.UTF_8.displayName(), lines);

                        Playlist playlist = playlistsByTitle.get(strTitle);
                        if (playlist != null) {
                            playlist.getTracks().clear();
                            playlist.getTracks().addAll(trackHrefs.values());
                            spotifyClient.patch(playlist);
                            LOGGER.info(String.format("%s chart exported patched", strTitle));
                        }

                        LOGGER.info(String.format("%s chart exported in %s in %d s", strTitle,
                                resultFile.getAbsolutePath(),
                                (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - begin)));

                    } catch (Exception e) {
                        LOGGER.error(String.format("fail to export %s charts", chartRss), e);
                    }

                    return "";
                }
            });

            // consume iterables
            Iterables.size(results);

        }

    } finally {
        cache.close();
    }

}

From source file:org.datagator.tools.importer.Main.java

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

    int columnHeaders = 0; // cli input
    int rowHeaders = 0; // cli input

    try {//from   www  . jav  a2  s. c o  m
        CommandLine cmds = parser.parse(opts, args);
        if (cmds.hasOption("filter")) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
        if (cmds.hasOption("layout")) {
            String[] layout = cmds.getOptionValues("layout");
            if ((layout == null) || (layout.length != 2)) {
                throw new IllegalArgumentException("Bad layout.");
            }
            try {
                columnHeaders = Integer.valueOf(layout[0]);
                rowHeaders = Integer.valueOf(layout[1]);
                if ((columnHeaders < 0) || (rowHeaders < 0)) {
                    throw new IllegalArgumentException("Bad layout.");
                }
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException(ex);
            }
        }
        if (cmds.hasOption("help")) {
            help.printHelp("importer", opts, true);
            System.exit(EX_OK);
        }
        // positional arguments, i.e., input file name(s)
        args = cmds.getArgs();
    } catch (ParseException ex) {
        throw new IllegalArgumentException(ex);
    } catch (IllegalArgumentException ex) {
        help.printHelp("importer", opts, true);
        throw ex;
    }

    JsonGenerator jg = json.createGenerator(System.out, JsonEncoding.UTF8);
    jg.setPrettyPrinter(new StandardPrinter());

    final Extractor extractor;

    if (args.length == 1) {
        extractor = new FileExtractor(new File(args[0]));
    } else if (args.length > 1) {
        throw new UnsupportedOperationException("Not supported yet.");
    } else {
        throw new IllegalArgumentException("Missing input.");
    }

    int columnsCount = -1;
    int matrixCount = 0;

    ArrayDeque<String> stack = new ArrayDeque<String>();

    AtomType token = extractor.nextAtom();
    while (token != null) {
        switch (token) {
        case FLOAT:
        case INTEGER:
        case STRING:
        case NULL:
            jg.writeObject(extractor.getCurrentAtomData());
            break;
        case START_RECORD:
            jg.writeStartArray();
            break;
        case END_RECORD:
            int _numFields = (Integer) extractor.getCurrentAtomData();
            if (columnsCount < 0) {
                columnsCount = _numFields;
            } else if (columnsCount != _numFields) {
                throw new RuntimeException(String.format("row %s has different length than previous rows",
                        String.valueOf(_numFields - 1)));
            }
            jg.writeEndArray();
            break;
        case START_GROUP:
            stack.push(String.valueOf(extractor.getCurrentAtomData()));
            jg.writeStartObject();
            jg.writeStringField("kind", "datagator#Matrix");
            jg.writeNumberField("columnHeaders", columnHeaders);
            jg.writeNumberField("rowHeaders", rowHeaders);
            jg.writeFieldName("rows");
            jg.writeStartArray();
            break;
        case END_GROUP:
            int rowsCount = (Integer) extractor.getCurrentAtomData();
            if (rowsCount == 0) {
                jg.writeStartArray();
                jg.writeEndArray();
                rowsCount = 1;
                columnsCount = 0;
            }
            jg.writeEndArray();
            jg.writeNumberField("rowsCount", rowsCount);
            jg.writeNumberField("columnsCount", columnsCount);
            jg.writeEndObject();
            matrixCount += 1;
            stack.pop();
            break;
        default:
            break;
        }
        token = extractor.nextAtom();
    }

    jg.close();

    System.exit(EX_OK);
}

From source file:com.turn.ttorrent.cli.TorrentMain.java

/**
 * Torrent reader and creator./*from w  ww  .  j  a  va  2s.  c  o  m*/
 *
 * <p>
 * You can use the {@code main()} function of this class to read or create
 * torrent files. See usage for details.
 * </p>
 *
 */
public static void main(String[] args) {
    BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n")));

    CmdLineParser parser = new CmdLineParser();
    CmdLineParser.Option help = parser.addBooleanOption('h', "help");
    CmdLineParser.Option filename = parser.addStringOption('t', "torrent");
    CmdLineParser.Option create = parser.addBooleanOption('c', "create");
    CmdLineParser.Option pieceLength = parser.addIntegerOption('l', "length");
    CmdLineParser.Option announce = parser.addStringOption('a', "announce");

    try {
        parser.parse(args);
    } catch (CmdLineParser.OptionException oe) {
        System.err.println(oe.getMessage());
        usage(System.err);
        System.exit(1);
    }

    // Display help and exit if requested
    if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) {
        usage(System.out);
        System.exit(0);
    }

    String filenameValue = (String) parser.getOptionValue(filename);
    if (filenameValue == null) {
        usage(System.err, "Torrent file must be provided!");
        System.exit(1);
    }

    Integer pieceLengthVal = (Integer) parser.getOptionValue(pieceLength);
    if (pieceLengthVal == null) {
        pieceLengthVal = Torrent.DEFAULT_PIECE_LENGTH;
    } else {
        pieceLengthVal = pieceLengthVal * 1024;
    }
    logger.info("Using piece length of {} bytes.", pieceLengthVal);

    Boolean createFlag = (Boolean) parser.getOptionValue(create);

    //For repeated announce urls
    @SuppressWarnings("unchecked")
    Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce);

    String[] otherArgs = parser.getRemainingArgs();

    if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) {
        usage(System.err,
                "Announce URL and a file or directory must be " + "provided to create a torrent file!");
        System.exit(1);
    }

    OutputStream fos = null;
    try {
        if (Boolean.TRUE.equals(createFlag)) {
            if (filenameValue != null) {
                fos = new FileOutputStream(filenameValue);
            } else {
                fos = System.out;
            }

            //Process the announce URLs into URIs
            List<URI> announceURIs = new ArrayList<URI>();
            for (String url : announceURLs) {
                announceURIs.add(new URI(url));
            }

            //Create the announce-list as a list of lists of URIs
            //Assume all the URI's are first tier trackers
            List<List<URI>> announceList = new ArrayList<List<URI>>();
            announceList.add(announceURIs);

            File source = new File(otherArgs[0]);
            if (!source.exists() || !source.canRead()) {
                throw new IllegalArgumentException(
                        "Cannot access source file or directory " + source.getName());
            }

            String creator = String.format("%s (ttorrent)", System.getProperty("user.name"));

            Torrent torrent = null;
            if (source.isDirectory()) {
                List<File> files = new ArrayList<File>(
                        FileUtils.listFiles(source, TrueFileFilter.TRUE, TrueFileFilter.TRUE));
                Collections.sort(files);
                torrent = Torrent.create(source, files, pieceLengthVal, announceList, creator);
            } else {
                torrent = Torrent.create(source, pieceLengthVal, announceList, creator);
            }

            torrent.save(fos);
        } else {
            Torrent.load(new File(filenameValue), true);
        }
    } catch (Exception e) {
        logger.error("{}", e.getMessage(), e);
        System.exit(2);
    } finally {
        if (fos != System.out) {
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:com.basistech.ninja.Train.java

/**
 * Command line interface to train a model.
 *
 * <pre>/*from  w ww.  ja v a  2s  .c o m*/
 *  usage: Train [options]
 *  --batch-size <arg>      batch size (default = 10)
 *  --epochs <arg>          epochs (default = 5)
 *  --examples <arg>        input examples file (required)
 *  --layer-sizes <arg>     layer sizes, including input/output, e.g. 3 4 2 (required)
 *  --learning-rate <arg>   learning-rate (default = 0.7)
 *  --model <arg>           output model file (required)
 * </pre>
 *
 * @param args command line arguments
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    String defaultBatchSize = "10";
    String deafaultEpochs = "5";
    String defaultLearningRate = "0.7";

    Options options = new Options();
    Option option;
    option = new Option(null, "examples", true, "input examples file (required)");
    option.setRequired(true);
    options.addOption(option);
    option = new Option(null, "model", true, "output model file (required)");
    option.setRequired(true);
    options.addOption(option);
    option = new Option(null, "layer-sizes", true,
            "layer sizes, including input/output, e.g. 3 4 2 (required)");
    option.setRequired(true);
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    option = new Option(null, "batch-size", true, String.format("batch size (default = %s)", defaultBatchSize));
    options.addOption(option);
    option = new Option(null, "epochs", true, String.format("epochs (default = %s)", deafaultEpochs));
    options.addOption(option);
    option = new Option(null, "learning-rate", true,
            String.format("learning-rate (default = %s)", defaultLearningRate));
    options.addOption(option);

    CommandLineParser parser = new GnuParser();
    CommandLine cmdline = null;
    try {
        cmdline = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException e) {
        System.err.println(e.getMessage());
        usage(options);
        System.exit(1);
    }
    String[] remaining = cmdline.getArgs();
    if (remaining == null) {
        usage(options);
        System.exit(1);
    }

    List<Integer> layerSizes = Lists.newArrayList();
    for (String s : cmdline.getOptionValues("layer-sizes")) {
        layerSizes.add(Integer.parseInt(s));
    }

    File examplesFile = new File(cmdline.getOptionValue("examples"));
    Train that = new Train(layerSizes, examplesFile);
    int batchSize = Integer.parseInt(cmdline.getOptionValue("batch-size", defaultBatchSize));
    int epochs = Integer.parseInt(cmdline.getOptionValue("epochs", deafaultEpochs));
    double learningRate = Double.parseDouble(cmdline.getOptionValue("learning-rate", defaultLearningRate));
    File modelFile = new File(cmdline.getOptionValue("model"));

    that.train(batchSize, epochs, learningRate, modelFile);
}

From source file:j8583.example.Client.java

public static void main(String[] args) throws Exception {
    Random rng = new Random(System.currentTimeMillis());
    log.debug("Reading config");
    mfact = ConfigParser.createFromClasspathConfig("j8583/example/config.xml");
    mfact.setAssignDate(true);/* ww  w .ja v  a 2  s  . c om*/
    mfact.setTraceNumberGenerator(new SimpleTraceGenerator((int) (System.currentTimeMillis() % 10000)));
    System.err.println("Connecting to server");
    Socket sock = new Socket("localhost", 9999);
    // Send 10 messages, then wait for the responses
    Client client = new Client(sock);
    Thread reader = new Thread(client, "j8583-client");
    reader.start();
    for (int i = 0; i < 10; i++) {
        IsoMessage req = mfact.newMessage(0x200);
        req.setValue(4, amounts[rng.nextInt(amounts.length)], IsoType.AMOUNT, 0);
        req.setValue(12, req.getObjectValue(7), IsoType.TIME, 0);
        req.setValue(13, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(15, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(17, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(37, System.currentTimeMillis() % 1000000, IsoType.NUMERIC, 12);
        req.setValue(41, data[rng.nextInt(data.length)], IsoType.ALPHA, 16);
        req.setValue(48, data[rng.nextInt(data.length)], IsoType.LLLVAR, 0);
        pending.put(req.getField(11).toString(), req);
        System.err.println(String.format("Sending request %s", req.getField(11)));
        req.write(sock.getOutputStream(), 2);
    }
    log.debug("Waiting for responses");
    while (pending.size() > 0 && sock.isConnected()) {
        Thread.sleep(500);
    }
    client.stop();
    reader.interrupt();
    log.debug("DONE.");
}