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(Locale l, String format, Object... args) 

Source Link

Document

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

Usage

From source file:com.clicktravel.cheddar.server.rest.application.RestApplication.java

/**
 * Starts the RestServer to listen on the given port and address combination
 *
 * @param args String arguments, {@code [context [service-port [status-port [bind-address] ] ] ]} where
 *            <ul>//from ww  w. jav  a 2s  .  c  o m
 *            <li>{@code context} - Name of application, defaults to {@code UNKNOWN}</li>
 *            <li>{@code service-port} - Port number for REST service endpoints, defaults to {@code 8080}</li>
 *            <li>{@code status-port} - Port number for REST status endpoints ({@code /status} and
 *            {@code /status/healthCheck}), defaults to {@code service-port + 100}</li>
 *            <li>{@code bind-address} - Local IP address to bind server to, defaults to {@code 0.0.0.0}</li>
 *            </ul>
 *
 * @throws Exception
 */
public static void main(final String... args) {
    final String context = args.length > 0 ? args[0] : "UNKNOWN";
    final int servicePort = args.length > 1 ? Integer.parseInt(args[1]) : 8080;
    final int statusPort = args.length > 2 ? Integer.parseInt(args[2]) : servicePort + 100;
    final String bindAddress = args.length > 3 ? args[3] : "0.0.0.0";
    MDC.put("context", context);
    MDC.put("hostId", System.getProperty("host.id", "UNKNOWN"));
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    final Logger logger = LoggerFactory.getLogger(RestApplication.class);
    try {
        logger.info("Java process starting");
        logger.debug(String.format("java.version:[%s] java.vendor:[%s]", System.getProperty("java.version"),
                System.getProperty("java.vendor")));
        @SuppressWarnings("resource")
        final ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        logger.debug("Finished getting ApplicationContext");
        final ApplicationLifecycleController applicationLifecycleController = applicationContext
                .getBean(ApplicationLifecycleController.class);
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            logger.info("Shutdown hook invoked - Commencing graceful termination of Java process");
            applicationLifecycleController.shutdownApplication();
            logger.info("Java process terminating");
        }));
        applicationLifecycleController.startApplication(servicePort, statusPort, bindAddress);
        Thread.currentThread().join();
    } catch (final InterruptedException e) {
        logger.info("Java process interrupted");
        System.exit(1);
    } catch (final Exception e) {
        logger.error("Error starting Java process", e);
        System.exit(1);
    }
}

From source file:eu.mrbussy.pdfsplitter.Application.java

/**
 * Start the main program.//from   w ww.  ja v  a  2  s. c o  m
 * 
 * @param args
 *            - Arguments passed on to the program
 */
public static void main(String[] args) {

    // Read configurations
    try {
        String configDirname = FilenameUtils.concat(System.getProperty("user.home"),
                String.format(".%1$s%2$s", NAME, IOUtils.DIR_SEPARATOR));
        String filename = FilenameUtils.concat(configDirname, CONFIGURATION_FILE);

        // Check to see if the directory exists and the file can be created/opened
        File configDir = new File(configDirname);
        if (!configDir.exists())
            configDir.mkdir();

        // Check to see if the file exists. If not create it
        File file = new File(filename);
        if (!file.exists()) {
            file.createNewFile();
        }
        Configuration = new PropertiesConfiguration(file);
        // Automatically store the settings that change
        Configuration.setAutoSave(true);

    } catch (ConfigurationException | IOException ex) {
        // Unable to read the file. Probably because it does not exist --> create it.
        ex.printStackTrace();
    }

    // Set locale to a configured language
    Locale.setDefault(
            new Locale(Configuration.getString("language", "nl"), Configuration.getString("country", "NL")));

    // Start by parsing the command line
    ParseCommandline(args);

    // Display the help if required and leave the app
    if (arguments.hasOption("h")) {
        showHelp();
    }

    // Display the app version and leave the app.
    if (arguments.hasOption("v")) {
        showVersion();
    }

    // Not command line so start the app GUI
    if (!arguments.hasOption("c")) {
        try {
            // Change the look and feel
            UIManager.setLookAndFeel(
                    Configuration.getString("LookAndFeel", "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"));
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    (new MainWindow()).setVisible(true);
                }
            });
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | UnsupportedLookAndFeelException e) {
            // Something terrible happened so show the  help
            showHelp();
        }

    }

}

