Example usage for java.lang SecurityException getMessage

List of usage examples for java.lang SecurityException getMessage

Introduction

In this page you can find the example usage for java.lang SecurityException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:security.SecurityExample.java

public static void main(String[] args) {
    SecurityManager manager = new SecurityManager();
    SecureBean bean = getSecureBean();/*  w ww .ja va2s. c om*/
    manager.login("clarence", "pwd");
    bean.writeSecureMessage();
    manager.logout();
    try {
        manager.login("bilbo", "mylittletreasure");
        bean.writeSecureMessage();
    } catch (SecurityException ex) {
        System.out.println("Exception caught: " + ex.getMessage());
    } finally {
        manager.logout();
    }
    try {
        bean.writeSecureMessage();
    } catch (SecurityException ex) {
        System.out.println("Exception caught: " + ex.getMessage());
    }
}

From source file:net.jradius.server.Main.java

public static void main(String[] args) {
    if (args.length != 1) {
        showUsage();//from   www  . jav a  2  s. c om
        System.exit(1);
    }

    /**
     * CADBiS daemon run
     * --->
     */
    if (JRadiusConfigurator.getInstance().getProperty("cadbis_daemon").equals("enabled"))
        CADBiS.getInstance().start();
    /**
     * <--- eof CADBiS
     */

    String configFilePath = args[0];

    try {
        File file = new File(configFilePath);
        Configuration.initialize(file);
        JRadiusServer server = new JRadiusServer();
        server.start();
    } catch (FileNotFoundException e) {
        System.err.println("Error: The configuration file '" + configFilePath + "' does not exist.");
    } catch (ConfigurationException e1) {
        System.err.println("Error: The configuration file could not be read,"
                + " because the file contains an error: " + e1.getMessage());
        showStackTrace(e1);
    } catch (SecurityException e2) {
        System.err.println("Error: The configuration file could not be read,"
                + " because a security error occurred: " + e2.getMessage());
        showStackTrace(e2);
    } catch (IllegalArgumentException e3) {
        System.err.println("Error: The configuration file could not be read,"
                + " because an illegal argument error occurred: " + e3.getMessage());
        showStackTrace(e3);
    } catch (ClassNotFoundException e4) {
        System.err.println("Error: The configuration file could not be read,"
                + " because a class specified in the configuration file could not be found: "
                + e4.getMessage());
        showStackTrace(e4);
    } catch (NoSuchMethodException e5) {
        System.err.println("Error: The configuration file could not be read,"
                + " because a method does not exist in a class specified in the configuration file: "
                + e5.getMessage());
        showStackTrace(e5);
    } catch (InstantiationException e6) {
        System.err.println("Error: The configuration file could not be read,"
                + " because an object specified in the configuration file could not be instantiated: "
                + e6.getMessage());
        showStackTrace(e6);
    } catch (IllegalAccessException e7) {
        System.err.println("Error: The configuration file could not be read,"
                + " because an illegal access error occurred: " + e7.getMessage());
        showStackTrace(e7);
    } catch (InvocationTargetException e8) {
        System.err.println("Error: The configuration file could not be read,"
                + " because an invocation target exception was thrown: " + e8.getMessage());
        showStackTrace(e8);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return;
}

From source file:com.cws.esolutions.security.main.UserManagementUtility.java

public static final void main(final String[] args) {
    final String methodName = UserManagementUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {//from w  w w  .j av  a 2s .  co m
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", (Object) args);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(UserManagementUtility.CNAME, options, true);

        return;
    }

    try {
        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        if ((commandLine.hasOption("configFile"))
                && (!(StringUtils.isBlank(commandLine.getOptionValue("configFile"))))) {
            SecurityServiceInitializer.initializeService(commandLine.getOptionValue("configFile"),
                    UserManagementUtility.LOG_CONFIG, true);
        } else {
            SecurityServiceInitializer.initializeService(UserManagementUtility.SEC_CONFIG,
                    UserManagementUtility.LOG_CONFIG, true);
        }

        AccountControlResponse response = null;

        final UserAccount userAccount = new UserAccount();
        final RequestHostInfo reqInfo = new RequestHostInfo();
        final SecurityConfigurationData secConfigData = UserManagementUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();

        try {
            reqInfo.setHostAddress(InetAddress.getLocalHost().getHostAddress());
            reqInfo.setHostName(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException uhx) {
            reqInfo.setHostAddress("127.0.0.1");
            reqInfo.setHostName("localhost");
        }

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RequestHostInfo reqInfo: {}", reqInfo);
        }

        AccountControlRequest request = new AccountControlRequest();
        request.setApplicationId(secConfig.getApplicationId());
        request.setApplicationName(secConfig.getApplicationName());
        request.setHostInfo(reqInfo);
        request.setRequestor(secConfig.getSvcAccount());

        if (DEBUG) {
            DEBUGGER.debug("AccountControlRequest request: {}", request);
        }

        if (commandLine.hasOption("search")) {
            if (StringUtils.isEmpty(commandLine.getOptionValue("search"))) {
                throw new ParseException("No entry option was provided. Cannot continue.");
            }

            userAccount.setEmailAddr(commandLine.getOptionValue("search"));

            if (DEBUG) {
                DEBUGGER.debug("UserAccount userAccount: {}", userAccount);
            }

            request.setUserAccount(userAccount);

            if (DEBUG) {
                DEBUGGER.debug("AccountControlRequest: {}", request);
            }

            response = processor.searchAccounts(request);
        } else if (commandLine.hasOption("load")) {
            if (StringUtils.isEmpty(commandLine.getOptionValue("load"))) {
                throw new ParseException("No entry option was provided. Cannot continue.");
            }

            userAccount.setGuid(commandLine.getOptionValue("load"));

            request.setUserAccount(userAccount);

            if (DEBUG) {
                DEBUGGER.debug("AccountControlRequest: {}", request);
            }

            response = processor.loadUserAccount(request);
        }

        if (DEBUG) {
            DEBUGGER.debug("AccountControlResponse response: {}", response);
        }

        if ((response != null) && (response.getRequestStatus() == SecurityRequestStatus.SUCCESS)) {
            UserAccount account = response.getUserAccount();

            if (DEBUG) {
                DEBUGGER.debug("UserAccount: {}", account);
            }

            System.out.println(account);
        }
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);

        System.err.println("An error occurred during processing: " + ssx.getMessage());
    }
}

