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.github.liyp.test.TestMain.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    // add a shutdown hook to stop the server
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override/*w ww .j a  v  a2 s .c o m*/
        public void run() {
            System.out.println("########### shoutdown begin....");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("########### shoutdown end....");
        }
    }));

    System.out.println(args.length);
    Iterator<String> iterator1 = IteratorUtils
            .arrayIterator(new String[] { "one", "two", "three", "11", "22", "AB" });
    Iterator<String> iterator2 = IteratorUtils.arrayIterator(new String[] { "a", "b", "c", "33", "ab", "aB" });

    Iterator<String> chainedIter = IteratorUtils.chainedIterator(iterator1, iterator2);

    System.out.println("==================");

    Iterator<String> iter = IteratorUtils.filteredIterator(chainedIter, new Predicate() {
        @Override
        public boolean evaluate(Object arg0) {
            System.out.println("xx:" + arg0.toString());
            String str = (String) arg0;
            return str.matches("([a-z]|[A-Z]){2}");
        }
    });
    while (iter.hasNext()) {
        System.out.println(iter.next());
    }

    System.out.println("===================");

    System.out.println("asas".matches("[a-z]{4}"));

    System.out.println("Y".equals(null));

    System.out.println(String.format("%02d", 1000L));

    System.out.println(ArrayUtils.toString(splitAndTrim(" 11, 21,12 ,", ",")));

    System.out.println(new ArrayList<String>().toString());

    JSONObject json = new JSONObject("{\"keynull\":null}");
    json.put("bool", false);
    json.put("keya", "as");
    json.put("key2", 2212222222222222222L);
    System.out.println(json);
    System.out.println(json.get("keynull").equals(null));

    String a = String.format("{\"id\":%d,\"method\":\"testCrossSync\"," + "\"circle\":%d},\"isEnd\":true", 1,
            1);
    System.out.println(a.getBytes().length);

    System.out.println(new String[] { "a", "b" });

    System.out.println(new JSONArray("[\"aa\",\"\"]"));

    String data = String.format("%9d %s", 1, RandomStringUtils.randomAlphanumeric(10));
    System.out.println(data.getBytes().length);

    System.out.println(ArrayUtils.toString("1|2| 3|  333||| 3".split("\\|")));

    JSONObject j1 = new JSONObject("{\"a\":\"11111\"}");
    JSONObject j2 = new JSONObject(j1.toString());
    j2.put("b", "22222");
    System.out.println(j1 + " | " + j2);

    System.out.println("======================");

    String regex = "\\d+(\\-\\d+){2} \\d+(:\\d+){2}";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher("2015-12-28 15:46:14  _NC250_MD:motion de\n");
    String eventDate = matcher.find() ? matcher.group() : "";

    System.out.println(eventDate);
}

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

