Example usage for org.apache.commons.lang3 StringUtils isEmpty

List of usage examples for org.apache.commons.lang3 StringUtils isEmpty

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils isEmpty.

Prototype

public static boolean isEmpty(final CharSequence cs) 

Source Link

Document

Checks if a CharSequence is empty ("") or null.

 StringUtils.isEmpty(null)      = true StringUtils.isEmpty("")        = true StringUtils.isEmpty(" ")       = false StringUtils.isEmpty("bob")     = false StringUtils.isEmpty("  bob  ") = false 

NOTE: This method changed in Lang version 2.0.

Usage

From source file:net.phoenix.thrift.server.Server.java

/**
 * ? spring?//  ww  w.jav a  2 s .com
 * @param args
 * @throws Exception
 */
public static int main(String[] args) throws Exception {
    if (args.length == 0 || StringUtils.isEmpty(args[0])) {
        LOG.error("Please assign spring configuration file . ");
        return 0;
    }
    FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext();
    context.setConfigLocation(args[0]);
    context.registerShutdownHook();
    context.refresh();
    context.close();
    return 1;
}

From source file:com.thinkbiganalytics.kerberos.TestKerberosKinit.java

public static void main(String[] args) throws Exception {
    final TestKerberosKinit testKerberosKinit = new TestKerberosKinit();
    Scanner scanner = new Scanner(System.in);

    System.out.println(" ");
    System.out.print("Which environment are you in? Enter 1 for HDP or 2 for Cloudera: ");
    String environmentCode = scanner.nextLine();
    if (StringUtils.isEmpty(environmentCode)) {
        environmentCode = "1";
    }/*from w  w w  .j a v  a  2s. c om*/

    String environment;
    switch (environmentCode) {
    case "1":
        environment = ENVIRONMENT_HDP;
        break;
    case "2":
        environment = ENVIRONMENT_CLOUDERA;
        break;
    default:
        throw new Exception("Invalid environment code");
    }

    System.out.println(" ");
    System.out.println(
            "Hit enter to default to: /etc/hadoop/conf/core-site.xml,/etc/hadoop/conf/hdfs-site.xml,/usr/hdp/current/hive-client/conf/hive-site.xml");
    System.out.print("Please enter the list of configuration resources: ");
    String configResources = scanner.nextLine();
    if (StringUtils.isEmpty(configResources)) {
        configResources = "/etc/hadoop/conf/core-site.xml,/etc/hadoop/conf/hdfs-site.xml,/usr/hdp/current/hive-client/conf/hive-site.xml";
    }

    System.out.println(" ");
    System.out.println("Hit enter to default to: /etc/security/keytabs/hive-thinkbig.headless.keytab");
    System.out.print("Please enter the keytab file location: ");
    String keytab = scanner.nextLine();
    if (StringUtils.isEmpty(keytab)) {
        keytab = "/etc/security/keytabs/hive-thinkbig.headless.keytab";
    }

    System.out.println(" ");
    System.out.println("Hit enter to default to: hive/sandbox.hortonworks.com@sandbox.hortonworks.com");
    System.out.print("Please enter the real user principal name: ");
    String realUserPrincipal = scanner.nextLine();
    if (StringUtils.isEmpty(realUserPrincipal)) {
        realUserPrincipal = "hive/sandbox.hortonworks.com@sandbox.hortonworks.com";
    }

    System.out.println(" ");
    System.out.println("Please enter Y/N (default is N)");
    System.out.print("Do you want to test with a proxy user: ");
    String proxyUser = scanner.nextLine();
    if (StringUtils.isEmpty(realUserPrincipal)) {
        proxyUser = "N";
    }

    System.out.println(" ");
    System.out.println("Hit enter to default to: hdfs://sandbox.hortonworks.com:8020");
    System.out.print("Please enter the HDFS URL: ");
    String hdfsUrl = scanner.nextLine();
    if (StringUtils.isEmpty(hdfsUrl)) {
        hdfsUrl = "hdfs://sandbox.hortonworks.com:8020";
    }

    System.out.println(" ");
    System.out.println("Hit enter to default to: jdbc:hive2://localhost:10000/default");
    System.out.print("Please enter the Hive base connection string: ");
    String hiveHost = scanner.nextLine();
    if (StringUtils.isEmpty(hiveHost)) {
        hiveHost = "jdbc:hive2://localhost:10000/default";
    }

    String proxyUserName = null;
    if ("Y".equalsIgnoreCase(proxyUser)) {
        System.out.println(" ");
        System.out.print("Please enter the proxy user: ");
        proxyUserName = scanner.next();
    }

    System.out.println(" ");
    System.out.println("Executing Kinit to generate a kerberos ticket");

    if ("Y".equalsIgnoreCase(proxyUser)) {
        System.out.println("Testing with the proxy user: " + proxyUserName);
        testKerberosKinit.testHdfsWithUserImpersonation(configResources, keytab, realUserPrincipal,
                proxyUserName, environment, hdfsUrl);

        //testKerberosKinit.testHiveJdbcConnectionWithUserImpersonation(configResources, keytab, realUserPrincipal, proxyUserName);
        testKerberosKinit.testHiveJdbcConnection(configResources, keytab, realUserPrincipal, proxyUserName,
                hiveHost);
    } else {
        System.out.println("No Proxy User");
        testKerberosKinit.testHdfsAsKerberosUser(configResources, keytab, realUserPrincipal, environment,
                hdfsUrl);
        testKerberosKinit.testHiveJdbcConnection(configResources, keytab, realUserPrincipal, null, hiveHost);
    }
}

From source file:net.sfr.tv.mom.mgt.HornetqConsole.java

/**
 * @param args the command line arguments
 *///from   w  ww .j ava  2  s  .  c  om