From source file:com.cws.esolutions.core.main.NetworkUtility.java

public static final void main(final String[] args) {
    final String methodName = NetworkUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {//from  w  w w  .j a va  2 s  .c  o m
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", (Object) args);
    }

    if (args.length == 0) {
        new HelpFormatter().printHelp(NetworkUtility.CNAME, options, true);

        return;
    }

    try {
        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
        }

        String coreConfiguration = (StringUtils.isBlank(System.getProperty("coreConfigFile")))
                ? NetworkUtility.CORE_SVC_CONFIG
                : System.getProperty("coreConfigFile");
        String securityConfiguration = (StringUtils.isBlank(System.getProperty("secConfigFile")))
                ? NetworkUtility.CORE_LOG_CONFIG
                : System.getProperty("secConfigFile");
        String coreLogging = (StringUtils.isBlank(System.getProperty("coreLogConfig")))
                ? NetworkUtility.SEC_SVC_CONFIG
                : System.getProperty("coreLogConfig");
        String securityLogging = (StringUtils.isBlank(System.getProperty("secLogConfig")))
                ? NetworkUtility.SEC_LOG_CONFIG
                : System.getProperty("secLogConfig");

        if (DEBUG) {
            DEBUGGER.debug("String coreConfiguration: {}", coreConfiguration);
            DEBUGGER.debug("String securityConfiguration: {}", securityConfiguration);
            DEBUGGER.debug("String coreLogging: {}", coreLogging);
            DEBUGGER.debug("String securityLogging: {}", securityLogging);
        }

        SecurityServiceInitializer.initializeService(securityConfiguration, securityLogging, false);
        CoreServiceInitializer.initializeService(coreConfiguration, coreLogging, false, true);

        final CoreConfigurationData coreConfigData = NetworkUtility.appBean.getConfigData();
        final SecurityConfigurationData secConfigData = NetworkUtility.secBean.getConfigData();

        if (DEBUG) {
            DEBUGGER.debug("CoreConfigurationData coreConfigData: {}", coreConfigData);
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
        }

        if (commandLine.hasOption("ssh")) {
            if (!(commandLine.hasOption("hostname"))
                    || (!(StringUtils.isBlank(commandLine.getOptionValue("hostname"))))) {
                throw new CoreServiceException("No target host was provided. Unable to process request.");
            } else if (!(commandLine.hasOption("username"))
                    && (StringUtils.isBlank(commandLine.getOptionValue("username")))) {
                throw new CoreServiceException("No username was provided. Using default.");
            }

            // NetworkUtils.executeSshConnection(commandLine.getOptionValue("hostname"), commandList);
        } else if (commandLine.hasOption("http")) {
            if (!(commandLine.hasOption("hostname"))
                    || (!(StringUtils.isBlank(commandLine.getOptionValue("hostname"))))) {
                throw new CoreServiceException("No target host was provided. Unable to process request.");
            } else if (!(commandLine.hasOption("method"))
                    && (StringUtils.isBlank(commandLine.getOptionValue("method")))) {
                throw new CoreServiceException("No HTTP method was provided. Unable to process request.");
            }

            NetworkUtils.executeHttpConnection(new URL(commandLine.getOptionValue("hostname")),
                    commandLine.getOptionValue("method"));
        } else if (commandLine.hasOption("copyFiles")) {
            if (!(commandLine.hasOption("hostname"))
                    || (StringUtils.isBlank(commandLine.getOptionValue("hostname")))) {
                throw new CoreServiceException("No target host was provided. Unable to process request.");
            } else if (!(commandLine.hasOption("sourceFile"))
                    && (StringUtils.isBlank(commandLine.getOptionValue("sourceFile")))) {
                throw new CoreServiceException("No source file(s) were provided. Unable to process request.");
            } else if (!(commandLine.hasOption("targetFile"))
                    && (StringUtils.isBlank(commandLine.getOptionValue("targetFile")))) {
                throw new CoreServiceException("No target file(s) were provided. Unable to process request.");
            }

            List<String> filesToTransfer = new ArrayList<String>(
                    Arrays.asList(commandLine.getOptionValues("sourceFile")));
            List<String> filesToCreate = new ArrayList<String>(
                    Arrays.asList(commandLine.getOptionValues("targetFile")));

            if (DEBUG) {
                DEBUGGER.debug("List<String> filesToTransfer: {}", filesToTransfer);
                DEBUGGER.debug("List<String> filesToCreate: {}", filesToCreate);
            }

            if (commandLine.hasOption("withSSH")) {
                for (String fileName : filesToTransfer) {
                    if (DEBUG) {
                        DEBUGGER.debug("String fileName: {}", fileName);
                    }

                    NetworkUtils.executeSftpTransfer(fileName,
                            filesToCreate.get(filesToTransfer.indexOf(fileName)),
                            commandLine.getOptionValue("hostname"), FileUtils.getFile(fileName).exists());
                }
            }

            else if (commandLine.hasOption("withFTP")) {
                if ((commandLine.hasOption("withSSL"))
                        && (Boolean.valueOf(commandLine.getOptionValue("withSSL")))) {
                    // ftp/s
                }

                // NetworkUtils.executeFtpConnection(sourceFile, targetFile, targetHost, isUpload);
            }
        }
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);

        System.err.println("An error occurred during processing: " + ssx.getMessage());
    } catch (CoreServiceException csx) {
        ERROR_RECORDER.error(csx.getMessage(), csx);

        System.err.println("An error occurred during processing: " + csx.getMessage());
    } catch (MalformedURLException mux) {
        ERROR_RECORDER.error(mux.getMessage(), mux);

        System.err.println("An error occurred during processing: " + mux.getMessage());
    }
}