From source file:com.aj.hangman.HangmanReq.java

public static void main(String[] args) {
    HangmanDict dictionary = new HangmanDict();

    try {/*from  w ww. j a v  a 2  s .  c  o m*/
        BufferedReader input = new BufferedReader(new InputStreamReader(
                new URL("http://gallows.hulu.com/play?code=gudehosa@usc.edu").openStream()));
        String info = input.readLine();
        JSONParser parser = new JSONParser();

        Object obj;
        try {
            obj = parser.parse(info);
            JSONObject retJson = (JSONObject) obj;

            TOKEN = (String) retJson.get("token");
            STATUS = (String) retJson.get("status");
            STATE = (String) retJson.get("state");
            REM = (Long) retJson.get("remaining_guesses");
            PREM = REM;
            System.out.println("State:: " + STATE);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        while ("ALIVE".equalsIgnoreCase(STATUS)) {
            // call make guess function, returns character
            guess = dictionary.makeGuess(STATE);
            System.out.println("Guessed:: " + guess);
            // call the url to update
            BufferedReader reInput = new BufferedReader(
                    new InputStreamReader(new URL("http://gallows.hulu.com/play?code=gudehosa@usc.edu"
                            + String.format("&token=%s&guess=%s", TOKEN, guess)).openStream()));

            // parse the url to get the updated value
            String reInfo = reInput.readLine();
            JSONParser reParser = new JSONParser();

            Object retObj = reParser.parse(reInfo);
            JSONObject retJson = (JSONObject) retObj;

            STATUS = (String) retJson.get("status");
            STATE = (String) retJson.get("state");
            REM = (Long) retJson.get("remaining_guesses");
            System.out.println("State:: " + STATE);
        }

        if ("DEAD".equalsIgnoreCase(STATUS)) {
            // print lost
            System.out.println("You LOOSE: DEAD");
        } else if ("FREE".equalsIgnoreCase(STATUS)) {
            // print free
            System.out.println("You WIN: FREE");
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:it.crs4.features.ImageToAvro.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    CommandLine cmd = null;/*from w ww . jav a 2  s.c o  m*/
    try {
        cmd = parseCmdLine(opts, args);
    } catch (ParseException e) {
        System.err.println("ERROR: " + e.getMessage());
        System.exit(1);
    }
    String fn = null;
    try {
        fn = cmd.getArgs()[0];
    } catch (ArrayIndexOutOfBoundsException e) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("java ImageToAvro IMG_FILE", opts);
        System.exit(2);
    }
    String outDirName = null;
    if (cmd.hasOption("outdir")) {
        outDirName = cmd.getOptionValue("outdir");
        File outDir = new File(outDirName);
        if (!outDir.exists()) {
            boolean ret = outDir.mkdirs();
            if (!ret) {
                System.err.format("ERROR: can't create %s\n", outDirName);
                System.exit(3);
            }
        }
    }

    String name = PathTools.stripext(PathTools.basename(fn));
    ImageReader reader = new ImageReader();
    reader.setId(fn);
    LOGGER.info("Reading from {}", fn);
    BioImgFactory factory = new BioImgFactory(reader);
    int seriesCount = factory.getSeriesCount();

    // FIXME: add support for XY slicing
    String seriesName;
    String outFn;
    for (int i = 0; i < seriesCount; i++) {
        seriesName = String.format("%s_%d", name, i);
        outFn = new File(outDirName, seriesName + ".avro").getPath();
        factory.setSeries(i);
        factory.writeSeries(seriesName, outFn);
        LOGGER.info("Writing to {}", outFn);
    }
    reader.close();
    LOGGER.info("All done");
}

From source file:interactivespaces.hardware.driver.gaming.wilddivine.IomDriver.java

public static void main(String[] args) {
    final SimpleInteractiveSpacesEnvironment spaceEnvironment = new SimpleInteractiveSpacesEnvironment();
    spaceEnvironment.setExecutorService(Executors.newScheduledThreadPool(100));
    SimpleServiceRegistry serviceRegistry = new SimpleServiceRegistry(spaceEnvironment);
    spaceEnvironment.setServiceRegistry(serviceRegistry);
    Configuration configuration = SimpleConfiguration.newConfiguration();
    spaceEnvironment.setLog(new Jdk14Logger("foo"));
    Usb4JavaUsbCommunicationEndpointService service = new Usb4JavaUsbCommunicationEndpointService();
    serviceRegistry.registerService(service);
    service.startup();//from   ww w.ja  va 2  s .c  o m

    IomDriver driver = new IomDriver();
    driver.prepare(spaceEnvironment, configuration, spaceEnvironment.getLog());

    driver.addListener(new IomDeviceListener() {

        @Override
        public void onEvent(IomDriver driver, double heartRateValue, double skinConductivityLevel) {
            spaceEnvironment.getLog()
                    .info(String.format("Heart is %f, skin is %f", heartRateValue, skinConductivityLevel));
        }
    });

    try {
        driver.startup();

        InteractiveSpacesUtilities.delay(20000);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        driver.shutdown();
        spaceEnvironment.getExecutorService().shutdown();
    }
}

From source file:bluevia.examples.MODemo.java

/**
 * @param args//from  w ww.java  2  s . c  o m
 */
public static void main(String[] args) throws IOException {

    BufferedReader iReader = null;
    String apiDataFile = "API-AccessToken.ini";

    String consumer_key;
    String consumer_secret;
    String registrationId;

    OAuthConsumer apiConsumer = null;
    HttpURLConnection request = null;
    URL moAPIurl = null;

    Logger logger = Logger.getLogger("moSMSDemo.class");
    int i = 0;
    int rc = 0;

    Thread mThread = Thread.currentThread();

    try {
        System.setProperty("debug", "1");

        iReader = new BufferedReader(new FileReader(apiDataFile));

        // Private data: consumer info + access token info + phone info
        consumer_key = iReader.readLine();
        consumer_secret = iReader.readLine();
        registrationId = iReader.readLine();

        // Set up the oAuthConsumer
        while (true) {
            try {

                logger.log(Level.INFO, String.format("#%d: %s\n", ++i, "Requesting messages..."));

                apiConsumer = new DefaultOAuthConsumer(consumer_key, consumer_secret);

                apiConsumer.setMessageSigner(new HmacSha1MessageSigner());

                moAPIurl = new URL("https://api.bluevia.com/services/REST/SMS/inbound/" + registrationId
                        + "/messages?version=v1&alt=json");

                request = (HttpURLConnection) moAPIurl.openConnection();
                request.setRequestMethod("GET");

                apiConsumer.sign(request);

                StringBuffer doc = new StringBuffer();
                BufferedReader br = null;

                rc = request.getResponseCode();
                if (rc == HttpURLConnection.HTTP_OK) {
                    br = new BufferedReader(new InputStreamReader(request.getInputStream()));

                    String line = br.readLine();
                    while (line != null) {
                        doc.append(line);
                        line = br.readLine();
                    }

                    System.out.printf("Output message: %s\n", doc.toString());
                    try {
                        JSONObject apiResponse1 = new JSONObject(doc.toString());
                        String aux = apiResponse1.getString("receivedSMS");
                        if (aux != null) {
                            String szMessage;
                            String szOrigin;
                            String szDate;

                            JSONObject smsPool = apiResponse1.getJSONObject("receivedSMS");
                            JSONArray smsInfo = smsPool.optJSONArray("receivedSMS");
                            if (smsInfo != null) {
                                for (i = 0; i < smsInfo.length(); i++) {
                                    szMessage = smsInfo.getJSONObject(i).getString("message");
                                    szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress")
                                            .getString("phoneNumber");
                                    szDate = smsInfo.getJSONObject(i).getString("dateTime");
                                    System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate,
                                            szOrigin, szMessage);
                                }
                            } else {
                                JSONObject sms = smsPool.getJSONObject("receivedSMS");
                                szMessage = sms.getString("message");
                                szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber");
                                szDate = sms.getString("dateTime");
                                System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin,
                                        szMessage);
                            }
                        }
                    } catch (JSONException e) {
                        System.err.println("JSON error: " + e.getMessage());
                    }

                } else if (rc == HttpURLConnection.HTTP_NO_CONTENT)
                    System.out.printf("No content\n");
                else
                    System.err.printf("Error: %d:%s\n", rc, request.getResponseMessage());

                request.disconnect();

            } catch (Exception e) {
                System.err.println("Exception: " + e.getMessage());
            }
            mThread.sleep(15000);
        }
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    }
}