public static void main(String[] args) {

    try {

        String jmxHost = "127.0.0.1";
        String jmxPort = "6001";

        // Process command line arguments
        String arg;
        for (int i = 0; i < args.length; i++) {
            arg = args[i];
            switch (arg) {
            case "-h":
                jmxHost = args[++i];
                break;
            case "-p":
                jmxPort = args[++i];
                break;
            default:
                break;
            }
        }

        // Check for arguments consistency
        if (StringUtils.isEmpty(jmxHost) || !NumberUtils.isNumber(jmxPort)) {
            LOGGER.info("Usage : ");
            LOGGER.info("hq-console.jar <-h host(127.0.0.1)> <-p port(6001)>\n");
            System.exit(1);
        }

        System.out.println(
                SystemUtils.LINE_SEPARATOR.concat(Ansi.format("HornetQ Console ".concat(VERSION), Color.CYAN)));

        final StringBuilder _url = new StringBuilder("service:jmx:rmi://").append(jmxHost).append(':')
                .append(jmxPort).append("/jndi/rmi://").append(jmxHost).append(':').append(jmxPort)
                .append("/jmxrmi");

        final String jmxServiceUrl = _url.toString();
        JMXConnector jmxc = null;

        final CommandRouter router = new CommandRouter();

        try {
            jmxc = JMXConnectorFactory.connect(new JMXServiceURL(jmxServiceUrl), null);
            assert jmxc != null; // jmxc must be not null
        } catch (final MalformedURLException e) {
            System.out.println(SystemUtils.LINE_SEPARATOR
                    .concat(Ansi.format(jmxServiceUrl + " :" + e.getMessage(), Color.RED)));
        } catch (Throwable t) {
            System.out.println(SystemUtils.LINE_SEPARATOR.concat(
                    Ansi.format("Unable to connect to JMX service URL : ".concat(jmxServiceUrl), Color.RED)));
            System.out.print(SystemUtils.LINE_SEPARATOR.concat(
                    Ansi.format("Did you add jmx-staticport-agent.jar to your classpath ?", Color.MAGENTA)));
            System.out.println(SystemUtils.LINE_SEPARATOR.concat(Ansi.format(
                    "Or did you set the com.sun.management.jmxremote.port option in the hornetq server startup script ?",
                    Color.MAGENTA)));
            System.exit(-1);
        }

        System.out.println("\n".concat(Ansi
                .format("Successfully connected to JMX service URL : ".concat(jmxServiceUrl), Color.YELLOW)));

        final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        // PRINT SERVER STATUS REPORT
        System.out.print((String) router.get(Command.STATUS, Option.VM).execute(mbsc, null));
        System.out.print((String) router.get(Command.STATUS, Option.SERVER).execute(mbsc, null));
        System.out.print((String) router.get(Command.STATUS, Option.CLUSTER).execute(mbsc, null));

        printHelp(router);

        // START COMMAND LINE
        Scanner scanner = new Scanner(System.in);
        System.out.print("> ");
        String input;
        while (!(input = scanner.nextLine().concat(" ")).equals("exit ")) {

            String[] cliArgs = input.split("\\ ");
            CommandHandler handler;

            if (cliArgs.length < 1) {
                System.out.print("> ");
                continue;
            }

            Command cmd = Command.fromString(cliArgs[0]);
            if (cmd == null) {
                System.out.print(Ansi.format("Syntax error !", Color.RED).concat("\n"));
                cmd = Command.HELP;
            }

            switch (cmd) {
            case STATUS:
            case LIST:
            case DROP:

                Set<Option> options = router.get(cmd);

                for (Option opt : options) {

                    if (cliArgs[1].equals(opt.toString())) {
                        handler = router.get(cmd, opt);

                        String[] cmdOpts = null;
                        if (cliArgs.length > 2) {
                            cmdOpts = new String[cliArgs.length - 2];
                            for (int i = 0; i < cmdOpts.length; i++) {
                                cmdOpts[i] = cliArgs[2 + i];
                            }
                        }

                        Object result = handler.execute(mbsc, cmdOpts);
                        if (result != null && String.class.isAssignableFrom(result.getClass())) {
                            System.out.print((String) result);
                        }
                        System.out.print("> ");
                    }
                }

                break;

            case FORK:
                // EXECUTE SYSTEM COMMAND
                ProcessBuilder pb = new ProcessBuilder(Arrays.copyOfRange(cliArgs, 1, cliArgs.length));
                pb.inheritIO();
                pb.start();
                break;

            case HELP:
                printHelp(router);
                break;
            }
        }
    } catch (MalformedURLException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }

    echo(SystemUtils.LINE_SEPARATOR.concat(Ansi.format("Bye!", Color.CYAN)));

}

From source file:io.pivotal.kr.load_gen.Main.java

public static void main(String[] args) throws IOException {
    if (args.length != 6) {
        System.err.println(/*from   w w  w .j a  va  2 s .  co  m*/
                "Correct usage: java -jar load-gen.jar <batch|autocommit> <insert|select|update|delete> <dataDir> <sqlMapConfigXMLPath> <delimiter> <numberOfThreads>");

        System.exit(-1);
    }

    String type = args[0];
    String mode = args[1];
    String dataDir = args[2];
    String sqlMapConfigXMLPath = args[3];
    String delimiter = args[4];
    String numberOfThreads = args[5];

    if (StringUtils.isEmpty(type) || StringUtils.isEmpty(mode) || StringUtils.isEmpty(dataDir)
            || StringUtils.isEmpty(sqlMapConfigXMLPath) || StringUtils.isEmpty(delimiter)
            || StringUtils.isEmpty(numberOfThreads)) {
        System.err.println(
                "Correct usage: java -jar load-gen.jar <batch|autocommit> <insert|select|update|delete> <dataDir> <sqlMapConfigXMLPath> <delimiter> <numberOfThreads>");

        System.exit(-1);
    }

    dataDir = stripSurroundingQuotes(dataDir);
    sqlMapConfigXMLPath = stripSurroundingQuotes(sqlMapConfigXMLPath);
    delimiter = stripSurroundingQuotes(delimiter);

    new GemfireXDLoadManager(type, mode, dataDir, sqlMapConfigXMLPath, delimiter,
            Integer.parseInt(numberOfThreads));
}

From source file:com.jkoolcloud.tnt4j.streams.configure.zookeeper.ZKConfigInit.java

/**
 * Main entry point for running as a standalone application.
 *
 * @param args/*from ww  w.  j  a v a2 s.  co m*/
 *            command-line arguments. Supported arguments:
 *            <table summary="TNT4J-Streams configuration uploader to ZooKeeper command line arguments">
 *            <tr>
 *            <td>&nbsp;&nbsp;</td>
 *            <td>&nbsp;-f:&lt;cfg_file_name&gt;</td>
 *            <td>(optional) Load TNT4J-Streams configuration upload to ZooKeeper configuration from
 *            &lt;cfg_file_name&gt;</td>
 *            </tr>
 *            <tr>
 *            <td>&nbsp;&nbsp;</td>
 *            <td>&nbsp;&nbsp;&nbsp;-c</td>
 *            <td>(optional) Clean ZooKeeper contained TNT4J-Streams configuration</td>
 *            </tr>
 *            </table>
 */
public static void main(String... args) {
    LOGGER.log(OpLevel.INFO,
            StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "ZKConfigInit.starting.main"));
    boolean argsValid = processArgs(args);
    if (argsValid) {
        if (StringUtils.isEmpty(cfgFileName)) {
            LOGGER.log(OpLevel.ERROR, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                    "ZKConfigInit.upload.cfg.not.defined"));
            System.exit(2);
        } else {
            loadConfigAndRun(cfgFileName);
        }
    }

    System.exit(argsValid ? 0 : 1);
}

From source file:by.lang.StringUtilsTest.java