From source file:timeline.CmdSearchTerm.java

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

    // Check how many arguments were passed in
    if ((args == null) || (args.length != 6)) {

        System.err.println("Please provide command as following.");
        System.err.println("java -cp twitter4j-multi-oauth-0.5.jar "
                + "timeline.CmdSearchTerm consumer_key consumer_secret" + " user_token user_secret output_path "
                + "term ");
        System.exit(-1);//from   w ww .j a  va2s.com
    }

    AppOAuth AppOAuths = new AppOAuth();
    String endpoint = "/search/tweets";

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

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

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

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

    try {

        TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint, consumer_key, consumer_secret, user_token,
                user_secret);
        Twitter twitter = tf.getInstance();

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

        // screen_name / user_id provided by arguments
        System.out.println("Trying to create output directory");
        String filesPath = OutputDirPath + "/";
        File theDir = new File(filesPath);

        // If the directory does not exist, create it
        if (!theDir.exists()) {

            try {
                theDir.mkdirs();

            } catch (SecurityException se) {

                System.err.println("Could not create output " + "directory: " + OutputDirPath);
                System.err.println(se.getMessage());
                System.exit(-1);
            }
        }

        String fileName = filesPath + term.replace(" ", "");
        PrintWriter writer = new PrintWriter(fileName, "UTF-8");

        Query query = new Query(term);
        QueryResult result;

        List<Status> statuses = new ArrayList<>();
        int totalTweets = 0;
        int numberOfTweetsToGet = 5000;
        long lastID = Long.MAX_VALUE;

        while (totalTweets < numberOfTweetsToGet) {
            if (numberOfTweetsToGet - totalTweets > 100) {
                query.setCount(100);
            } else {
                query.setCount(numberOfTweetsToGet - totalTweets);
            }
            try {
                result = twitter.search(query);
                statuses.addAll(result.getTweets());

                if (statuses.size() > 0) {
                    for (Status status : statuses) {
                        String rawJSON = TwitterObjectFactory.getRawJSON(status);
                        writer.println(rawJSON);

                        totalTweets += 1;

                        if (status.getId() < lastID) {
                            lastID = status.getId();
                        }
                    }
                } else {
                    break;
                }
                System.out.println("totalTweets: " + totalTweets);
                statuses.clear();

            } catch (TwitterException e) {
                // e.printStackTrace();

                System.out.println("Tweets Get Exception: " + e.getMessage());

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

                    System.out.println("No more remianing calls");
                }

                if (totalTweets < 1) {
                    writer.close();
                    // Remove file if tweets not found
                    File fileToDelete = new File(fileName);
                    fileToDelete.delete();
                    break;
                }
            }
            query.setMaxId(lastID - 1);

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

                System.out.println("No more remianing calls");
                break;
            }
        }

        if (totalTweets > 0) {
            System.out.println("Total dumped tweets of " + term + " are: " + totalTweets);
        } else {

            // Remove file if tweets not found
            File fileToDelete = new File(fileName);
            fileToDelete.delete();
        }
        writer.close();
    } catch (TwitterException te) {
        // te.printStackTrace();
        System.out.println("Failed to get term results because: " + te.getMessage());
        System.exit(-1);
    }
    System.out.println("!!!! DONE !!!!");
}

From source file:timeline.CmdUserTimeline.java

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

    // Check how many arguments were passed in
    if ((args == null) || (args.length != 7)) {

        System.err.println("Please provide command as following.");
        System.err.println("java -cp twitter4j-multi-oauth-0.3.jar "
                + "timeline.CmdUserTimeline consumer_key consumer_secret"
                + " user_token user_secret output_path " + "screen_name_or_userid "
                + "number_of_tweets_to_get_max_is_3200");
        System.exit(-1);//from  w  w w  . j  av  a 2 s .c  o m
    }

    AppOAuth AppOAuths = new AppOAuth();
    Misc helpers = new Misc();
    String endpoint = "/statuses/user_timeline";

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

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

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

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

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

    try {

        TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint, consumer_key, consumer_secret, user_token,
                user_secret);
        Twitter twitter = tf.getInstance();

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

        // screen_name / user_id provided by arguments
        System.out.println("Trying to create output directory");
        String filesPath = OutputDirPath + "/";
        File theDir = new File(filesPath);

        // If the directory does not exist, create it
        if (!theDir.exists()) {

            try {
                theDir.mkdirs();

            } catch (SecurityException se) {

                System.err.println("Could not create output " + "directory: " + OutputDirPath);
                System.err.println(se.getMessage());
                System.exit(-1);
            }
        }

        String fileName = filesPath + targetedUser;
        PrintWriter writer = new PrintWriter(fileName, "UTF-8");

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

        List<Status> statuses = new ArrayList<>();
        int size = statuses.size();
        int pageno = 1;
        int totalTweets = 0;
        boolean tweetCounterReached = false;
        System.out.println("NUMBER_OF_TWEETS to get:" + NUMBER_OF_TWEETS);
        while (true) {

            try {

                Paging page = new Paging(pageno++, 200);

                if (chckedNumaric) {

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

                    statuses.addAll(twitter.getUserTimeline(LongValueTargetedUser, page));

                    if (statuses.size() > 0) {
                        for (Status status : statuses) {
                            String rawJSON = TwitterObjectFactory.getRawJSON(status);
                            writer.println(rawJSON);

                            totalTweets += 1;
                            if (totalTweets >= NUMBER_OF_TWEETS) {
                                tweetCounterReached = true;
                                break;
                            }
                        }
                        if (tweetCounterReached) {
                            break;
                        }
                    }
                } else {

                    statuses.addAll(twitter.getUserTimeline(targetedUser, page));

                    if (statuses.size() > 0) {
                        for (Status status : statuses) {
                            String rawJSON = TwitterObjectFactory.getRawJSON(status);
                            writer.println(rawJSON);

                            totalTweets += 1;
                            if (totalTweets >= NUMBER_OF_TWEETS) {
                                tweetCounterReached = true;
                                break;
                            }
                        }
                        if (tweetCounterReached) {
                            break;
                        }
                    }
                }

                // If user's total tweet are less than 195 then no next call
                if (size == 0) {
                    if (totalTweets < 195) {
                        break;
                    }
                }

                // If user's all tweets parsed then exit
                if (totalTweets == size) {
                    break;
                }

                size = totalTweets;

                statuses.clear();

            } catch (TwitterException e) {

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

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

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

                    System.out.println("No more remianing calls");
                }

                if (totalTweets < 1) {
                    writer.close();
                    // Remove file if tweets not found
                    File fileToDelete = new File(fileName);
                    fileToDelete.delete();
                }
                break;
            }

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

                System.out.println("No more remianing calls");
                break;
            }

        } // while get tweets
        writer.close();

        if (totalTweets > 0) {
            System.out.println("Total dumped tweets of " + targetedUser + " are: " + totalTweets);
        } else {

            // Remove file if tweets not found
            File fileToDelete = new File(fileName);
            fileToDelete.delete();
        }

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

