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.usp.poli.lta.cereda.spa2run.Main.java

public static void main(String[] args) {

    Utils.printBanner();//from   w  w  w.j a va 2 s .c o  m
    CommandLineParser parser = new DefaultParser();

    try {
        CommandLine line = parser.parse(Utils.getOptions(), args);
        List<Spec> specs = Utils.fromFilesToSpecs(line.getArgs());
        List<Metric> metrics = Utils.fromFilesToMetrics(line);
        Utils.setMetrics(metrics);
        Utils.resetCalculations();
        AdaptiveAutomaton automaton = Utils.getAutomatonFromSpecs(specs);

        System.out.println("SPA generated successfully:");
        System.out.println("- " + specs.size() + " submachine(s) found.");
        if (!Utils.detectEpsilon(automaton)) {
            System.out.println("- No empty transitions.");
        }
        if (!metrics.isEmpty()) {
            System.out.println("- " + metrics.size() + " metric(s) found.");
        }

        System.out.println("\nStarting shell, please wait...\n" + "(press CTRL+C or type `:quit'\n"
                + "to exit the application)\n");

        String query = "";
        Scanner scanner = new Scanner(System.in);
        String prompt = "[%d] query> ";
        String result = "[%d] result> ";
        int counter = 1;
        do {

            try {
                String term = String.format(prompt, counter);
                System.out.print(term);
                query = scanner.nextLine().trim();
                if (!query.equals(":quit")) {
                    boolean accept = automaton.recognize(Utils.toSymbols(query));
                    String type = automaton.getRecognitionPaths().size() == 1 ? " (deterministic)"
                            : " (nondeterministic)";
                    System.out.println(String.format(result, counter) + accept + type);

                    if (!metrics.isEmpty()) {
                        System.out.println(StringUtils.repeat(" ", String.format("[%d] ", counter).length())
                                + Utils.prettyPrintMetrics());
                    }

                    System.out.println();

                }
            } catch (Exception exception) {
                System.out.println();
                Utils.printException(exception);
                System.out.println();
            }

            counter++;
            Utils.resetCalculations();

        } while (!query.equals(":quit"));
        System.out.println("That's all folks!");

    } catch (ParseException nothandled) {
        Utils.printHelp();
    } catch (Exception exception) {
        Utils.printException(exception);
    }
}

From source file:example.Publisher.java

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

    String user = env("ACTIVEMQ_USER", "admin");
    String password = env("ACTIVEMQ_PASSWORD", "password");
    String host = env("ACTIVEMQ_HOST", "localhost");
    int port = Integer.parseInt(env("ACTIVEMQ_PORT", "1883"));
    final String destination = arg(args, 0, "/topic/event");

    int messages = 10000;
    int size = 256;

    String DATA = "abcdefghijklmnopqrstuvwxyz";
    String body = "";
    for (int i = 0; i < size; i++) {
        body += DATA.charAt(i % DATA.length());
    }//w w  w . ja v  a  2 s  .  c  om
    Buffer msg = new AsciiBuffer(body);

    MQTT mqtt = new MQTT();
    mqtt.setHost(host, port);
    mqtt.setUserName(user);
    mqtt.setPassword(password);

    FutureConnection connection = mqtt.futureConnection();
    connection.connect().await();

    final LinkedList<Future<Void>> queue = new LinkedList<Future<Void>>();
    UTF8Buffer topic = new UTF8Buffer(destination);
    for (int i = 1; i <= messages; i++) {

        // Send the publish without waiting for it to complete. This allows us
        // to send multiple message without blocking..
        queue.add(connection.publish(topic, msg, QoS.AT_LEAST_ONCE, false));

        // Eventually we start waiting for old publish futures to complete
        // so that we don't create a large in memory buffer of outgoing message.s
        if (queue.size() >= 1000) {
            queue.removeFirst().await();
        }

        if (i % 1000 == 0) {
            System.out.println(String.format("Sent %d messages.", i));
        }
    }

    queue.add(connection.publish(topic, new AsciiBuffer("SHUTDOWN"), QoS.AT_LEAST_ONCE, false));
    while (!queue.isEmpty()) {
        queue.removeFirst().await();
    }

    connection.disconnect().await();

    System.exit(0);
}