public static void main(String[] args) {
    System.out.println("?,....");
    System.out.println(StringUtils.abbreviate("The quick brown fox jumps over the lazy dog.", 10));

    System.out.println(".");
    System.out.println(StringUtils.chomp("1,2,3,", ","));

    System.out.println("???.");
    System.out.println(StringUtils.contains("defg", "ef"));
    System.out.println(StringUtils.contains("ef", "defg"));

    System.out.println("??nulltoString().");
    System.out.println(StringUtils.defaultString(null, "defaultIfEmpty"));
    System.out.println(".");
    System.out.println(StringUtils.deleteWhitespace("aa  bb  cc"));

    System.out.println("??.");
    System.out.println(StringUtils.isAlpha("ab"));
    System.out.println(StringUtils.isAlphanumeric("12"));
    System.out.println(StringUtils.isBlank(""));
    System.out.println(StringUtils.isNumeric("123"));

    System.out.println("?Null  \"\"");
    System.out.println(StringUtils.isEmpty(null));
    System.out.println(StringUtils.isNotEmpty(null));
    System.out.println("?null  \"\" ");
    System.out.println(StringUtils.isBlank("  "));
    System.out.println(StringUtils.isNotBlank(null));
    System.out.println(".Nullnull");
    System.out.println(StringUtils.trim(null));
    System.out.println("Null\"\" ?Null");
    System.out.println(StringUtils.trimToNull(""));
    // NULL  "" ?""
    // System.out.println(StringUtils.trimToEmpty(null));
    // ??/*from   w w w .  j a va2  s.c  o  m*/
    // System.out.println(StringUtils.strip("  \t"));
    // ?""null?Null
    // System.out.println(StringUtils.stripToNull(" \t"));
    // ?""null?""
    // System.out.println(StringUtils.stripToEmpty(null));
    // ""Null ? ""
    // System.out.println(StringUtils.defaultString(null));
    // Null ?(?)
    // System.out.println(StringUtils.defaultString("", "df"));
    // null""?(?)
    // System.out.println(StringUtils.defaultIfEmpty(null, "sos"));
    // .~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ?null(?2?)
    // System.out.println(StringUtils.strip("fsfsdf", "f"));
    // ?null???(????)
    // System.out.println(StringUtils.stripStart("ddsuuu ", "d"));
    // ?null???(????)
    // System.out.println(StringUtils.stripEnd("dabads", "das"));
    // 
    // ArrayToList(StringUtils.stripAll(new String[]{" ? ", "  ",
    // " "}));
    // ?null.?(??)
    // ArrayToList(StringUtils.stripAll(new String[]{" ? ", " ", ""},
    // ""));
    // ,~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // 2?,Null
    // System.out.println(StringUtils.equals(null, null));
    // ??
    // System.out.println(StringUtils.equalsIgnoreCase("abc", "ABc"));
    // ????~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ?null""-1
    // System.out.println(StringUtils.indexOf(null, "a"));
    // ?(?)2k
    // System.out.println(StringUtils.indexOf("akfekcd?", "k", 2));
    // ???
    // System.out.println(StringUtils.ordinalIndexOf("akfekcd?", "k", 2));
    // ,??
    // System.out.println(StringUtils.indexOfIgnoreCase("adfs", "D"));
    // ?(?),??
    // System.out.println(StringUtils.indexOfIgnoreCase("adfs", "a", 3));
    // ??
    // System.out.println(StringUtils.lastIndexOf("adfas", "a"));
    // ?,2
    // System.out.println(StringUtils.lastIndexOf("dabasdafs", "a", 3));
    // ,-1
    // System.out.println(StringUtils.lastOrdinalIndexOf("yksdfdht", "f",
    // 2));
    // ????
    // System.out.println(StringUtils.lastIndexOfIgnoreCase("sdffet", "E"));
    // ,1
    // System.out.println(StringUtils.lastIndexOfIgnoreCase("efefrfs", "F"
    // , 2));
    // ?boolean,null?
    // System.out.println(StringUtils.contains("sdf", "dg"));
    // ?boolean,null?,??
    // System.out.println(StringUtils.containsIgnoreCase("sdf", "D"));
    // ??,boolean
    // System.out.println(StringUtils.containsWhitespace(" d"));
    // ???
    // System.out.println(StringUtils.indexOfAny("absfekf", new
    // String[]{"f", "b"}));
    // (?)
    // System.out.println(StringUtils.indexOfAny("afefes", "e"));
    // ??boolean
    // System.out.println(StringUtils.containsAny("asfsd", new char[]{'k',
    // 'e', 's'}));
    // ?lastIndexOf???boolean
    // System.out.println(StringUtils.containsAny("f", ""));
    // 
    // System.out.println(StringUtils.indexOfAnyBut("seefaff", "af"));
    // ?
    // System.out.println(StringUtils.containsOnly("??", "?"));
    // ?
    // System.out.println(StringUtils.containsOnly("?", new char[]{'',
    // '?'}));
    // ??
    // System.out.println(StringUtils.containsNone("??", ""));
    // ??
    // System.out.println(StringUtils.containsNone("?", new char[]{'',
    // ''}));
    // ????4
    // System.out.println(StringUtils.lastIndexOfAny("", new
    // String[]{"", ""}));
    // ?indexOfAny?? (?)
    // System.out.println(StringUtils.countMatches("", ""));
    // ?CharSequence??Unicode?falseCharSequence=
    // 0true
    // System.out.println(StringUtils.isAlpha("2"));
    // ???UnicodeCharSequence?''CharSequence?=
    // 0true
    // System.out.println(StringUtils.isAlphaSpace("NBA "));
    // ???UnicodeCharSequence?falseCharSequence=
    // 0true
    // System.out.println(StringUtils.isAlphanumeric("NBA"));
    // Unicode
    // CharSequence???''falseCharSequence=
    // 0true
    // System.out.println(StringUtils.isAlphanumericSpace("NBA"));
    // ???ASCII?CharSequencefalseCharSequence=
    // 0true
    // System.out.println(StringUtils.isAsciiPrintable("NBA"));
    // ???
    // System.out.println(StringUtils.isNumeric("NBA"));
    // ???
    // System.out.println(StringUtils.isNumericSpace("33 545"));
    // ??""
    // System.out.println(StringUtils.isWhitespace(" "));
    // ??
    // System.out.println(StringUtils.isAllLowerCase("kjk33"));
    // ?
    // System.out.println(StringUtils.isAllUpperCase("KJKJ"));
    // ?~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ?2?:
    // System.out.println(StringUtils.difference("", ""));
    // 2
    // System.out.println(StringUtils.indexOfDifference("ww.taobao",
    // "www.taobao.com"));
    // ?
    // System.out.println(StringUtils.indexOfDifference(new String[]
    // {"", "", ""}));
    // ???
    // System.out.println(StringUtils.getCommonPrefix(new String[] {"",
    // "", ""}));
    // ??????
    // System.out.println(StringUtils.getLevenshteinDistance("?",
    // ""));
    // ???
    // System.out.println(StringUtils.startsWith("", ""));
    // ?????
    // System.out.println(StringUtils.startsWithIgnoreCase("",
    // ""));
    // ???
    // System.out.println(StringUtils.startsWithAny("abef", new
    // String[]{"ge", "af", "ab"}));
    // ??
    // System.out.println(StringUtils.endsWith("abcdef", "def"));
    // ????
    // System.out.println(StringUtils.endsWithIgnoreCase("abcdef", "Def"));
    // ?~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ??nullnull.""""
    // System.out.println(StringUtils.substring("", 2));
    // ?
    // System.out.println(StringUtils.substring("", 2, 4));
    // ?
    // System.out.println(StringUtils.left("", 3));
    // ??
    // System.out.println(StringUtils.right("", 3));
    // ???
    // System.out.println(StringUtils.mid("", 3, 2));
    // ??
    // System.out.println(StringUtils.substringBefore("", ""));
    // ?????
    // System.out.println(StringUtils.substringAfter("", ""));
    // ??.
    // System.out.println(StringUtils.substringBeforeLast("", ""));
    // ?????
    // System.out.println(StringUtils.substringAfterLast("", ""));
    // ???null:2010?
    // System.out.println(StringUtils.substringBetween("??2010?????",
    // "??"));
    // ???
    // ArrayToList(StringUtils.substringsBetween("[a][b][c]", "[", "]"));
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ?nullnull
    // ArrayToList(StringUtils.split("?  "));
    // ?
    // ArrayToList(StringUtils.split("? ,,", ","));
    // ???0
    // ArrayToList(StringUtils.split("? ", "", 2));
    // ???,?
    // ArrayToList(StringUtils.splitByWholeSeparator("ab-!-cd-!-ef",
    // "-!-"));
    // ???,???
    // ArrayToList(StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-",
    // 2));
    // " "?,?null
    // ArrayToList(StringUtils.splitByWholeSeparatorPreserveAllTokens(" ab
    // de fg ",
    // null));
    // ?," "??
    // ArrayToList(StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de
    // fg",
    // null, 3));
    // ???,
    // ArrayToList(StringUtils.splitPreserveAllTokens(" ab de fg "));
    // ???,?
    // ArrayToList(StringUtils.splitPreserveAllTokens(" ab de fg ",
    // null));
    // ???,???
    // ArrayToList(StringUtils.splitPreserveAllTokens(" ab de fg ", null,
    // 2));
    // ??
    // ArrayToList(StringUtils.splitByCharacterType("AEkjKr i39:"));
    // 
    // ArrayToList(StringUtils.splitByCharacterTypeCamelCase("ASFSRules234"));
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ??
    // System.out.println(StringUtils.concat(getArrayData()));
    // ?.?null
    // System.out.println(StringUtils.concatWith(",", getArrayData()));
    // ?
    // System.out.println(StringUtils.join(getArrayData()));
    // ?
    // System.out.println(StringUtils.join(getArrayData(), ":"));
    // (?)?(?,??)
    // System.out.println(StringUtils.join(getArrayData(), ":", 1, 3));
    // ?.?
    // System.out.println(StringUtils.join(getListData(), ":"));
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // 
    // System.out.println(StringUtils.deleteWhitespace(" s   4j"));
    // ?
    // System.out.println(StringUtils.removeStart("www.baidu.com", "www."));
    // ?,??
    // System.out.println(StringUtils.removeStartIgnoreCase("www.baidu.com",
    // "WWW"));
    // ???
    // System.out.println(StringUtils.removeEnd("www.baidu.com", ".com"));
    // ?????
    // System.out.println(StringUtils.removeEndIgnoreCase("www.baidu.com",
    // ".COM"));
    // ?
    // System.out.println(StringUtils.remove("www.baidu.com/baidu", "bai"));
    // "\n", "\r",  "\r\n".
    // System.out.println(StringUtils.chomp("abcrabc\r"));
    // ?
    // System.out.println(StringUtils.chomp("baidu.com", "com"));
    // ?."\n", "\r",  "\r\n"
    // System.out.println(StringUtils.chop("wwe.baidu"));
    // ?~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ???
    // System.out.println(StringUtils.replaceOnce("www.baidu.com/baidu",
    // "baidu", "hao123"));
    // ?
    // System.out.println(StringUtils.replace("www.baidu.com/baidu",
    // "baidu", "hao123"));
    // ????
    // System.out.println(StringUtils.replace("www.baidu.com/baidu",
    // "baidu", "hao123", 1));
    // ?????:baidu?taobaocom?net
    // System.out.println(StringUtils.replaceEach("www.baidu.com/baidu", new
    // String[]{"baidu", "com"}, new String[]{"taobao", "net"}));
    // ????
    // System.out.println(StringUtils.replaceEachRepeatedly("www.baidu.com/baidu",
    // new String[]{"baidu", "com"}, new String[]{"taobao", "net"}));
    // ????.(????)
    // System.out.println(StringUtils.replaceChars("www.baidu.com", "bdm",
    // "qo"));
    // ?(?)?(?)
    // System.out.println(StringUtils.overlay("www.baidu.com", "hao123", 4,
    // 9));
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ????
    // System.out.println(StringUtils.repeat("ba", 3));
    // ??????
    // System.out.println(StringUtils.repeat("ab", "ou", 3));
    // ??(???)
    // System.out.println(StringUtils.rightPad("?", 4));
    // ????(?)
    // System.out.println(StringUtils.rightPad("?", 4, "?"));
    // ???
    // System.out.println(StringUtils.leftPad("?", 4));
    // ??????(?)
    // System.out.println(StringUtils.leftPad("?", 4, ""));
    // ?????
    // System.out.println(StringUtils.center("?", 3));
    // ??????
    // System.out.println(StringUtils.center("?", 5, "?"));
    // ??(?),??(??+=?)
    // System.out.println(StringUtils.abbreviate("?", 5));
    // 2: ...ijklmno
    // System.out.println(StringUtils.abbreviate("abcdefghijklmno", 12,
    // 10));
    // ???.: ab.f
    // System.out.println(StringUtils.abbreviateMiddle("abcdef", ".", 4));
    // ?,~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // ?.
    // System.out.println(StringUtils.capitalize("Ddf"));
    // ?.
    // System.out.println(StringUtils.uncapitalize("DTf"));
    // ????????
    // System.out.println(StringUtils.swapCase("I am Jiang, Hello"));
    // ?
    // System.out.println(StringUtils.reverse(""));
    // ?(?)??
    // System.out.println(StringUtils.reverseDelimited("::", ':'));
    // isEmpty
    System.out.println(StringUtils.isEmpty(null)); // true
    System.out.println(StringUtils.isEmpty("")); // true
    System.out.println(StringUtils.isEmpty(" ")); // false
    System.out.println(StringUtils.isEmpty("bob")); // false
    System.out.println(StringUtils.isEmpty("  bob  ")); // false

    // isBlank
    System.out.println(StringUtils.isBlank(null)); // true
    System.out.println(StringUtils.isBlank("")); // true
    System.out.println(StringUtils.isBlank(" ")); // true
    System.out.println(StringUtils.isBlank("bob")); // false
    System.out.println(StringUtils.isBlank("  bob  ")); // false

    // trim
    System.out.println(StringUtils.trim(null)); // null
    System.out.println(StringUtils.trim("")); // ""
    System.out.println(StringUtils.trim("     ")); // ""
    System.out.println(StringUtils.trim("abc")); // "abc"
    System.out.println(StringUtils.trim("    abc")); // "abc"
    System.out.println(StringUtils.trim("    abc  ")); // "abc"
    System.out.println(StringUtils.trim("    ab c  ")); // "ab c"

    // strip
    System.out.println(StringUtils.strip(null)); // null
    System.out.println(StringUtils.strip("")); // ""
    System.out.println(StringUtils.strip("   ")); // ""
    System.out.println(StringUtils.strip("abc")); // "abc"
    System.out.println(StringUtils.strip("  abc")); // "abc"
    System.out.println(StringUtils.strip("abc  ")); // "abc"
    System.out.println(StringUtils.strip(" abc ")); // "abc"
    System.out.println(StringUtils.strip(" ab c ")); // "ab c"
    System.out.println(StringUtils.strip("  abcyx", "xyz")); // " abc"
    System.out.println(StringUtils.stripStart("yxabcxyz  ", "xyz")); // "abcxyz
    // "
    System.out.println(StringUtils.stripEnd("  xyzabcyx", "xyz")); // "
    // xyzabc"
    // ?
    String str1 = "aaa bbb ccc";
    String[] dim1 = StringUtils.split(str1); // => ["aaa", "bbb", "ccc"]

    System.out.println(dim1.length);// 3
    System.out.println(dim1[0]);// "aaa"
    System.out.println(dim1[1]);// "bbb"
    System.out.println(dim1[2]);// "ccc"

    // 
    String str2 = "aaa,bbb,ccc";
    String[] dim2 = StringUtils.split(str2, ","); // => ["aaa", "bbb",
    // "ccc"]

    System.out.println(dim2.length);// 3
    System.out.println(dim2[0]);// "aaa"
    System.out.println(dim2[1]);// "bbb"
    System.out.println(dim2[2]);// "ccc"

    // 
    String str3 = "aaa,,bbb";
    String[] dim3 = StringUtils.split(str3, ","); // => ["aaa", "bbb"]

    System.out.println(dim3.length);// 2
    System.out.println(dim3[0]);// "aaa"
    System.out.println(dim3[1]);// "bbb"

    // ?
    String str4 = "aaa,,bbb";
    String[] dim4 = StringUtils.splitPreserveAllTokens(str4, ","); // =>
    // ["aaa",
    // "",
    // "bbb"]

    System.out.println(dim4.length);// 3
    System.out.println(dim4[0]);// "aaa"
    System.out.println(dim4[1]);// ""
    System.out.println(dim4[2]);// "bbb"

    // ??
    String str5 = "aaa,bbb,ccc";
    String[] dim5 = StringUtils.split(str5, ",", 2); // => ["aaa",
    // "bbb,ccc"]

    System.out.println(dim5.length);// 2
    System.out.println(dim5[0]);// "aaa"
    System.out.println(dim5[1]);// "bbb,ccc"

    // 
    String[] array = { "aaa", "bbb", "ccc" };
    String result1 = StringUtils.join(array, ",");

    System.out.println(result1);// "aaa,bbb,ccc"

    // ?
    List<String> list = new ArrayList<String>();
    list.add("aaa");
    list.add("bbb");
    list.add("ccc");
    String result2 = StringUtils.join(list, ",");
    System.out.println(result2);// "aaa,bbb,ccc"

}