From source file:com.cws.esolutions.security.main.PasswordUtility.java

public static void main(final String[] args) {
    final String methodName = PasswordUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {/*from  w w  w.  j av a  2  s. c o m*/
        DEBUGGER.debug("Value: {}", methodName);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(PasswordUtility.CNAME, options, true);

        System.exit(1);
    }

    BufferedReader bReader = null;
    BufferedWriter bWriter = null;

    try {
        // load service config first !!
        SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG,
                false);

        if (DEBUG) {
            DEBUGGER.debug("Options options: {}", options);

            for (String arg : args) {
                DEBUGGER.debug("Value: {}", arg);
            }
        }

        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();
        final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo();
        final SystemConfig systemConfig = secConfigData.getSystemConfig();

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig);
            DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig);
        }

        if (commandLine.hasOption("encrypt")) {
            if ((StringUtils.isBlank(repoConfig.getPasswordFile()))
                    || (StringUtils.isBlank(repoConfig.getSaltFile()))) {
                System.err.println("The password/salt files are not configured. Entries will not be stored!");
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            final String entryName = commandLine.getOptionValue("entry");
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");
            final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
                DEBUGGER.debug("String password: {}", password);
                DEBUGGER.debug("String salt: {}", salt);
            }

            final String encodedSalt = PasswordUtils.base64Encode(salt);
            final String encodedUserName = PasswordUtils.base64Encode(username);
            final String encryptedPassword = PasswordUtils.encryptText(password, salt,
                    secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                    systemConfig.getEncoding());
            final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword);

            if (DEBUG) {
                DEBUGGER.debug("String encodedSalt: {}", encodedSalt);
                DEBUGGER.debug("String encodedUserName: {}", encodedUserName);
                DEBUGGER.debug("String encodedPassword: {}", encodedPassword);
            }

            if (commandLine.hasOption("store")) {
                try {
                    new File(passwordFile.getParent()).mkdirs();
                    new File(saltFile.getParent()).mkdirs();

                    boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile();

                    if (DEBUG) {
                        DEBUGGER.debug("saltFileExists: {}", saltFileExists);
                    }

                    // write the salt out first
                    if (!(saltFileExists)) {
                        throw new IOException("Unable to create salt file");
                    }

                    boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile();

                    if (!(passwordFileExists)) {
                        throw new IOException("Unable to create password file");
                    }

                    if (commandLine.hasOption("replace")) {
                        File[] files = new File[] { saltFile, passwordFile };

                        if (DEBUG) {
                            DEBUGGER.debug("File[] files: {}", (Object) files);
                        }

                        for (File file : files) {
                            if (DEBUG) {
                                DEBUGGER.debug("File: {}", file);
                            }

                            String currentLine = null;
                            File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile");

                            if (DEBUG) {
                                DEBUGGER.debug("File tmpFile: {}", tmpFile);
                            }

                            bReader = new BufferedReader(new FileReader(file));
                            bWriter = new BufferedWriter(new FileWriter(tmpFile));

                            while ((currentLine = bReader.readLine()) != null) {
                                if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) {
                                    bWriter.write(currentLine + System.getProperty("line.separator"));
                                    bWriter.flush();
                                }
                            }

                            bWriter.close();

                            FileUtils.deleteQuietly(file);
                            FileUtils.copyFile(tmpFile, file);
                            FileUtils.deleteQuietly(tmpFile);
                        }
                    }

                    FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt
                            + System.getProperty("line.separator"), true);
                    FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + ","
                            + encodedPassword + System.getProperty("line.separator"), true);
                } catch (IOException iox) {
                    ERROR_RECORDER.error(iox.getMessage(), iox);
                }
            }

            System.out.println("Entry Name " + entryName + " stored.");
        }

        if (commandLine.hasOption("decrypt")) {
            String saltEntryName = null;
            String saltEntryValue = null;
            String decryptedPassword = null;
            String passwordEntryName = null;

            if ((StringUtils.isEmpty(commandLine.getOptionValue("entry"))
                    && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) {
                throw new ParseException("No entry or username was provided to decrypt.");
            }

            if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) {
                throw new ParseException("no entry provided to decrypt");
            }

            String entryName = commandLine.getOptionValue("entry");
            String username = commandLine.getOptionValue("username");

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) {
                throw new IOException(
                        "Unable to read configured password/salt file. Please check configuration and/or permissions.");
            }

            for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) {
                saltEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String saltEntryName: {}", saltEntryName);
                }

                if (StringUtils.equals(saltEntryName, entryName)) {
                    saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    break;
                }
            }

            if (StringUtils.isEmpty(saltEntryValue)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) {
                passwordEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName);
                }

                if (StringUtils.equals(passwordEntryName, saltEntryName)) {
                    String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue,
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            systemConfig.getEncoding());

                    break;
                }
            }

            if (StringUtils.isEmpty(decryptedPassword)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            System.out.println(decryptedPassword);
        } else if (commandLine.hasOption("encode")) {
            System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0)));
        } else if (commandLine.hasOption("decode")) {
            System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0)));
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        System.err.println("An error occurred during processing: " + iox.getMessage());
        System.exit(1);
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
        System.exit(1);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
        System.exit(1);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
        System.exit(1);
    } finally {
        try {
            if (bReader != null) {
                bReader.close();
            }

            if (bWriter != null) {
                bReader.close();
            }
        } catch (IOException iox) {
        }
    }

    System.exit(0);
}