From source file:org.jimsey.projects.turbine.condenser.Application.java

public static void main(final String... args) {
    ConfigurableApplicationContext spring = SpringApplication.run(Application.class, args);

    // logBeanNames(spring);
    Ping ping = (Ping) spring.getBean("ping");
    long message = ping.ping();
    logger.info(String.format("ping=%s", message));
}

From source file:com.google.play.developerapi.samples.BasicUploadApk.java

public static void main(String[] args) {
    try {/*from   w  w w .j  av  a2 s .c  o  m*/
        Preconditions.checkArgument(!Strings.isNullOrEmpty(ApplicationConfig.PACKAGE_NAME),
                "ApplicationConfig.PACKAGE_NAME cannot be null or empty!");

        // Create the API service.
        AndroidPublisher service = AndroidPublisherHelper.init(ApplicationConfig.APPLICATION_NAME,
                ApplicationConfig.SERVICE_ACCOUNT_EMAIL);
        final Edits edits = service.edits();

        // Create a new edit to make changes to your listing.
        Insert editRequest = edits.insert(ApplicationConfig.PACKAGE_NAME, null /** no content */
        );
        AppEdit edit = editRequest.execute();
        final String editId = edit.getId();
        log.info(String.format("Created edit with id: %s", editId));

        // Upload new apk to developer console
        final String apkPath = BasicUploadApk.class.getResource(ApplicationConfig.APK_FILE_PATH).toURI()
                .getPath();
        final AbstractInputStreamContent apkFile = new FileContent(AndroidPublisherHelper.MIME_TYPE_APK,
                new File(apkPath));
        Upload uploadRequest = edits.apks().upload(ApplicationConfig.PACKAGE_NAME, editId, apkFile);
        Apk apk = uploadRequest.execute();
        log.info(String.format("Version code %d has been uploaded", apk.getVersionCode()));

        // Assign apk to alpha track.
        List<Integer> apkVersionCodes = new ArrayList<>();
        apkVersionCodes.add(apk.getVersionCode());
        Update updateTrackRequest = edits.tracks().update(ApplicationConfig.PACKAGE_NAME, editId, TRACK_ALPHA,
                new Track().setVersionCodes(apkVersionCodes));
        Track updatedTrack = updateTrackRequest.execute();
        log.info(String.format("Track %s has been updated.", updatedTrack.getTrack()));

        // Commit changes for edit.
        Commit commitRequest = edits.commit(ApplicationConfig.PACKAGE_NAME, editId);
        AppEdit appEdit = commitRequest.execute();
        log.info(String.format("App edit with id %s has been comitted", appEdit.getId()));

    } catch (IOException | URISyntaxException | GeneralSecurityException ex) {
        log.error("Excpetion was thrown while uploading apk to alpha track", ex);
    }
}

From source file:com.carl.interesting.StartINGServer.java

/**
 * Main method./* w  w w  . ja  va2 s . c  o m*/
 * 
 * @param args [explain parameter]
 * @return void [explain return type]
 * @exception throws [exception type] [explain exception]
 * @see [class,class#method,class#member]
 */
public static void main(String[] args) {
    LOG.info("Start ING server");
    switch (args.length) {
    case 0:
        // LOG.info("The default port " + PORT + " will be used.");
        break;
    case 1:
        PORT = Integer.parseInt(args[0]);
        break;
    default:
        PORT = Integer.parseInt(args[0]);
    }
    try {
        initServer();
        // start server
        if (null == startServer(PORT)) {
            LOG.error("port " + PORT + " has been used");
            System.exit(0);
            return;
        }
        LOG.info(String.format("ING Server is started at: " + "%s/" + Constant.PROJECT + "/ ...",
                BASE + ":" + Integer.toString(PORT)));
        // start clean monitor job
        // new MonitorCleanJob().start();
        // ??(Host/Mon/Osd/Mds/Pool/Access)
        // clusterServiceImpl.initFromDB();
        // ??()
        // initHostAgentDB();
        // ?
        // initScheduler();
        // initLeader();
        // ?license
        // communicationScheduler.initCommunicate();
        // ?
        // warningDisScheduler.initWarningDistribute();
        // recoverTask();
    } catch (Exception e) {
        LogUtil.logError(LOG, e);
    }
}

From source file:com.uber.tchannel.ping.PingClient.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "host", true, "Server Host to connect to");
    options.addOption("p", "port", true, "Server Port to connect to");
    options.addOption("n", "requests", true, "Number of requests to make");
    options.addOption("?", "help", false, "Usage");
    HelpFormatter formatter = new HelpFormatter();

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

    if (cmd.hasOption("?")) {
        formatter.printHelp("PingClient", options, true);
        return;//w ww. j  a  v a2 s  .c  o  m
    }

    String host = cmd.getOptionValue("h", "localhost");
    int port = Integer.parseInt(cmd.getOptionValue("p", "8888"));
    int requests = Integer.parseInt(cmd.getOptionValue("n", "10000"));

    System.out.println(String.format("Connecting from client to server on port: %d", port));
    new PingClient(host, port, requests).run();
    System.out.println("Stopping Client...");
}