public static void main(String[] args) {
    try {/*www  . ja  v a  2s  . 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 an edit to update listing for application.
        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));

        // Update listing for US version of the application.
        final Listing newUsListing = new Listing();
        newUsListing.setTitle(US_LISTING_TITLE).setFullDescription(US_LISTING_FULL_DESCRIPTION)
                .setShortDescription(US_LISTING_SHORT_DESCRITPION).setVideo(LISTINGS_PROMO_VIDEO);

        Update updateUSListingsRequest = edits.listings().update(ApplicationConfig.PACKAGE_NAME, editId,
                Locale.US.toString(), newUsListing);
        Listing updatedUsListing = updateUSListingsRequest.execute();
        log.info(String.format("Created new US app listing with title: %s", updatedUsListing.getTitle()));

        // Create and update listing for UK version of the application.
        final Listing newUkListing = new Listing();
        newUkListing.setTitle(UK_LISTING_TITLE).setFullDescription(UK_LISTING_FULL_DESCRIPTION)
                .setShortDescription(UK_LISTING_SHORT_DESCRITPION).setVideo(LISTINGS_PROMO_VIDEO);

        Update updateUkListingsRequest = edits.listings().update(ApplicationConfig.PACKAGE_NAME, editId,
                Locale.UK.toString(), newUkListing);
        Listing updatedUkListing = updateUkListingsRequest.execute();
        log.info(String.format("Created new UK app listing with title: %s", updatedUkListing.getTitle()));

        // 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 | GeneralSecurityException ex) {
        log.error("Exception was thrown while updating listing", ex);
    }
}

From source file:jparser.JParser.java

/**
 * @param args the command line arguments
 *///from w  w  w  .  j  a va  2 s .  c o  m
public static void main(String[] args) {

    Options options = new Options();
    CommandLineParser parser = new DefaultParser();

    options.addOption(
            Option.builder().longOpt("to").desc("Indica el tipo de archivo al que debera convertir: JSON / XML")
                    .hasArg().argName("tipo").build());

    options.addOption(Option.builder().longOpt("path")
            .desc("Indica la ruta donde se encuentra el archivo origen").hasArg().argName("origen").build());

    options.addOption(
            Option.builder().longOpt("target").desc("Indica la ruta donde se guardara el archivo resultante")
                    .hasArg().argName("destino").build());

    options.addOption("h", "help", false, "Muestra la guia de como usar la aplicacion");

    try {
        CommandLine command = parser.parse(options, args);
        Path source = null;
        Path target = null;
        FactoryFileParse.TypeParce type = FactoryFileParse.TypeParce.NULL;
        Optional<Customer> customer = Optional.empty();

        if (command.hasOption("h")) {
            HelpFormatter helper = new HelpFormatter();
            helper.printHelp("JParser", options);

            System.exit(0);
        }

        if (command.hasOption("to"))
            type = FactoryFileParse.TypeParce.fromValue(command.getOptionValue("to", ""));

        if (command.hasOption("path"))
            source = Paths.get(command.getOptionValue("path", ""));

        if (command.hasOption("target"))
            target = Paths.get(command.getOptionValue("target", ""));

        switch (type) {
        case JSON:
            customer = FactoryFileParse.createNewInstance(FactoryFileParse.TypeParce.XML).read(source);

            break;

        case XML:
            customer = FactoryFileParse.createNewInstance(FactoryFileParse.TypeParce.JSON).read(source);

            break;
        }

        if (customer.isPresent()) {
            Customer c = customer.get();

            boolean success = FactoryFileParse.createNewInstance(type).write(c, target);

            System.out.println(String.format("Operatation was: %s", success ? "success" : "fails"));
        }

    } catch (ParseException ex) {
        Logger.getLogger(JParser.class.getSimpleName()).log(Level.SEVERE, ex.getMessage(), ex);

        System.exit(-1);
    }
}

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

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption(Option.builder("i").argName("path").desc("The TSV file to read").hasArg().required()
            .longOpt("input-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());//w  w w. j  a va 2 s  .co 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());
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp(LoadConstructAnalysisTableIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

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

    File inputFile = new File(cl.getOptionValue("input-file"));
    if (!inputFile.exists()) {
        System.err.format("Unable to find input file at %s\n", cl.getOptionValue("input-file"));
        new HelpFormatter().printHelp(LoadConstructAnalysisTableIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    DB db;

    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"));
    }

    try {
        db.getConn().setAutoCommit(false);

        ConstructAnalysisFileParser parser = new ConstructAnalysisFileParser();
        parser.parse(inputFile);

        List<Pair<Integer, DB.OPERATION_PERFORMED>> results = ChemicalAssociatedWithPathway
                .insertOrUpdateChemicalsAssociatedWithPathwayFromParser(db, parser);
        if (results != null) {
            for (Pair<Integer, DB.OPERATION_PERFORMED> r : results) {
                System.out.format("%d: %s\n", r.getLeft(), r.getRight());
            }
        }
        // If we didn't encounter an exception, commit the transaction.
        db.getConn().commit();
    } catch (Exception e) {
        System.err.format("Caught exception when trying to load plate composition, rolling back. %s\n",
                e.getMessage());
        db.getConn().rollback();
        throw (e);
    } finally {
        db.getConn().close();
    }

}

From source file:edu.lternet.pasta.portal.user.SavedData.java

/**
 * @param args// www .ja  va 2  s  .  c om
 */
public static void main(String[] args) {
    String uid = "ucarroll";
    String scope1 = "knb-lter-nin";
    Integer identifier1 = new Integer(1);
    String scope2 = "knb-lter-sbc";
    Integer identifier2 = new Integer(28);
    Integer revision = new Integer(1);
    String savedDataXML = null;

    ConfigurationListener.configure();
    SavedData savedData = new SavedData(uid);

    savedData.addDocid(scope1, identifier1, revision);
    savedData.addDocid(scope2, identifier2, revision);
    List<String> dataStore = savedData.fetchDataStore();
    String savedDataList = savedData.getSavedDataList();
    System.out.println(String.format("Saved data list: %s", savedDataList));
    try {
        savedDataXML = savedData.getSavedDataXML("0", "10", null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    //savedData.removeDocid(scope2, identifier2);
    dataStore = savedData.fetchDataStore();
    //savedData.removeAllDataPackages();
}

From source file:edu.indiana.d2i.sloan.internal.LaunchVMSimulator.java

/**
 * @param args/*from w  w  w  .  ja v a2 s. c  o  m*/
 */
public static void main(String[] args) {
    LaunchVMSimulator simulator = new LaunchVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine line = simulator.parseCommandLine(parser, args);

        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));
        String mode = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE));
        String policyFilePath = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH));

        if (!HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Cannot find VM working dir: %s", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST));
        }

        VMMode vmmode = HypervisorCmdSimulator.getVMMode(mode);

        if (vmmode == null) {
            logger.error(String.format("Invalid requested mode: %s, can only be %s or %s", mode,
                    VMMode.MAINTENANCE.toString(), VMMode.SECURE.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_VM_MODE));
        }

        if (!HypervisorCmdSimulator.resourceExist(policyFilePath)) {
            logger.error(String.format("Cannot find plicy file: %s", policyFilePath));
            System.exit(ERROR_CODE.get(ERROR_STATE.FIREWALL_POLICY_NOT_EXIST));
        }

        // load VM status info
        Properties prop = new Properties();
        String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME;

        prop.load(new FileInputStream(new File(filename)));

        // can only launch VM when it is in shutdown state
        VMState currentState = VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE)));

        if (!currentState.equals(VMState.SHUTDOWN)) {
            logger.error(String.format("Can only launch VM when it is in %s state, current VM state is %s",
                    VMState.SHUTDOWN.toString(), currentState.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_SHUTDOWN));
        }
        // launch VM
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        // update VM state file

        // set following properties
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH), policyFilePath);
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE), vmmode.toString());

        // set VM state to running
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.RUNNING.toString());

        // save VM state file back
        prop.store(new FileOutputStream(new File(filename)), "");

        // success
        System.exit(0);
    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (FileNotFoundException e) {
        logger.error(String.format("Cannot find vm state file: %s", e.getMessage()));

        System.exit(ERROR_CODE.get(ERROR_STATE.VM_STATE_FILE_NOT_FOUND));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }
}