From source file:timeline.DBThreaderParser.java

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

    // Check how many arguments were passed in
    if ((args == null) || (args.length < 5)) {
        System.err.println("5 Parameters are required to launch a Job.");
        System.err.println("First: String 'OUTPUT_PATH'");
        System.err.println("Second: (int) Total Number Of Jobs");
        System.err.println("Third: (int) This Job Number");
        System.err.println("Fourth: (int) Seconds to pause between next launch");
        System.err.println("Fifth: (int) Number of Tweets to get. Max 3200");
        System.err.println("Example: fileName.class /output/path 10 1 2 3200");
        System.exit(-1);/*from   ww w.ja va  2  s  . co m*/
    }

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

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

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

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

    MysqlDB DB = new MysqlDB();
    AppOAuth AppOAuths = new AppOAuth();
    Misc helpers = new Misc();
    String endpoint = "/statuses/user_timeline";

    try {

        String totalRowsQuery = "SELECT count( * ) as wLoad FROM `twitter_users`"
                + " WHERE `tweets_dumped_all` = 0";
        ResultSet totalRowsResults = DB.selectQ(totalRowsQuery);

        int TotalWorkLoad = 0;
        while (totalRowsResults.next()) {
            TotalWorkLoad = totalRowsResults.getInt("wLoad");
        }

        if (TotalWorkLoad < 1) {
            System.err.println("No User in database to get Tweets");
            System.exit(-1);
        }

        // Free memmory
        totalRowsResults = null;

        if (TOTAL_JOBS > TotalWorkLoad) {
            System.err.println("Number of jobs are more than total work"
                    + " load Please reduce Number of jobs to launch.");
            System.exit(-1);
        }

        float TotalWorkLoadf = TotalWorkLoad;
        float TOTAL_JOBSf = TOTAL_JOBS;
        float res = (TotalWorkLoadf / TOTAL_JOBSf);

        int chunkSize = (int) Math.ceil(res);
        int offSet = JOB_NO * chunkSize;

        String selectQuery = "SELECT `id`,`targeteduser` FROM " + "`twitter_users` WHERE "
                + "`tweets_dumped_all` = 0 LIMIT " + offSet + "," + chunkSize;

        ResultSet results = DB.selectQ(selectQuery);

        int numRows = DB.numRows(results);
        if (numRows < 1) {
            System.err.println(
                    "No User in database to get Tweets" + " with offset " + offSet + " and limit " + chunkSize);
            System.exit(-1);
        }

        /**
         * wait before launching actual job
         */
        int secondsToPause = 0;
        try {
            secondsToPause = Integer.parseInt(args[3]);
        } catch (NumberFormatException e) {
            System.err.println("Argument" + args[3] + " must be an integer.");
            System.exit(-1);
        }

        secondsToPause = (TOTAL_JOBS * secondsToPause) - (JOB_NO * secondsToPause);
        System.out.println("secondsToPause: " + secondsToPause);
        helpers.pause(secondsToPause);
        /**
         * wait before launching actual job
         */

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

        int RemainingCalls = AppOAuths.RemainingCalls - 2;
        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);

        System.out.println("User's Tweets");

        System.out.println("Trying to create output directory");
        String filesPath = OutputDirPath + "/";
        File theDir = new File(filesPath);

        // If the directory does not exist, create it
        if (!theDir.exists()) {
            try {
                theDir.mkdirs();

            } catch (SecurityException se) {

                System.err.println("Could not create output " + "directory: " + OutputDirPath);
                System.err.println(se.getMessage());
                System.exit(-1);
            }
        }

        System.out.flush();

        OUTERMOST: while (results.next()) {

            int targetedUserID = results.getInt("id");
            String targetedUser = results.getString("targeteduser");
            System.out.println("Targeted User: " + targetedUser);

            // Create User file to push tweets in it
            String fileName = filesPath + "/" + targetedUser;
            PrintWriter writer = new PrintWriter(fileName, "UTF-8");

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

            List<Status> statuses = new ArrayList<>();
            int size = statuses.size();
            int pageno = 1;
            int totalTweets = 0;
            boolean tweetCounterReached = false;
            System.out.println("NUMBER_OF_TWEETS to get:" + NUMBER_OF_TWEETS);
            while (true) {
                try {

                    Paging page = new Paging(pageno++, 200);

                    if (chckedNumaric) {

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

                        statuses.addAll(twitter.getUserTimeline(LongValueTargetedUser, page));

                        if (statuses.size() > 0) {
                            for (Status status : statuses) {
                                String rawJSON = TwitterObjectFactory.getRawJSON(status);
                                writer.println(rawJSON);

                                totalTweets += 1;
                                if (totalTweets >= NUMBER_OF_TWEETS) {
                                    tweetCounterReached = true;
                                    break;
                                }
                            }
                            if (tweetCounterReached) {
                                break;
                            }
                        }
                    } else {

                        statuses.addAll(twitter.getUserTimeline(targetedUser, page));

                        if (statuses.size() > 0) {
                            for (Status status : statuses) {
                                String rawJSON = TwitterObjectFactory.getRawJSON(status);
                                writer.println(rawJSON);

                                totalTweets += 1;
                                if (totalTweets >= NUMBER_OF_TWEETS) {
                                    tweetCounterReached = true;
                                    break;
                                }
                            }
                            if (tweetCounterReached) {
                                break;
                            }
                        }
                    }

                    // If user's total tweet are less 
                    // than 195 then no next call
                    if (size == 0) {
                        if (totalTweets < 195) {
                            break;
                        }
                    }

                    // If user's all tweets parsed 
                    // then proceed to next user 
                    if (totalTweets == size) {
                        break;
                    }

                    size = totalTweets;

                    statuses.clear();

                } catch (TwitterException e) {

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

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

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

                        // Load OAuth user
                        tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO);
                        twitter = tf.getInstance();

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

                        RemainingCalls = AppOAuths.RemainingCalls - 2;
                        RemainingCallsCounter = 0;

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

                    if (totalTweets < 1) {
                        writer.close();
                        // Remove file if tweets not found
                        File fileToDelete = new File(fileName);
                        fileToDelete.delete();
                    }

                    // Update stats
                    String fieldValues = "`tweets_dumped_all` = 2";
                    String where = "id = " + targetedUserID;
                    DB.Update("`twitter_users`", fieldValues, where);
                    continue OUTERMOST;

                }

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

                    // Load OAuth user
                    tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO);
                    twitter = tf.getInstance();

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

                    RemainingCalls = AppOAuths.RemainingCalls - 2;
                    RemainingCallsCounter = 0;

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

            } // while get tweets
            writer.close();

            if (totalTweets > 0) {

                System.out.println("Total dumped tweets of " + targetedUser + " are: " + totalTweets);
                // Update stats
                String fieldValues = "`tweets_dumped_all` = 1, " + " `tweets_all_count` = " + totalTweets;
                String where = "id = " + targetedUserID;
                DB.Update("`twitter_users`", fieldValues, where);
            } else {

                // Update stats
                String fieldValues = "`tweets_dumped_all` = 2, " + " `tweets_all_count` = " + totalTweets;
                String where = "id = " + targetedUserID;
                DB.Update("`twitter_users`", fieldValues, where);

                // Remove file if tweets not found
                File fileToDelete = new File(fileName);
                fileToDelete.delete();
            }

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

                // Load OAuth user
                tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO);
                twitter = tf.getInstance();

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

                RemainingCalls = AppOAuths.RemainingCalls - 2;
                RemainingCallsCounter = 0;

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

            System.out.flush();
        } // while get users from database
    } catch (TwitterException te) {
        // te.printStackTrace();
        System.out.println("Failed to get tweets: " + te.getMessage());
        System.exit(-1);
    }
    System.out.println("!!!! DONE !!!!");

    // Close System.out for this thread which will
    // flush and close this thread.
    System.out.close();
}