From source file:com.metamx.druid.utils.ExposeS3DataSource.java

public static void main(String[] args) throws ServiceException, IOException, NoSuchAlgorithmException {
    CLI cli = new CLI();
    cli.addOption(new RequiredOption(null, "s3Bucket", true, "s3 bucket to pull data from"));
    cli.addOption(new RequiredOption(null, "s3Path", true,
            "base input path in s3 bucket.  Everything until the date strings."));
    cli.addOption(new RequiredOption(null, "timeInterval", true, "ISO8601 interval of dates to index"));
    cli.addOption(new RequiredOption(null, "granularity", true, String.format(
            "granularity of index, supported granularities: [%s]", Arrays.asList(Granularity.values()))));
    cli.addOption(new RequiredOption(null, "zkCluster", true, "Cluster string to connect to ZK with."));
    cli.addOption(new RequiredOption(null, "zkBasePath", true, "The base path to register index changes to."));

    CommandLine commandLine = cli.parse(args);

    if (commandLine == null) {
        return;/*w w w  . ja v a 2s  .c o  m*/
    }

    String s3Bucket = commandLine.getOptionValue("s3Bucket");
    String s3Path = commandLine.getOptionValue("s3Path");
    String timeIntervalString = commandLine.getOptionValue("timeInterval");
    String granularity = commandLine.getOptionValue("granularity");
    String zkCluster = commandLine.getOptionValue("zkCluster");
    String zkBasePath = commandLine.getOptionValue("zkBasePath");

    Interval timeInterval = new Interval(timeIntervalString);
    Granularity gran = Granularity.valueOf(granularity.toUpperCase());
    final RestS3Service s3Client = new RestS3Service(new AWSCredentials(
            System.getProperty("com.metamx.aws.accessKey"), System.getProperty("com.metamx.aws.secretKey")));
    ZkClient zkClient = new ZkClient(new ZkConnection(zkCluster), Integer.MAX_VALUE, new StringZkSerializer());

    zkClient.waitUntilConnected();

    for (Interval interval : gran.getIterable(timeInterval)) {
        log.info("Processing interval[%s]", interval);
        String s3DatePath = JOINER.join(s3Path, gran.toPath(interval.getStart()));
        if (!s3DatePath.endsWith("/")) {
            s3DatePath += "/";
        }

        StorageObjectsChunk chunk = s3Client.listObjectsChunked(s3Bucket, s3DatePath, "/", 2000, null, true);
        TreeSet<String> commonPrefixes = Sets.newTreeSet();
        commonPrefixes.addAll(Arrays.asList(chunk.getCommonPrefixes()));

        if (commonPrefixes.isEmpty()) {
            log.info("Nothing at s3://%s/%s", s3Bucket, s3DatePath);
            continue;
        }

        String latestPrefix = commonPrefixes.last();

        log.info("Latest segments at [s3://%s/%s]", s3Bucket, latestPrefix);

        chunk = s3Client.listObjectsChunked(s3Bucket, latestPrefix, "/", 2000, null, true);
        Integer partitionNumber;
        if (chunk.getCommonPrefixes().length == 0) {
            partitionNumber = null;
        } else {
            partitionNumber = -1;
            for (String partitionPrefix : chunk.getCommonPrefixes()) {
                String[] splits = partitionPrefix.split("/");
                partitionNumber = Math.max(partitionNumber, Integer.parseInt(splits[splits.length - 1]));
            }
        }

        log.info("Highest segment partition[%,d]", partitionNumber);

        if (partitionNumber == null) {
            final S3Object s3Obj = new S3Object(new S3Bucket(s3Bucket),
                    String.format("%sdescriptor.json", latestPrefix));
            updateWithS3Object(zkBasePath, s3Client, zkClient, s3Obj);
        } else {
            for (int i = partitionNumber; i >= 0; --i) {
                final S3Object partitionObject = new S3Object(new S3Bucket(s3Bucket),
                        String.format("%s%s/descriptor.json", latestPrefix, i));

                updateWithS3Object(zkBasePath, s3Client, zkClient, partitionObject);
            }
        }
    }
}