From source file:friendsandfollowers.DBFollowersIDs.java

public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException,
        FileNotFoundException, UnsupportedEncodingException {

    // Check arguments that passed in
    if ((args == null) || (args.length == 0)) {
        System.err.println("2 Parameters are required plus one optional " + "parameter to launch a Job.");
        System.err.println("First: String 'OUTPUT: /output/path/'");
        System.err.println("Second: (int) Number of ids to fetch. " + "Provide number which increment by 5000 "
                + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids.");
        System.err.println("Third (optional): 'screen_name / user_id_str'");
        System.err.println("If 3rd argument not provided then provide" + " Twitter users through database.");
        System.exit(-1);// ww  w .j a v a2  s .c o  m
    }

    MysqlDB DB = new MysqlDB();
    AppOAuth AppOAuths = new AppOAuth();
    Misc helpers = new Misc();
    String endpoint = "/followers/ids";

    String OutputDirPath = null;
    try {
        OutputDirPath = StringEscapeUtils.escapeJava(args[0]);
    } catch (Exception e) {
        System.err.println("Argument" + args[0] + " must be an String.");
        System.exit(-1);
    }

    int IDS_TO_FETCH_INT = -1;
    try {
        IDS_TO_FETCH_INT = Integer.parseInt(args[1]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + args[1] + " must be an integer.");
        System.exit(-1);
    }

    int IDS_TO_FETCH = 0;
    if (IDS_TO_FETCH_INT > 5000) {

        float IDS_TO_FETCH_F = (float) IDS_TO_FETCH_INT / 5000;
        IDS_TO_FETCH = (int) Math.ceil(IDS_TO_FETCH_F);
    } else if ((IDS_TO_FETCH_INT <= 5000) && (IDS_TO_FETCH_INT > 0)) {
        IDS_TO_FETCH = 1;
    }

    String targetedUser = "";
    if (args.length == 3) {
        try {
            targetedUser = StringEscapeUtils.escapeJava(args[2]);
        } catch (Exception e) {
            System.err.println("Argument" + args[2] + " must be an String.");
            System.exit(-1);
        }
    }

    try {

        TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint);
        Twitter twitter = tf.getInstance();

        int RemainingCalls = AppOAuths.RemainingCalls;
        int RemainingCallsCounter = 0;
        System.out.println("First Time Remianing Calls: " + RemainingCalls);

        String Screen_name = AppOAuths.screen_name;
        System.out.println("First Time Loaded OAuth Screen_name: " + Screen_name);

        IDs ids;
        System.out.println("Listing followers ids.");

        // if targetedUser not provided by argument, then look into database.
        if (StringUtils.isEmpty(targetedUser)) {

            String selectQuery = "SELECT * FROM `followers_parent` WHERE " + "`targeteduser` != '' AND "
                    + "`nextcursor` != '0' AND " + "`nextcursor` != '2'";

            ResultSet results = DB.selectQ(selectQuery);

            int numRows = DB.numRows(results);
            if (numRows < 1) {
                System.err.println("No User in database to get followersIDS");
                System.exit(-1);
            }

            OUTERMOST: while (results.next()) {

                int followers_parent_id = results.getInt("id");
                targetedUser = results.getString("targeteduser");
                long cursor = results.getLong("nextcursor");
                System.out.println("Targeted User: " + targetedUser);

                int idsLoopCounter = 0;
                int totalIDs = 0;

                // put idsJSON in a file
                PrintWriter writer = new PrintWriter(OutputDirPath + "/" + targetedUser, "UTF-8");

                // call different functions for screen_name and id_str
                Boolean chckedNumaric = helpers.isNumeric(targetedUser);

                do {
                    ids = null;
                    try {

                        if (chckedNumaric) {

                            long LongValueTargetedUser = Long.valueOf(targetedUser).longValue();

                            ids = twitter.getFollowersIDs(LongValueTargetedUser, cursor);
                        } else {
                            ids = twitter.getFollowersIDs(targetedUser, cursor);
                        }

                    } catch (TwitterException te) {

                        // do not throw if user has protected tweets, 
                        // or if they deleted their account
                        if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED
                                || te.getStatusCode() == HttpResponseCode.NOT_FOUND) {

                            System.out.println(targetedUser + " is protected or account is deleted");
                        } else {
                            System.out.println("Followers Get Exception: " + te.getMessage());
                        }

                        // If rate limit reached then switch Auth user
                        RemainingCallsCounter++;
                        if (RemainingCallsCounter >= RemainingCalls) {

                            // load auth user
                            tf = AppOAuths.loadOAuthUser(endpoint);
                            twitter = tf.getInstance();

                            System.out.println(
                                    "New User Loaded OAuth" + " Screen_name: " + AppOAuths.screen_name);

                            RemainingCalls = AppOAuths.RemainingCalls;
                            RemainingCallsCounter = 0;

                            System.out.println("New Remianing Calls: " + RemainingCalls);
                        }

                        // update cursor in "followers_parent"
                        String fieldValues = "`nextcursor` = 2";
                        String where = "id = " + followers_parent_id;
                        DB.Update("`followers_parent`", fieldValues, where);

                        // If error then switch to next user
                        continue OUTERMOST;
                    }

                    if (ids.getIDs().length > 0) {

                        idsLoopCounter++;
                        totalIDs += ids.getIDs().length;
                        System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length);

                        JSONObject responseDetailsJson = new JSONObject();
                        JSONArray jsonArray = new JSONArray();
                        for (long id : ids.getIDs()) {
                            jsonArray.put(id);
                        }
                        Object idsJSON = responseDetailsJson.put("ids", jsonArray);

                        writer.println(idsJSON);
                    }

                    // If rate limit reached then switch Auth user
                    RemainingCallsCounter++;
                    if (RemainingCallsCounter >= RemainingCalls) {

                        // load auth user
                        tf = AppOAuths.loadOAuthUser(endpoint);
                        twitter = tf.getInstance();

                        System.out.println("New User Loaded OAuth " + "Screen_name: " + AppOAuths.screen_name);

                        RemainingCalls = AppOAuths.RemainingCalls;
                        RemainingCallsCounter = 0;

                        System.out.println("New Remianing Calls: " + RemainingCalls);
                    }

                    if (IDS_TO_FETCH_INT != -1) {
                        if (idsLoopCounter == IDS_TO_FETCH) {
                            break;
                        }
                    }

                } while ((cursor = ids.getNextCursor()) != 0);
                writer.close();
                System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs);
                System.out.println();

                // update cursor in "followers_parent"
                String fieldValues = "`nextcursor` = " + cursor;
                String where = "id = " + followers_parent_id;
                DB.Update("`followers_parent`", fieldValues, where);

            } // loop through every result found in db
        } else {

            // Second Argument Set, so we are here.
            System.out.println("screen_name / user_id_str passed by argument");

            int idsLoopCounter = 0;
            int totalIDs = 0;

            // put idsJSON in a file
            PrintWriter writer = new PrintWriter(
                    OutputDirPath + "/" + targetedUser + "_ids_" + helpers.getUnixTimeStamp(), "UTF-8");

            // call different functions for screen_name and id_str
            Boolean chckedNumaric = helpers.isNumeric(targetedUser);
            long cursor = -1;

            do {
                ids = null;
                try {

                    if (chckedNumaric) {

                        long LongValueTargetedUser = Long.valueOf(targetedUser).longValue();

                        ids = twitter.getFollowersIDs(LongValueTargetedUser, cursor);
                    } else {
                        ids = twitter.getFollowersIDs(targetedUser, cursor);
                    }

                } catch (TwitterException te) {

                    // do not throw if user has protected tweets, or if they deleted their account
                    if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED
                            || te.getStatusCode() == HttpResponseCode.NOT_FOUND) {

                        System.out.println(targetedUser + " is protected or account is deleted");
                    } else {
                        System.out.println("Followers Get Exception: " + te.getMessage());
                    }
                    System.exit(-1);
                }

                if (ids.getIDs().length > 0) {

                    idsLoopCounter++;
                    totalIDs += ids.getIDs().length;
                    System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length);

                    JSONObject responseDetailsJson = new JSONObject();
                    JSONArray jsonArray = new JSONArray();

                    for (long id : ids.getIDs()) {
                        jsonArray.put(id);
                    }

                    Object idsJSON = responseDetailsJson.put("ids", jsonArray);
                    writer.println(idsJSON);
                }

                // If rate limit reach then switch Auth user
                RemainingCallsCounter++;
                if (RemainingCallsCounter >= RemainingCalls) {

                    // load auth user
                    tf = AppOAuths.loadOAuthUser(endpoint);
                    twitter = tf.getInstance();

                    System.out.println("New User Loaded OAuth Screen_name: " + AppOAuths.screen_name);

                    RemainingCalls = AppOAuths.RemainingCalls;
                    RemainingCallsCounter = 0;

                    System.out.println("New Remianing Calls: " + RemainingCalls);
                }

                if (IDS_TO_FETCH_INT != -1) {
                    if (idsLoopCounter == IDS_TO_FETCH) {
                        break;
                    }
                }

            } while ((cursor = ids.getNextCursor()) != 0);
            writer.close();

            System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs);
            System.out.println();
        }

    } catch (TwitterException te) {
        // te.printStackTrace();
        System.err.println("Failed to get followers' ids: " + te.getMessage());
        System.exit(-1);
    }
    System.out.println("!!!! DONE !!!!");
}