From source file:timeline.FilesThreaderParser.java

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

    // Check how many arguments were passed in
    if ((args == null) || (args.length < 7)) {
        System.err.println("7 Parameters are required to launch a Job.");
        System.err.println("First: String 'INPUT: " + "/path/to/perline/screen_names/files/'");
        System.err.println("Second: String 'OUTPUT_PATH'");
        System.err.println("Third: (int) Total Number Of Jobs");
        System.err.println("Fourth: (int) This Job Number");
        System.err.println("Fifth: (int) Seconds to pause between " + "next launch");
        System.err.println("Sixth: (int) Number of Tweets to get. Max 3200");
        System.err.println("Name of current threader.");
        System.err.println("Example: fileName.class /output/path " + "10 2 3200 pool-1-thread-1");
        System.exit(-1);/*from  w  w  w.  j  a va2 s.  com*/
    }

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

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

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

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

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

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

    AppOAuth AppOAuths = new AppOAuth();
    Misc helpers = new Misc();
    String endpoint = "/statuses/user_timeline";

    try {

        int TotalWorkLoad = 0;
        ArrayList<String> allFiles = null;
        try {
            final File folder = new File(inputPath);
            allFiles = helpers.listFilesForSingleFolder(folder);
            TotalWorkLoad = allFiles.size();
        } catch (Exception e) {

            System.err.println("Input folder is not exists: " + e.getMessage());
            System.exit(-1);
        }

        System.out.println("Total Workload is: " + TotalWorkLoad);

        if (TotalWorkLoad < 1) {
            System.err.println("No input file exists in: " + inputPath);
            System.exit(-1);
        }

        if (TOTAL_JOBS > TotalWorkLoad) {
            System.err.println("Number of jobs are more than total work"
                    + " load. Please reduce 'Number of jobs' to launch.");
            System.exit(-1);
        }

        float TotalWorkLoadf = TotalWorkLoad;
        float TOTAL_JOBSf = TOTAL_JOBS;
        float res = (TotalWorkLoadf / TOTAL_JOBSf);

        int chunkSize = (int) Math.ceil(res);
        int offSet = JOB_NO * chunkSize;
        int chunkSizeToGet = (JOB_NO + 1) * chunkSize;

        System.out.println("My Share is " + chunkSize);
        System.out.println("My offSet is " + offSet);
        System.out.println("My chunkSizeToGet is " + chunkSizeToGet);
        System.out.println();

        /**
         * wait before launching actual job
         */
        int secondsToPause = 0;
        try {
            secondsToPause = Integer.parseInt(args[4]);
        } catch (NumberFormatException e) {
            System.err.println("Argument" + args[4] + " must be an integer.");
            System.exit(-1);
        }

        secondsToPause = (TOTAL_JOBS * secondsToPause) - (JOB_NO * secondsToPause);
        System.out.println("secondsToPause: " + secondsToPause);
        helpers.pause(secondsToPause);
        /**
         * wait before launching actual job
         */

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

        int RemainingCalls = AppOAuths.RemainingCalls - 2;
        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);

        System.out.println("User's Tweets");

        System.out.println("Trying to create output directory");

        int dirCounter = 1;
        int fileCounter = 0;

        String filesPath = OutputDirPath + "/" + ThreadName + "-tweets-" + dirCounter;
        File theDir = new File(filesPath);

        // If the directory does not exist, create it
        if (!theDir.exists()) {
            try {
                theDir.mkdirs();

            } catch (SecurityException se) {

                System.err.println("Could not create output " + "directory: " + OutputDirPath + "/" + ThreadName
                        + "-tweets-" + dirCounter);
                System.err.println(se.getMessage());
                System.exit(-1);
            }
        }

        if (JOB_NO + 1 == TOTAL_JOBS) {
            chunkSizeToGet = TotalWorkLoad;
        }

        // to write output in a file
        System.out.flush();

        List<String> myFilesShare = allFiles.subList(offSet, chunkSizeToGet);

        for (String myFile : myFilesShare) {
            System.out.println("Going to parse file: " + myFile);
            System.out.println();

            try (BufferedReader br = new BufferedReader(new FileReader(inputPath + "/" + myFile))) {
                String line;

                OUTERMOST: while ((line = br.readLine()) != null) {

                    if (fileCounter >= 30000) {

                        dirCounter++;
                        fileCounter = 0;
                        filesPath = OutputDirPath + "/" + ThreadName + "-tweets-" + dirCounter;
                        theDir = new File(filesPath);

                        // If the directory does not exist, create it
                        if (!theDir.exists()) {
                            try {
                                theDir.mkdirs();

                            } catch (SecurityException se) {

                                System.err.println("Could not create output " + "directory: " + OutputDirPath
                                        + "/" + ThreadName + "-tweets-" + dirCounter);
                                System.err.println(se.getMessage());
                                System.exit(-1);
                            }
                        }
                    }

                    System.out.println("Going to get tweets of " + "Screen-name / user_id: " + line);

                    String targetedUser = line.trim();
                    System.out.println("Targeted User: " + targetedUser);

                    // Create User file to push tweets in it
                    String fileName = filesPath + "/" + targetedUser;
                    PrintWriter writer = new PrintWriter(fileName, "UTF-8");

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

                    List<Status> statuses = new ArrayList<>();
                    int size = statuses.size();
                    int pageno = 1;
                    int totalTweets = 0;
                    boolean tweetCounterReached = false;
                    System.out.println("NUMBER_OF_TWEETS to get:" + NUMBER_OF_TWEETS);
                    System.out.println();

                    while (true) {
                        try {

                            Paging page = new Paging(pageno++, 200);

                            if (chckedNumaric) {

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

                                statuses.addAll(twitter.getUserTimeline(LongValueTargetedUser, page));

                                if (statuses.size() > 0) {
                                    for (Status status : statuses) {
                                        String rawJSON = TwitterObjectFactory.getRawJSON(status);
                                        writer.println(rawJSON);

                                        totalTweets += 1;
                                        if (totalTweets >= NUMBER_OF_TWEETS) {
                                            tweetCounterReached = true;
                                            break;
                                        }
                                    }
                                    if (tweetCounterReached) {
                                        break;
                                    }
                                }
                            } else {

                                statuses.addAll(twitter.getUserTimeline(targetedUser, page));

                                if (statuses.size() > 0) {
                                    for (Status status : statuses) {
                                        String rawJSON = TwitterObjectFactory.getRawJSON(status);
                                        writer.println(rawJSON);

                                        totalTweets += 1;
                                        if (totalTweets >= NUMBER_OF_TWEETS) {
                                            tweetCounterReached = true;
                                            break;
                                        }
                                    }
                                    if (tweetCounterReached) {
                                        break;
                                    }
                                }
                            }

                            // If user's total tweet are less 
                            // than 195 then no next call
                            if (size == 0) {
                                if (totalTweets < 195) {
                                    break;
                                }
                            }

                            // If user's all tweets parsed 
                            // then proceed to next user 
                            if (totalTweets == size) {
                                break;
                            }

                            size = totalTweets;

                            statuses.clear();

                        } catch (TwitterException e) {

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

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

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

                                // Load OAuth user
                                tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO);
                                twitter = tf.getInstance();

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

                                RemainingCalls = AppOAuths.RemainingCalls - 2;
                                RemainingCallsCounter = 0;

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

                            if (totalTweets < 1) {
                                writer.close();
                                // Remove file if tweets not found
                                File fileToDelete = new File(fileName);
                                fileToDelete.delete();
                            }

                            continue OUTERMOST;

                        }

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

                            // Load OAuth user
                            tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO);
                            twitter = tf.getInstance();

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

                            RemainingCalls = AppOAuths.RemainingCalls - 2;
                            RemainingCallsCounter = 0;

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

                    } // while get tweets
                    writer.close();

                    if (totalTweets > 0) {
                        fileCounter++;
                        System.out.println("Total dumped tweets of " + targetedUser + " are: " + totalTweets);

                    } else {

                        // Remove file if tweets not found
                        File fileToDelete = new File(fileName);
                        fileToDelete.delete();
                    }

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

                        // Load OAuth user
                        tf = AppOAuths.loadOAuthUser(endpoint, TOTAL_JOBS, JOB_NO);
                        twitter = tf.getInstance();

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

                        RemainingCalls = AppOAuths.RemainingCalls - 2;
                        RemainingCallsCounter = 0;

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

                } // while get users

            } // read my single file
            catch (IOException e) {
                System.err.println("Failed to read lines from " + myFile);
            }

            File currentFile = new File(inputPath + "/" + myFile);
            currentFile.delete();

            // to write output in a file
            System.out.flush();
        } // all my files share
    } catch (TwitterException te) {
        // te.printStackTrace();
        System.out.println("Failed to get tweets: " + te.getMessage());
        System.exit(-1);
    }
    System.out.println("!!!! DONE !!!!");

    // Close System.out for this thread which will
    // flush and close this thread.
    System.out.close();
}