From source file:com.wouterbreukink.onedrive.Main.java

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

    // Parse command line args
    try {//from   w w  w.  j  a va2 s  .  c o  m
        CommandLineOpts.initialise(args);
    } catch (ParseException ex) {
        log.error("Unable to parse command line arguments - " + ex.getMessage());
        CommandLineOpts.printHelp();
        return;
    }

    if (getCommandLineOpts().help()) {
        CommandLineOpts.printHelp();
        return;
    }

    if (getCommandLineOpts().version()) {
        String version = getCommandLineOpts().getClass().getPackage().getImplementationVersion();
        log.info("onedrive-java-client version " + (version != null ? version : "DEVELOPMENT"));
        return;
    }

    // Initialise a log file (if set)
    if (getCommandLineOpts().getLogFile() != null) {
        String logFileName = LogUtils.addFileLogger(getCommandLineOpts().getLogFile());
        log.info(String.format("Writing log output to %s", logFileName));
    }

    if (getCommandLineOpts().isAuthorise()) {
        AuthorisationProvider.FACTORY.printAuthInstructions();
        return;
    }

    if (getCommandLineOpts().getLocalPath() == null || getCommandLineOpts().getRemotePath() == null
            || getCommandLineOpts().getDirection() == null) {
        log.error("Must specify --local, --remote and --direction");
        CommandLineOpts.printHelp();
        return;
    }

    // Initialise the OneDrive authorisation
    AuthorisationProvider authoriser;
    try {
        authoriser = AuthorisationProvider.FACTORY.create(getCommandLineOpts().getKeyFile());
        authoriser.getAccessToken();
    } catch (OneDriveAPIException ex) {
        log.error("Unable to authorise client: " + ex.getMessage());
        log.error("Re-run the application with --authorise");
        return;
    }

    // Initialise the providers
    OneDriveProvider api;
    FileSystemProvider fileSystem;
    if (getCommandLineOpts().isDryRun()) {
        log.warn("This is a dry run - no changes will be made");
        api = OneDriveProvider.FACTORY.readOnlyApi(authoriser);
        fileSystem = FileSystemProvider.FACTORY.readOnlyProvider();
    } else {
        api = OneDriveProvider.FACTORY.readWriteApi(authoriser);
        fileSystem = FileSystemProvider.FACTORY.readWriteProvider();
    }

    // Report on progress
    TaskReporter reporter = new TaskReporter();

    // Get the primary drive
    Drive primary = api.getDefaultDrive();

    // Report quotas
    log.info(String.format("Using drive with id '%s' (%s). Usage %s of %s (%.2f%%)", primary.getId(),
            primary.getDriveType(), readableFileSize(primary.getQuota().getUsed()),
            readableFileSize(primary.getQuota().getTotal()),
            ((double) primary.getQuota().getUsed() / primary.getQuota().getTotal()) * 100));

    // Check the given root folder
    OneDriveItem rootFolder = api.getPath(getCommandLineOpts().getRemotePath());

    if (!rootFolder.isDirectory()) {
        log.error(String.format("Specified root '%s' is not a folder", rootFolder.getFullName()));
        return;
    }

    File localRoot = new File(getCommandLineOpts().getLocalPath());

    log.info(String.format("Local folder '%s'", localRoot.getAbsolutePath()));
    log.info(String.format("Remote folder '<onedrive>%s'", rootFolder.getFullName()));

    // Start synchronisation operation at the root
    final TaskQueue queue = new TaskQueue();
    queue.add(new CheckTask(new Task.TaskOptions(queue, api, fileSystem, reporter), rootFolder, localRoot));

    // Get a bunch of threads going
    ExecutorService executorService = Executors.newFixedThreadPool(getCommandLineOpts().getThreads());

    for (int i = 0; i < getCommandLineOpts().getThreads(); i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    //noinspection InfiniteLoopStatement
                    while (true) {
                        Task taskToRun = null;
                        try {
                            taskToRun = queue.take();
                            taskToRun.run();
                        } finally {
                            if (taskToRun != null) {
                                queue.done(taskToRun);
                            }
                        }
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
    }

    queue.waitForCompletion();
    log.info("Synchronisation complete");
    reporter.report();
}