From source file:edu.indiana.d2i.sloan.internal.SwitchVMSimulator.java

/**
 * @param args//w ww.j  av a2 s  .co m
 */
public static void main(String[] args) {
    SwitchVMSimulator simulator = new SwitchVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine line = simulator.parseCommandLine(parser, args);

        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));
        String mode = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE));
        String policyFilePath = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH));

        if (!HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Cannot find VM working dir: %s", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST));
        }

        VMMode requestedMode = HypervisorCmdSimulator.getVMMode(mode);

        if (requestedMode == null) {
            logger.error(String.format("Invalid requested mode: %s, can only be %s or %s", mode,
                    VMMode.MAINTENANCE.toString(), VMMode.SECURE.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_VM_MODE));
        }

        if (!HypervisorCmdSimulator.resourceExist(policyFilePath)) {
            logger.error(String.format("Cannot find plicy file: %s", policyFilePath));
            System.exit(ERROR_CODE.get(ERROR_STATE.FIREWALL_POLICY_NOT_EXIST));
        }

        // load VM state file
        Properties prop = new Properties();
        String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME;

        prop.load(new FileInputStream(new File(filename)));

        // cannot switch when VM is not running
        VMState currentState = VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE)));

        if (!currentState.equals(VMState.RUNNING)) {
            logger.error("Cannot perform switch when VM is not running");
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_RUNNING));
        }

        // get current mode
        VMMode currentMode = VMMode.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE)));

        if (currentMode.equals(requestedMode)) {
            logger.error(String.format("VM is already in the requested mode: %s", requestedMode.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_ALREADY_IN_REQUESTED_MODE));
        }

        // switch VM
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        // update firewall policy
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH), policyFilePath);

        // update VM status file, i.e. set mode to the requested mode
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE), requestedMode.toString());

        // save VM state file back
        prop.store(new FileOutputStream(new File(filename)), "");

        // success
        System.exit(0);
    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (FileNotFoundException e) {
        logger.error(String.format("Cannot find vm state file: %s", e.getMessage()));

        System.exit(ERROR_CODE.get(ERROR_STATE.VM_STATE_FILE_NOT_FOUND));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }
}

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

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

    StringBuilder commandList = new StringBuilder();
    for (DeviceCommand cmd : DeviceCommand.values()) {
        if (commandList.length() > 0) {
            commandList.append(", ");
        }/*from  www  .j av a  2 s . c o  m*/
        commandList.append(cmd.toString());
    }

    options.addOption(Option //
            .builder() //
            .longOpt("base-url") //
            .desc("Sets the base URL of the web service") //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("u") //
            .longOpt("username") //
            .desc("The username for authentication (usually mail address)") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("p") //
            .longOpt("password") //
            .desc("The password for authentication") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("c") //
            .longOpt("command") //
            .desc(String.format("The command, which should be sent to the device (%s)", commandList)) //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("q") //
            .longOpt("query-status") //
            .desc("Queries the status of the device") //
            .build());
    options.addOption(Option //
            .builder() //
            .longOpt("query-calendar") //
            .desc("Queries the calendar of the device") //
            .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(CmdLineTool.class.getName(), options);
        System.exit(1);
        return;
    }

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

    String baseUrl = cmds.getOptionValue("base-url");
    String username = cmds.getOptionValue('u');
    String password = cmds.getOptionValue('p');
    String commandStr = cmds.getOptionValue('c');
    boolean doQueryState = cmds.hasOption('q');
    boolean doQueryCalendar = cmds.hasOption("query-calendar");

    DeviceCommand command = null;
    if (commandStr != null) {
        try {
            command = DeviceCommand.valueOf(commandStr.toUpperCase());
        } catch (IllegalArgumentException ex) {
            System.err.println("Unknown command: " + commandStr);
            System.exit(1);
        }
    }

    IndegoController controller = new IndegoController(baseUrl, username, password);
    try {
        System.out.println("Connecting to device");
        controller.connect();
        System.out.println(String.format("...Connection established. Device serial number is: %s",
                controller.getDeviceSerialNumber()));
        if (command != null) {
            System.out.println(String.format("Sending command (%s)...", command));
            controller.sendCommand(command);
            System.out.println("...Command sent successfully!");
        }
        if (doQueryState) {
            System.out.println("Querying device state");
            DeviceStateInformation state = controller.getState();
            printState(System.out, state);
        }
        if (doQueryCalendar) {
            System.out.println("Querying device calendar");
            DeviceCalendar calendar = controller.getCalendar();
            printCalendar(System.out, calendar);
        }
    } catch (IndegoException ex) {
        ex.printStackTrace();
        System.exit(2);
    } finally {
        controller.disconnect();
    }
}

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