From source file:acmi.l2.clientmod.l2_version_switcher.Main.java

public static void main(String[] args) {
    if (args.length != 3 && args.length != 4) {
        System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>");
        System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME
                + " 1 \"system\\*\"");
        System.out.println(/*from   w ww .j a  v a  2  s.  c om*/
                "         l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48");
        System.exit(0);
    }

    List<String> argsList = new ArrayList<>(Arrays.asList(args));
    String host = argsList.get(0);
    String game = argsList.get(1);
    int version = Integer.parseInt(argsList.get(2));
    Helper helper = new Helper(host, game, version);
    boolean available = false;

    try {
        available = helper.isAvailable();
    } catch (IOException e) {
        System.err.print(e.getClass().getSimpleName());
        if (e.getMessage() != null) {
            System.err.print(": " + e.getMessage());
        }

        System.err.println();
    }

    System.out.println(String.format("Version %d available: %b", version, available));
    if (!available) {
        System.exit(0);
    }

    List<FileInfo> fileInfoList = null;
    try {
        fileInfoList = helper.getFileInfoList();
    } catch (IOException e) {
        System.err.println("Couldn\'t get file info map");
        System.exit(1);
    }

    boolean splash = argsList.remove("--splash");
    if (splash) {
        Optional<FileInfo> splashObj = fileInfoList.stream()
                .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny();
        if (splashObj.isPresent()) {
            try (InputStream is = new FilterInputStream(
                    Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) {
                @Override
                public int read() throws IOException {
                    int b = super.read();
                    if (b >= 0)
                        b ^= 0x36;
                    return b;
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    int r = super.read(b, off, len);
                    if (r >= 0) {
                        for (int i = 0; i < r; i++)
                            b[off + i] ^= 0x36;
                    }
                    return r;
                }
            }) {
                new DataInputStream(is).readFully(new byte[28]);
                BufferedImage bi = ImageIO.read(is);

                JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath());
                frame.setContentPane(new JComponent() {
                    {
                        setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
                    }

                    @Override
                    protected void paintComponent(Graphics g) {
                        g.drawImage(bi, 0, 0, null);
                    }
                });
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Splash not found");
        }
        return;
    }

    String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null;

    File l2Folder = new File(System.getProperty("user.dir"));
    List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> {
        String filePath = separatorsToSystem(fi.getPath());

        if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE))
            return false;
        File file = new File(l2Folder, filePath);

        try {
            if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) {
                System.out.println(filePath + ": OK");
                return false;
            }
        } catch (IOException e) {
            System.out.println(filePath + ": couldn't check hash: " + e);
            return true;
        }

        System.out.println(filePath + ": need update");
        return true;
    }).collect(Collectors.toList());

    List<String> errors = Collections.synchronizedList(new ArrayList<>());
    ExecutorService executor = Executors.newFixedThreadPool(16);
    CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> {
        String filePath = separatorsToSystem(fi.getPath());
        File file = new File(l2Folder, filePath);

        File folder = file.getParentFile();
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                errors.add(filePath + ": couldn't create parent dir");
                return;
            }
        }

        try (InputStream input = Util
                .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath())));
                OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) {
            byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)];
            int pos = 0;
            int r;
            while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) {
                pos += r;
                if (pos == buffer.length) {
                    output.write(buffer, 0, pos);
                    pos = 0;
                }
            }
            if (pos != 0) {
                output.write(buffer, 0, pos);
            }
            System.out.println(filePath + ": OK");
        } catch (IOException e) {
            String msg = filePath + ": FAIL: " + e.getClass().getSimpleName();
            if (e.getMessage() != null) {
                msg += ": " + e.getMessage();
            }
            errors.add(msg);
        }
    }, executor)).toArray(CompletableFuture[]::new);
    CompletableFuture.allOf(tasks).thenRun(() -> {
        for (String err : errors)
            System.err.println(err);
        executor.shutdown();
    });
}