From source file:friendsandfollowers.DBFriendsIDs.java

public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException,
        FileNotFoundException, UnsupportedEncodingException {

    // Check arguments that passed in
    if ((args == null) || (args.length == 0)) {
        System.err.println("2 Parameters are required plus one optional " + "parameter to launch a Job.");
        System.err.println("First: String 'OUTPUT: /output/path/'");
        System.err.println("Second: (int) Number of ids to fetch. " + "Provide number which increment by 5000 "
                + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids.");
        System.err.println("Third (optional): 'screen_name / user_id_str'");
        System.err.println("If 3rd argument not provided then provide" + " Twitter users through database.");
        System.exit(-1);//  w ww .j  a  v  a  2 s .c o  m
    }

    MysqlDB DB = new MysqlDB();
    AppOAuth AppOAuths = new AppOAuth();
    Misc helpers = new Misc();
    String endpoint = "/friends/ids";

    String OutputDirPath = null;
    try {
        OutputDirPath = StringEscapeUtils.escapeJava(args[0]);
    } catch (Exception e) {
        System.err.println("Argument" + args[0] + " must be an String.");
        System.exit(-1);
    }

    int IDS_TO_FETCH_INT = -1;
    try {
        IDS_TO_FETCH_INT = Integer.parseInt(args[1]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + args[1] + " must be an integer.");
        System.exit(-1);
    }

    int IDS_TO_FETCH = 0;
    if (IDS_TO_FETCH_INT > 5000) {

        float IDS_TO_FETCH_F = (float) IDS_TO_FETCH_INT / 5000;
        IDS_TO_FETCH = (int) Math.ceil(IDS_TO_FETCH_F);
    } else if ((IDS_TO_FETCH_INT <= 5000) && (IDS_TO_FETCH_INT > 0)) {
        IDS_TO_FETCH = 1;
    }

    String targetedUser = "";
    if (args.length == 3) {
        try {
            targetedUser = StringEscapeUtils.escapeJava(args[2]);
        } catch (Exception e) {
            System.err.println("Argument" + args[2] + " must be an String.");
            System.exit(-1);
        }
    }

    try {

        TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint);
        Twitter twitter = tf.getInstance();

        int RemainingCalls = AppOAuths.RemainingCalls;
        int RemainingCallsCounter = 0;
        System.out.println("First Time Remianing Calls: " + RemainingCalls);

        String Screen_name = AppOAuths.screen_name;
        System.out.println("First Time Loaded OAuth Screen_name: " + Screen_name);

        IDs ids;
        System.out.println("Listing friends ids.");

        // if targetedUser not provided by argument, then look into database.
        if (StringUtils.isEmpty(targetedUser)) {

            String selectQuery = "SELECT * FROM `followings_parent` WHERE " + "`targeteduser` != '' AND "
                    + "`nextcursor` != '0' AND " + "`nextcursor` != '2'";

            ResultSet results = DB.selectQ(selectQuery);

            int numRows = DB.numRows(results);
            if (numRows < 1) {
                System.err.println("No User in database to get friendsIDS");
                System.exit(-1);
            }

            OUTERMOST: while (results.next()) {

                int following_parent_id = results.getInt("id");
                targetedUser = results.getString("targeteduser");
                long cursor = results.getLong("nextcursor");
                System.out.println("Targeted User: " + targetedUser);

                int idsLoopCounter = 0;
                int totalIDs = 0;

                // put idsJSON in a file
                PrintWriter writer = new PrintWriter(OutputDirPath + "/" + targetedUser, "UTF-8");

                // call different functions for screen_name and id_str
                Boolean chckedNumaric = helpers.isNumeric(targetedUser);

                do {
                    ids = null;
                    try {

                        if (chckedNumaric) {

                            long LongValueTargetedUser = Long.valueOf(targetedUser).longValue();

                            ids = twitter.getFriendsIDs(LongValueTargetedUser, cursor);
                        } else {
                            ids = twitter.getFriendsIDs(targetedUser, cursor);
                        }

                    } catch (TwitterException te) {

                        // do not throw if user has protected tweets, 
                        // or if they deleted their account
                        if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED
                                || te.getStatusCode() == HttpResponseCode.NOT_FOUND) {

                            System.out.println(targetedUser + " is protected or account is deleted");
                        } else {
                            System.out.println("Friends Get Exception: " + te.getMessage());
                        }

                        // If rate limit reached then switch Auth user
                        RemainingCallsCounter++;
                        if (RemainingCallsCounter >= RemainingCalls) {

                            // load auth user
                            tf = AppOAuths.loadOAuthUser(endpoint);
                            twitter = tf.getInstance();

                            System.out.println(
                                    "New User Loaded OAuth" + " Screen_name: " + AppOAuths.screen_name);

                            RemainingCalls = AppOAuths.RemainingCalls;
                            RemainingCallsCounter = 0;

                            System.out.println("New Remianing Calls: " + RemainingCalls);
                        }

                        // update cursor in "followings_parent"
                        String fieldValues = "`nextcursor` = 2";
                        String where = "id = " + following_parent_id;
                        DB.Update("`followings_parent`", fieldValues, where);

                        // If error then switch to next user
                        continue OUTERMOST;
                    }

                    if (ids.getIDs().length > 0) {

                        idsLoopCounter++;
                        totalIDs += ids.getIDs().length;
                        System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length);

                        JSONObject responseDetailsJson = new JSONObject();
                        JSONArray jsonArray = new JSONArray();
                        for (long id : ids.getIDs()) {
                            jsonArray.put(id);
                        }
                        Object idsJSON = responseDetailsJson.put("ids", jsonArray);

                        writer.println(idsJSON);
                    }

                    // If rate limit reached then switch Auth user.
                    RemainingCallsCounter++;
                    if (RemainingCallsCounter >= RemainingCalls) {

                        // load auth user
                        tf = AppOAuths.loadOAuthUser(endpoint);
                        twitter = tf.getInstance();

                        System.out.println("New User Loaded OAuth " + "Screen_name: " + AppOAuths.screen_name);

                        RemainingCalls = AppOAuths.RemainingCalls;
                        RemainingCallsCounter = 0;

                        System.out.println("New Remianing Calls: " + RemainingCalls);
                    }

                    if (IDS_TO_FETCH_INT != -1) {
                        if (idsLoopCounter == IDS_TO_FETCH) {
                            break;
                        }
                    }

                } while ((cursor = ids.getNextCursor()) != 0);
                writer.close();
                System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs);
                System.out.println();

                // update cursor in "followings_parent"
                String fieldValues = "`nextcursor` = " + cursor;
                String where = "id = " + following_parent_id;
                DB.Update("`followings_parent`", fieldValues, where);

            } // loop through every result found in db
        } else {

            // Second Argument Sets, so we are here.
            System.out.println("screen_name / user_id_str " + "passed by argument");

            int idsLoopCounter = 0;
            int totalIDs = 0;

            // put idsJSON in a file
            PrintWriter writer = new PrintWriter(
                    OutputDirPath + "/" + targetedUser + "_ids_" + helpers.getUnixTimeStamp(), "UTF-8");

            // call different functions for screen_name and id_str
            Boolean chckedNumaric = helpers.isNumeric(targetedUser);
            long cursor = -1;

            do {
                ids = null;
                try {

                    if (chckedNumaric) {

                        long LongValueTargetedUser = Long.valueOf(targetedUser).longValue();

                        ids = twitter.getFriendsIDs(LongValueTargetedUser, cursor);
                    } else {
                        ids = twitter.getFriendsIDs(targetedUser, cursor);
                    }

                } catch (TwitterException te) {

                    // do not throw if user has protected tweets, 
                    // or if they deleted their account
                    if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED
                            || te.getStatusCode() == HttpResponseCode.NOT_FOUND) {

                        System.out.println(targetedUser + " is protected or account is deleted");
                    } else {
                        System.out.println("Friends Get Exception: " + te.getMessage());
                    }
                    System.exit(-1);
                }

                if (ids.getIDs().length > 0) {

                    idsLoopCounter++;
                    totalIDs += ids.getIDs().length;
                    System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length);

                    JSONObject responseDetailsJson = new JSONObject();
                    JSONArray jsonArray = new JSONArray();
                    for (long id : ids.getIDs()) {
                        jsonArray.put(id);
                    }
                    Object idsJSON = responseDetailsJson.put("ids", jsonArray);

                    writer.println(idsJSON);

                }

                // If rate limit reach then switch Auth user
                RemainingCallsCounter++;
                if (RemainingCallsCounter >= RemainingCalls) {

                    // load auth user
                    tf = AppOAuths.loadOAuthUser(endpoint);
                    twitter = tf.getInstance();

                    System.out.println("New User Loaded OAuth Screen_name: " + AppOAuths.screen_name);

                    RemainingCalls = AppOAuths.RemainingCalls;
                    RemainingCallsCounter = 0;

                    System.out.println("New Remianing Calls: " + RemainingCalls);
                }

                if (IDS_TO_FETCH_INT != -1) {
                    if (idsLoopCounter == IDS_TO_FETCH) {
                        break;
                    }
                }

            } while ((cursor = ids.getNextCursor()) != 0);
            writer.close();
            System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs);
            System.out.println();

        }

    } catch (TwitterException te) {
        // te.printStackTrace();
        System.err.println("Failed to get friends' ids: " + te.getMessage());
        System.exit(-1);
    }
    System.out.println("!!!! DONE !!!!");
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.PdfaConvert.java