public static void main(String[] args) {
    try {//from   www. j a va2s  .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.
        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 = UploadApkWithListing.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 beta track.
        List<Integer> apkVersionCodes = new ArrayList<>();
        apkVersionCodes.add(apk.getVersionCode());
        Update updateTrackRequest = edits.tracks().update(ApplicationConfig.PACKAGE_NAME, editId, TRACK_BETA,
                new Track().setVersionCodes(apkVersionCodes));
        Track updatedTrack = updateTrackRequest.execute();
        log.info(String.format("Track %s has been updated.", updatedTrack.getTrack()));

        // Update recent changes field in apk listing.
        final ApkListing newApkListing = new ApkListing();
        newApkListing.setRecentChanges(APK_LISTING_RECENT_CHANGES_TEXT);

        Apklistings.Update updateRecentChangesRequest = edits.apklistings().update(
                ApplicationConfig.PACKAGE_NAME, editId, apk.getVersionCode(), Locale.US.toString(),
                newApkListing);
        updateRecentChangesRequest.execute();
        log.info("Recent changes has been updated.");

        // 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("Exception was thrown while uploading apk and updating recent changes", ex);
    }
}

From source file:com.dhenton9000.screenshots.ScreenShotLauncher.java

/**
 * main launching method that takes command line arguments
 *
 * @param args/* w ww . j a v  a 2  s  . c o m*/
 */
public static void main(String[] args) {

    final String[] actions = { ACTIONS.source.toString(), ACTIONS.target.toString(),
            ACTIONS.compare.toString() };
    final List actionArray = Arrays.asList(actions);

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("action").hasArg().isRequired().withArgName("action").create());
    HelpFormatter formatter = new HelpFormatter();

    String header = "Process screenshots\n" + "--action=source   create source screenshots\n"
            + "--action=target     create the screenshots for comparison\n"
            + "--action=compare  compare the images\n" + "%s\n\n";

    String action = null;
    try {
        // parse the command line arguments
        CommandLineParser parser = new PosixParser();
        CommandLine line = parser.parse(options, args);

        // validate that action option has been set
        if (line.hasOption("action")) {
            action = line.getOptionValue("action");
            LOG.debug("action '" + action + "'");
            if (!actionArray.contains(action)) {

                formatter.printHelp(ScreenShotLauncher.class.getName(),
                        String.format(header, String.format("action option '%s' is invalid", action)), options,
                        "\n\n", true);
                System.exit(1);

            }

        } else {
            formatter.printHelp(ScreenShotLauncher.class.getName(), String.format(header, "not found"), options,
                    "\n\n", false);
            System.exit(1);
        }
    } catch (ParseException exp) {
        formatter.printHelp(ScreenShotLauncher.class.getName(),
                String.format(header, "problem " + exp.getMessage()), options, "\n\n", false);
        System.exit(1);

    }
    ACTIONS actionEnum = ACTIONS.valueOf(action);
    ScreenShotLauncher launcher = new ScreenShotLauncher();
    try {
        launcher.handleRequest(actionEnum);
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);

    }
}