From source file:se.berazy.api.examples.App.java

/**
 * Operation examples./*from   w ww.ja  v a 2 s .c  om*/
 * @param args
 */
public static void main(String[] args) {
    Scanner scanner = null;
    try {
        client = new BookkeepingClient();
        System.out.println("Choose operation to invoke:\n");
        System.out.println("1. Create invoice");
        System.out.println("2. Credit invoice");
        scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            line = (line != null) ? line.trim().toLowerCase() : "";
            if (line.equals("1")) {
                outPutResponse(createInvoice());
            } else if (line.equals("2")) {
                outPutResponse(creditInvoice());
            } else if (line.equals("q") || line.equals("quit") || line.equals("exit")) {
                System.exit(0);
            } else {
                System.out.println("\nPlease choose an operation from 1-7.");
            }
        }
        scanner.close();
    } catch (Exception ex) {
        System.out.println(String.format(
                "\nAn exception occured, press CTRL+C to exit or enter 'q', 'quit' or 'exit'.\n\nException: %s %s",
                ex.getMessage(), ex.getStackTrace()));
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}

From source file:com.twitter.bazel.checkstyle.JavaCheckstyle.java

public static void main(String[] args) throws IOException {
    CommandLineParser parser = new DefaultParser();

    // create the Options
    Options options = new Options();
    options.addOption(Option.builder("f").required(true).hasArg().longOpt("extra_action_file")
            .desc("bazel extra action protobuf file").build());
    options.addOption(Option.builder("c").required(true).hasArg().longOpt("checkstyle_config_file")
            .desc("checkstyle config file").build());

    try {/*from  www  .j av a 2 s  .  c om*/
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        String extraActionFile = line.getOptionValue("f");
        String configFile = line.getOptionValue("c");

        String[] sourceFiles = getSourceFiles(extraActionFile);
        if (sourceFiles.length == 0) {
            LOG.fine("No java files found by checkstyle");
            return;
        }

        LOG.fine(sourceFiles.length + " java files found by checkstyle");

        String[] checkstyleArgs = (String[]) ArrayUtils.addAll(new String[] { "-c", configFile }, sourceFiles);

        LOG.fine("checkstyle args: " + Joiner.on(" ").join(checkstyleArgs));
        com.puppycrawl.tools.checkstyle.Main.main(checkstyleArgs);
    } catch (ParseException exp) {
        LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage()));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java " + CLASSNAME, options);
    }
}