public static void main(String[] args) throws IOException {
    if (logger == null) {
        System.out.println("About to initialize Log4j");
        logger = LogManager.getLogger();
        System.out.println("Finished initializing Log4j");
    }/* w  w w  . ja  v  a2s .  c o  m*/

    logger.debug("Entering main()");

    // WIP: the following command line code was pulled from FITS
    Options options = new Options();
    Option inputFileOption = new Option(PARAM_I, true, "input file");
    options.addOption(inputFileOption);
    options.addOption(PARAM_V, false, "print version information");
    options.addOption(PARAM_H, false, "help information");
    options.addOption(PARAM_O, true, "output sub-directory");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args, true);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    // print version info
    if (cmd.hasOption(PARAM_V)) {
        if (StringUtils.isEmpty(applicationVersion)) {
            applicationVersion = "<not set>";
            System.exit(1);
        }
        System.out.println("Version: " + applicationVersion);
        System.exit(0);
    }

    // print help info
    if (cmd.hasOption(PARAM_H)) {
        displayHelp();
        System.exit(0);
    }

    // input parameter
    if (cmd.hasOption(PARAM_I)) {
        String input = cmd.getOptionValue(PARAM_I);
        boolean hasValue = cmd.hasOption(PARAM_I);
        logger.debug("Has option {} value: [{}]", PARAM_I, hasValue);
        String paramVal = cmd.getOptionValue(PARAM_I);
        logger.debug("value of option: [{}] ****", paramVal);

        File inputFile = new File(input);
        if (!inputFile.exists()) {
            logger.warn("{} does not exist or is not readable.", input);
            System.exit(1);
        }

        String subDir = cmd.getOptionValue(PARAM_O);
        PdfaConvert convert;
        if (!StringUtils.isEmpty(subDir)) {
            convert = new PdfaConvert(subDir);
        } else {
            convert = new PdfaConvert();
        }
        if (inputFile.isDirectory()) {
            if (inputFile.listFiles() == null || inputFile.listFiles().length < 1) {
                logger.warn("Input directory is empty, nothing to process.");
                System.exit(1);
            } else {
                logger.debug("Have directory: [{}] with file count: {}", inputFile.getAbsolutePath(),
                        inputFile.listFiles().length);
                DirectoryStream<Path> dirStream = null;
                dirStream = Files.newDirectoryStream(inputFile.toPath());
                for (Path filePath : dirStream) {
                    logger.debug("Have file name: {}", filePath.toString());
                    // Note: only handling files, not recursively going into sub-directories
                    if (filePath.toFile().isFile()) {
                        // Catch possible exception for each file so can handle other files in directory.
                        try {
                            convert.examine(filePath.toFile());
                        } catch (Exception e) {
                            logger.error("Problem processing file: {} -- Error message: {}",
                                    filePath.getFileName(), e.getMessage());
                        }
                    } else {
                        logger.warn("Not a file so not processing: {}", filePath.toString()); // could be a directory but not recursing
                    }
                }
                dirStream.close();
            }
        } else {
            logger.debug("About to process file: {}", inputFile.getPath());
            try {
                convert.examine(inputFile);
            } catch (Exception e) {
                logger.error("Problem processing file: {} -- Error message: {}", inputFile.getName(),
                        e.getMessage());
                logger.debug("Problem processing file: {} -- Error message: {}", inputFile.getName(),
                        e.getMessage(), e);
            }
        }
    } else {
        System.err.println("Missing required option: " + PARAM_I);
        displayHelp();
        System.exit(-1);
    }

    System.exit(0);
}