From source file:timeline.DBNonThreader.java

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

    // Check how many arguments were passed in
    if ((args == null) || (args.length == 0)) {
        System.err.println("First: 'OUTPUT_PATH' is mendatory.");
        System.err.println("Second: (int) Number of Tweets to get. Max 3200");
        System.err.println("Third: 'screen_name / id_str'" + " is optional.");
        System.err.println("If 3rd argument not provided then provide" + " Twitter users through database.");

        System.exit(-1);//  w  w  w .j a v a  2s  .  co  m
    }

    MysqlDB DB = new MysqlDB();
    AppOAuth AppOAuths = new AppOAuth();
    Misc helpers = new Misc();
    String endpoint = "/statuses/user_timeline";

    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 NUMBER_OF_TWEETS = 3200;
    try {
        NUMBER_OF_TWEETS = Integer.parseInt(args[1]);
    } catch (Exception e) {
        System.err.println("Argument" + args[1] + " must be an integer.");
        System.exit(-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 - 2;
        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);

        System.out.println("User's Tweets");

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

            String selectQuery = "SELECT `id`,`targeteduser` FROM " + "`twitter_users` WHERE "
                    + "`tweets_dumped_all` = 0";

            ResultSet results = DB.selectQ(selectQuery);

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

            System.out.println("Trying to create output directory");
            String filesPath = OutputDirPath + "/";
            File theDir = new File(filesPath);

            // If the directory does not exist, create it
            if (!theDir.exists()) {

                try {
                    theDir.mkdirs();

                } catch (SecurityException se) {

                    System.err.println("Could not create output " + "directory: " + OutputDirPath);
                    System.err.println(se.getMessage());
                    System.exit(-1);
                }
            }

            OUTERMOST: while (results.next()) {

                int targetedUserID = results.getInt("id");
                targetedUser = results.getString("targeteduser");
                System.out.println("Targeted User: " + targetedUser);

                String fileName = filesPath + "/" + targetedUser;
                PrintWriter writer = new PrintWriter(fileName, "UTF-8");

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

                List<Status> statuses = new ArrayList<>();
                int size = statuses.size();
                int pageno = 1;
                int totalTweets = 0;
                boolean tweetCounterReached = false;
                System.out.println("NUMBER_OF_TWEETS to get:" + NUMBER_OF_TWEETS);
                while (true) {

                    try {

                        Paging page = new Paging(pageno++, 200);

                        if (chckedNumaric) {

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

                            statuses.addAll(twitter.getUserTimeline(LongValueTargetedUser, page));

                            if (statuses.size() > 0) {
                                for (Status status : statuses) {
                                    String rawJSON = TwitterObjectFactory.getRawJSON(status);
                                    writer.println(rawJSON);

                                    totalTweets += 1;
                                    if (totalTweets >= NUMBER_OF_TWEETS) {
                                        tweetCounterReached = true;
                                        break;
                                    }
                                }
                                if (tweetCounterReached) {
                                    break;
                                }
                            }
                        } else {

                            statuses.addAll(twitter.getUserTimeline(targetedUser, page));

                            if (statuses.size() > 0) {
                                for (Status status : statuses) {
                                    String rawJSON = TwitterObjectFactory.getRawJSON(status);
                                    writer.println(rawJSON);

                                    totalTweets += 1;
                                    if (totalTweets >= NUMBER_OF_TWEETS) {
                                        tweetCounterReached = true;
                                        break;
                                    }
                                }
                                if (tweetCounterReached) {
                                    break;
                                }
                            }
                        }

                        // If user's total tweet are less than 195 
                        // then no next call
                        if (size == 0) {
                            if (totalTweets < 195) {
                                break;
                            }
                        }

                        // If user's all tweets parsed 
                        // then proceed to next user 
                        if (totalTweets == size) {
                            break;
                        }

                        size = totalTweets;

                        statuses.clear();

                    } catch (TwitterException e) {

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

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

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

                            // Load OAuth user
                            tf = AppOAuths.loadOAuthUser(endpoint);
                            twitter = tf.getInstance();

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

                            RemainingCalls = AppOAuths.RemainingCalls - 2;
                            RemainingCallsCounter = 0;

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

                        if (totalTweets < 1) {
                            writer.close();
                            // Remove file if tweets not found
                            File fileToDelete = new File(fileName);
                            fileToDelete.delete();
                        }

                        // Update stats
                        String fieldValues = "`tweets_dumped_all` = 2";
                        String where = "id = " + targetedUserID;
                        DB.Update("`twitter_users`", fieldValues, where);
                        continue OUTERMOST;

                    }

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

                        // Load OAuth user
                        tf = AppOAuths.loadOAuthUser(endpoint);
                        twitter = tf.getInstance();

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

                        RemainingCalls = AppOAuths.RemainingCalls - 2;
                        RemainingCallsCounter = 0;

                        System.out.println("New Remianing Calls: " + RemainingCalls);
                    }
                } // while get tweets
                writer.close();

                if (totalTweets > 0) {

                    System.out.println("Total dumped tweets of " + targetedUser + " are: " + totalTweets);

                    // Update stats
                    String fieldValues = "`tweets_dumped_all` = 1, " + " `tweets_all_count` = " + totalTweets;
                    String where = "id = " + targetedUserID;
                    DB.Update("`twitter_users`", fieldValues, where);
                } else {

                    // Update stats
                    String fieldValues = "`tweets_dumped_all` = 2";
                    String where = "id = " + targetedUserID;
                    DB.Update("`twitter_users`", fieldValues, where);

                    // Remove file if tweets not found
                    File fileToDelete = new File(fileName);
                    fileToDelete.delete();
                }

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

                    // Load OAuth user
                    tf = AppOAuths.loadOAuthUser(endpoint);
                    twitter = tf.getInstance();

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

                    RemainingCalls = AppOAuths.RemainingCalls - 2;
                    RemainingCallsCounter = 0;

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

            } // while get users from database

        } else {
            // screen_name / user_id provided by arguments
            System.out.println("screen_name / user_id provided by arguments");

            System.out.println("Trying to create output directory");
            String filesPath = OutputDirPath + "/";
            File theDir = new File(filesPath);

            // If the directory does not exist, create it
            if (!theDir.exists()) {

                try {
                    theDir.mkdirs();

                } catch (SecurityException se) {

                    System.err.println("Could not create output " + "directory: " + OutputDirPath);
                    System.err.println(se.getMessage());
                    System.exit(-1);
                }
            }

            System.out.println("Targeted User: " + targetedUser);

            String fileName = filesPath + "/" + targetedUser;
            PrintWriter writer = new PrintWriter(fileName, "UTF-8");

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

            List<Status> statuses = new ArrayList<>();
            int size = statuses.size();
            int pageno = 1;
            int totalTweets = 0;
            boolean tweetCounterReached = false;
            System.out.println("NUMBER_OF_TWEETS to get:" + NUMBER_OF_TWEETS);
            while (true) {

                try {

                    Paging page = new Paging(pageno++, 200);

                    if (chckedNumaric) {

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

                        statuses.addAll(twitter.getUserTimeline(LongValueTargetedUser, page));

                        if (statuses.size() > 0) {
                            for (Status status : statuses) {
                                String rawJSON = TwitterObjectFactory.getRawJSON(status);
                                writer.println(rawJSON);

                                totalTweets += 1;
                                if (totalTweets >= NUMBER_OF_TWEETS) {
                                    tweetCounterReached = true;
                                    break;
                                }
                            }
                            if (tweetCounterReached) {
                                break;
                            }
                        }
                    } else {

                        statuses.addAll(twitter.getUserTimeline(targetedUser, page));

                        if (statuses.size() > 0) {
                            for (Status status : statuses) {
                                String rawJSON = TwitterObjectFactory.getRawJSON(status);
                                writer.println(rawJSON);

                                totalTweets += 1;
                                if (totalTweets >= NUMBER_OF_TWEETS) {
                                    tweetCounterReached = true;
                                    break;
                                }
                            }
                            if (tweetCounterReached) {
                                break;
                            }
                        }
                    }

                    // If user's total tweet are less than 195 then no next call
                    if (size == 0) {
                        if (totalTweets < 195) {
                            break;
                        }
                    }

                    // If user's all tweets parsed then proceed to next user 
                    if (totalTweets == size) {
                        break;
                    }

                    size = totalTweets;

                    statuses.clear();

                } catch (TwitterException e) {

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

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

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

                        // Load OAuth user
                        tf = AppOAuths.loadOAuthUser(endpoint);
                        twitter = tf.getInstance();

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

                        RemainingCalls = AppOAuths.RemainingCalls - 2;
                        RemainingCallsCounter = 0;

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

                    if (totalTweets < 1) {
                        writer.close();
                        // Remove file if tweets not found
                        File fileToDelete = new File(fileName);
                        fileToDelete.delete();
                    }
                }

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

                    // Load OAuth user
                    tf = AppOAuths.loadOAuthUser(endpoint);
                    twitter = tf.getInstance();

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

                    RemainingCalls = AppOAuths.RemainingCalls - 2;
                    RemainingCallsCounter = 0;

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

            } // while get tweets
            writer.close();

            if (totalTweets > 0) {
                System.out.println("Total dumped tweets of " + targetedUser + " are: " + totalTweets);
            } else {

                // Remove file if tweets not found
                File fileToDelete = new File(fileName);
                fileToDelete.delete();
            }

        } // screen_name / user_id provided by arguments

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