From source file:gobblin.util.CLIPasswordEncryptor.java

public static void main(String[] args) throws ParseException {
    CommandLine cl = parseArgs(args);// www .  j av a2s  .c o  m
    if (shouldPrintUsageAndExit(cl)) {
        printUsage();
        return;
    }
    String masterPassword = getMasterPassword(cl);
    TextEncryptor encryptor = getEncryptor(cl, masterPassword);

    if (cl.hasOption(ENCRYPTED_PWD_OPTION)) {
        Matcher matcher = ENCRYPTED_PATTERN.matcher(cl.getOptionValue(ENCRYPTED_PWD_OPTION));
        if (matcher.find()) {
            String encrypted = matcher.group(1);
            System.out.println(encryptor.decrypt(encrypted));
        } else {
            throw new RuntimeException("Input encrypted password does not match pattern \"ENC(...)\"");
        }
    } else if (cl.hasOption(PLAIN_PWD_OPTION)) {
        System.out.println("ENC(" + encryptor.encrypt(cl.getOptionValue(PLAIN_PWD_OPTION)) + ")");
    } else {
        printUsage();
        throw new RuntimeException(
                String.format("Must provide -%s or -%s option.", PLAIN_PWD_OPTION, ENCRYPTED_PWD_OPTION));
    }
}