From source file:net.sf.jsignpdf.Signer.java

/**
 * Main./*from   ww w  .  j  a v a2  s.  c o  m*/
 * 
 * @param args
 */
public static void main(String[] args) {
    SignerOptionsFromCmdLine tmpOpts = null;

    if (args != null && args.length > 0) {
        tmpOpts = new SignerOptionsFromCmdLine();
        parseCommandLine(args, tmpOpts);
    }

    try {
        SSLInitializer.init();
    } catch (Exception e) {
        LOGGER.warn("Unable to re-configure SSL layer", e);
    }

    pkcs11ProviderName = PKCS11Utils
            .registerProvider(ConfigProvider.getInstance().getProperty("pkcs11config.path"));

    traceInfo();

    if (tmpOpts != null) {
        if (tmpOpts.isPrintVersion()) {
            System.out.println("JSignPdf version " + VERSION);
        }
        if (tmpOpts.isPrintHelp()) {
            printHelp();
        }
        if (tmpOpts.isListKeyStores()) {
            LOGGER.info(RES.get("console.keystores"));
            for (String tmpKsType : KeyStoreUtils.getKeyStores()) {
                System.out.println(tmpKsType);
            }
        }
        if (tmpOpts.isListKeys()) {
            final String[] tmpKeyAliases = KeyStoreUtils.getKeyAliases(tmpOpts);
            LOGGER.info(RES.get("console.keys"));
            // list certificate aliases in the keystore
            for (String tmpCert : tmpKeyAliases) {
                System.out.println(tmpCert);
            }
        }
        if (ArrayUtils.isNotEmpty(tmpOpts.getFiles())
                || (!StringUtils.isEmpty(tmpOpts.getInFile()) && !StringUtils.isEmpty(tmpOpts.getOutFile()))) {
            signFiles(tmpOpts);
        } else {
            final boolean tmpCommand = tmpOpts.isPrintVersion() || tmpOpts.isPrintHelp()
                    || tmpOpts.isListKeyStores() || tmpOpts.isListKeys();
            if (!tmpCommand) {
                // no valid command provided - print help and exit
                printHelp();
                exit(EXIT_CODE_NO_COMMAND);
            }
        }
        exit(0);
    } else {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            System.err.println("Can't set Look&Feel.");
        }
        SignPdfForm tmpForm = new SignPdfForm(WindowConstants.EXIT_ON_CLOSE);
        tmpForm.pack();
        GuiUtils.center(tmpForm);
        tmpForm.setVisible(true);
    }
}