From source file:jtrace.scenes.OneCubeAnimate.java

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

    Scene scene = new Scene();

    scene.addLightSource(new LightSource(new Vector3D(-3, 3, -3), 4));
    scene.addLightSource(new LightSource(new Vector3D(6, 6, -3), 4));

    FlatTexture cubeTexture = (new FlatTexture(new SolidPigment(new Colour(0, 0, 1))));
    cubeTexture.addFinish(new DiffuseFinish(1.0));
    cubeTexture.addFinish(new AmbientFinish(0.1));
    cubeTexture.addFinish(new MirrorFinish(0.2));

    Cube cube = new Cube(new Vector3D(0, 0, 0), 0.5);
    cube.addTexture(cubeTexture);/*w w w . ja v a 2s .  c  o  m*/
    scene.addObject(cube);

    //        FlatTexture floorTexture = new FlatTexture(new CheckeredPigment(
    //                new Colour(.5,.5,.5), new Colour(1,1,1), 1));
    FlatTexture floorTexture = new FlatTexture(new ImagePigment(new File("wood.jpg"), 1.0));
    floorTexture.addFinish(new DiffuseFinish(1.0));

    Plane plane = new Plane(new Vector3D(0, -0.25, 0), Vector3D.PLUS_J, Vector3D.PLUS_K);
    plane.addTexture(floorTexture);
    scene.addObject(plane);

    Vector3D pointAt = new Vector3D(0, 0, 0);

    int steps = 100;
    for (int i = 0; i < steps; i++) {
        double R = 2.0;
        double x = R * Math.sin(i * 2 * Math.PI / steps);
        double z = -R * Math.cos(i * 2 * Math.PI / steps);
        Camera camera = new Camera(new Vector3D(x, 1, z), pointAt, Vector3D.PLUS_J, 1.0, 800.0 / 600.0);
        scene.setCamera(camera);
        BufferedImage image = scene.render(800, 600, 10);
        ImageIO.write(image, "PNG", new File(String.format("out_%02d.png", i)));
    }
}

From source file:CubaHSQLDBServer.java

public static void main(final String[] args) {
    final boolean validInit = args.length > 2;
    SwingUtilities.invokeLater(new Runnable() {
        @Override//from w w w  .  j a v  a  2 s.  c  o m
        public void run() {
            final CubaHSQLDBServer monitor = new CubaHSQLDBServer();
            monitor.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            monitor.setLocationRelativeTo(null);
            monitor.setVisible(true);

            if (validInit) {
                Integer dbPort = Integer.valueOf(args[0]);
                String dbPath = args[1];
                String dbName = args[2];
                final HSQLServer server = monitor.startServer(dbPort, dbPath, dbName);
                if (server != null) {
                    monitor.addWindowListener(new WindowAdapter() {
                        @Override
                        public void windowClosing(WindowEvent e) {
                            try {
                                server.shutdownCatalogs(2 /* NORMAL CLOSE MODE */);
                            } catch (RuntimeException exception) {
                                // Ignore exceptions from server.
                            }
                        }
                    });
                }
            } else {
                String argStr = StringUtils.join(args, ' ');
                monitor.setStatus(String.format(
                        "Invalid usage (args: '%s')\nExpected arguments: <port> <dbPath> <dbName>", argStr));
            }
        }
    });
}