Example usage for java.util ArrayList subList

List of usage examples for java.util ArrayList subList

Introduction

In this page you can find the example usage for java.util ArrayList subList.

Prototype

public List<E> subList(int fromIndex, int toIndex) 

Source Link

Document

Returns a view of the portion of this list between the specified fromIndex , inclusive, and toIndex , exclusive.

Usage

From source file:Main.java

public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();

    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");

    List lst = arrayList.subList(1, 3);
    for (int i = 0; i < lst.size(); i++)
        System.out.println(lst.get(i));

    // remove one element from sub list
    Object obj = lst.remove(0);//from  w  ww .j  ava 2  s  . c o m
    System.out.println(obj + " is removed");

    for (String str : arrayList)
        System.out.println(str);
}

From source file:Main.java

public static void main(String args[]) {
    ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

    arrlist.add(1);//  w ww .  j a v  a 2  s .  co  m
    arrlist.add(2);
    arrlist.add(3);
    arrlist.add(4);
    arrlist.add(5);

    System.out.println(arrlist);

    List<Integer> arrlist2 = arrlist.subList(2, 4);

    System.out.println(arrlist2);

}

From source file:MainClass.java

public static void main(String[] args) {
    ArrayList myList = new ArrayList(5);
    for (int i = 0; i < 5; i++) {
        myList.add(new Integer(i));
    }//from   w  w w . j a v  a  2  s. co m
    System.out.println("List contains " + myList.size() + " elements");

    Integer int2 = new Integer(2);
    System.out.println("List contains Integer(2): " + myList.contains(int2));
    System.out.println("Integer(2) is at index " + myList.indexOf(int2));

    myList.set(2, new Integer(99));
    System.out.println("Get element at index 2: " + myList.get(2));

    myList.ensureCapacity(15);
    for (int i = 10; i < 15; i++) {
        myList.add(new Integer(i));
    }

    myList.subList(10, 15).clear();
    myList.trimToSize();

    System.out.println(myList);
}

From source file:friendsandfollowers.FilesThreaderFriendsIDsParser.java

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

    // Check how many arguments were passed in
    if ((args == null) || (args.length < 5)) {
        System.err.println("5 Parameters are required  plus one optional " + "parameter to launch a Job.");
        System.err.println("First: String 'INPUT: DB or /input/path/'");
        System.err.println("Second: String 'OUTPUT: /output/path/'");
        System.err.println("Third: (int) Total Number Of Jobs");
        System.err.println("Fourth: (int) This Job Number");
        System.err.println("Fifth: (int) Number of seconds to pause");
        System.err.println("Sixth: (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("Example: fileToRun /input/path/ " + "/output/path/ 10 1 3 75000");
        System.exit(-1);/* w w  w.  j  av a 2s .c om*/
    }

    // TODO documentation for command line
    AppOAuth AppOAuths = new AppOAuth();
    Misc helpers = new Misc();
    String endpoint = "/friends/ids";

    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 outputPath = null;
    try {
        outputPath = 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 secondsToPause = 0;
    try {
        secondsToPause = Integer.parseInt(args[4]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + args[4] + " must be an integer.");
        System.exit(-1);
    }

    int IDS_TO_FETCH_INT = -1;
    if (args.length == 6) {
        try {
            IDS_TO_FETCH_INT = Integer.parseInt(args[5]);
        } catch (NumberFormatException e) {
            System.err.println("Argument" + args[5] + " 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;
    }

    secondsToPause = (TOTAL_JOBS * secondsToPause) - (JOB_NO * secondsToPause);
    System.out.println("secondsToPause: " + secondsToPause);
    helpers.pause(secondsToPause);

    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 screen names 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();

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

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

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

        IDs ids;
        System.out.println("Going to get friends ids.");

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

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

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

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

            try (BufferedReader br = new BufferedReader(new FileReader(inputPath + "/" + myFile))) {
                String line;
                OUTERMOST: while ((line = br.readLine()) != null) {
                    // process the line.

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

                    String targetedUser = line.trim(); // tmp
                    long cursor = -1;
                    int idsLoopCounter = 0;
                    int totalIDs = 0;

                    PrintWriter writer = new PrintWriter(outputPath + "/" + 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, TOTAL_JOBS, JOB_NO);
                                twitter = tf.getInstance();

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

                                RemainingCalls = AppOAuths.RemainingCalls;
                                RemainingCallsCounter = 0;

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

                            // Remove file if ids not found
                            if (totalIDs == 0) {

                                System.out.println("No ids fetched so removing " + "file " + targetedUser);

                                File fileToDelete = new File(outputPath + "/" + targetedUser);
                                fileToDelete.delete();
                            }
                            System.out.println();

                            // 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, TOTAL_JOBS, JOB_NO);
                            twitter = tf.getInstance();

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

                            RemainingCalls = AppOAuths.RemainingCalls;
                            RemainingCallsCounter = 0;

                            System.out.println("New OAuth 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);

                    // Remove file if ids not found
                    if (totalIDs == 0) {

                        System.out.println("No ids fetched so removing " + "file " + targetedUser);

                        File fileToDelete = new File(outputPath + "/" + targetedUser);
                        fileToDelete.delete();
                    }
                    System.out.println();

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

            // to write output in a file
            System.out.flush();
        } // all my files share

    } catch (TwitterException te) {
        // te.printStackTrace();
        System.err.println("Failed to get friends' ids: " + 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:friendsandfollowers.FilesThreaderFollowersIDsParser.java

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

    // Check how many arguments were passed in
    if ((args == null) || (args.length < 5)) {
        System.err.println("5 Parameters are required  plus one optional " + "parameter to launch a Job.");
        System.err.println("First: String 'INPUT: DB or /input/path/'");
        System.err.println("Second: String 'OUTPUT: /output/path/'");
        System.err.println("Third: (int) Total Number Of Jobs");
        System.err.println("Fourth: (int) This Job Number");
        System.err.println("Fifth: (int) Number of seconds to pause");
        System.err.println("Sixth: (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("Example: fileToRun /input/path/ " + "/output/path/ 10 1 3 75000");
        System.exit(-1);/*from   w w w.ja v  a 2 s. c o m*/
    }

    // TODO documentation for command line
    AppOAuth AppOAuths = new AppOAuth();
    Misc helpers = new Misc();
    String endpoint = "/followers/ids";

    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 outputPath = null;
    try {
        outputPath = 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 secondsToPause = 0;
    try {
        secondsToPause = Integer.parseInt(args[4]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + args[4] + " must be an integer.");
        System.exit(-1);
    }

    int IDS_TO_FETCH_INT = -1;
    if (args.length == 6) {
        try {
            IDS_TO_FETCH_INT = Integer.parseInt(args[5]);
        } catch (NumberFormatException e) {
            System.err.println("Argument" + args[5] + " 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;
    }

    secondsToPause = (TOTAL_JOBS * secondsToPause) - (JOB_NO * secondsToPause);
    System.out.println("secondsToPause: " + secondsToPause);
    helpers.pause(secondsToPause);

    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 screen names 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();

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

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

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

        IDs ids;
        System.out.println("Going to get followers ids.");

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

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

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

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

            try (BufferedReader br = new BufferedReader(new FileReader(inputPath + "/" + myFile))) {
                String line;
                OUTERMOST: while ((line = br.readLine()) != null) {
                    // process the line.

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

                    String targetedUser = line.trim(); // tmp
                    long cursor = -1;
                    int idsLoopCounter = 0;
                    int totalIDs = 0;

                    PrintWriter writer = new PrintWriter(outputPath + "/" + 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, TOTAL_JOBS, JOB_NO);
                                twitter = tf.getInstance();

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

                                RemainingCalls = AppOAuths.RemainingCalls;
                                RemainingCallsCounter = 0;

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

                            // Remove file if ids not found
                            if (totalIDs == 0) {

                                System.out.println("No ids fetched so removing " + "file " + targetedUser);

                                File fileToDelete = new File(outputPath + "/" + targetedUser);
                                fileToDelete.delete();
                            }
                            System.out.println();

                            // 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, TOTAL_JOBS, JOB_NO);
                            twitter = tf.getInstance();

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

                            RemainingCalls = AppOAuths.RemainingCalls;
                            RemainingCallsCounter = 0;

                            System.out.println("New OAuth 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);

                    // Remove file if ids not found
                    if (totalIDs == 0) {

                        System.out.println("No ids fetched so removing " + "file " + targetedUser);

                        File fileToDelete = new File(outputPath + "/" + targetedUser);
                        fileToDelete.delete();
                    }
                    System.out.println();

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

            // to write output in a file
            System.out.flush();
        } // all my files share

    } catch (TwitterException te) {
        // te.printStackTrace();
        System.err.println("Failed to get followers' ids: " + 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:profiles.FilesThreaderParser.java

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

    // 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 'INPUT: /input/path/'");
        System.err.println("Second: String 'OUTPUT: /output/path/'");
        System.err.println("Third: (int) Total Number Of Jobs");
        System.err.println("Fourth: (int) This Job Number");
        System.err.println("Fifth: (int) Number of seconds to pause");
        System.err.println("Example: fileToRun /input/path/ /output/path/ " + "10 1 3");
        System.exit(-1);/* www  . ja  va  2 s.c  o  m*/
    }

    // TODO documentation for command line
    AppOAuth AppOAuths = new AppOAuth();
    Misc helpers = new Misc();
    String endpoint = "/users/lookup";

    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 outputPath = null;
    try {
        outputPath = 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 secondsToPause = 0;
    try {
        secondsToPause = Integer.parseInt(args[4]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + args[4] + " must be an integer.");
        System.exit(-1);
    }

    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 targeted user 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();

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

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

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

        System.out.println("Going to get Profiles.");

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

        secondsToPause = (TOTAL_JOBS * secondsToPause) - (JOB_NO * secondsToPause);
        System.out.println("secondsToPause: " + secondsToPause);
        helpers.pause(secondsToPause);

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

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

        for (String fileName : fileNamesShare) {

            System.out.println("Going to parse file: " + fileName);

            try {

                // open file to write all profiles
                String filesPath = outputPath + "/";
                PrintWriter writer = new PrintWriter(filesPath + "/" + fileName, "UTF-8");

                try (BufferedReader br = new BufferedReader(new FileReader(inputPath + "/" + fileName))) {
                    String jsonString;
                    while ((jsonString = br.readLine()) != null) {
                        // process the line.

                        List<String> fileContent = new ArrayList<>();
                        fileContent.add(jsonString);

                        String[] strarray = fileContent.toArray(new String[0]);

                        String ss = Arrays.toString(strarray);

                        JSONArray obj = new JSONArray(ss);
                        JSONObject obj4 = (JSONObject) obj.get(0);

                        JSONArray idsS = (JSONArray) obj4.get("ids");

                        ArrayList<String> Idslist = new ArrayList<String>();
                        if (idsS != null) {
                            int len = idsS.length();
                            for (int i = 0; i < len; i++) {
                                Idslist.add(idsS.get(i).toString());
                            }
                        }

                        for (int start = 0; start < Idslist.size(); start += 100) {
                            int end = Math.min(start + 100, Idslist.size());
                            List<String> sublist = Idslist.subList(start, end);

                            long[] idsdata = new long[sublist.size()];
                            for (int i = 0; i < sublist.size(); i++) {
                                idsdata[i] = Long.valueOf(sublist.get(i));
                            }
                            ResponseList<User> profiles = null;

                            while (true) {

                                try {
                                    profiles = twitter.lookupUsers(idsdata);

                                    if (profiles.size() > 0) {
                                        for (User user : profiles) {
                                            String rawJSON = TwitterObjectFactory.getRawJSON(user);

                                            // put profilesJSON in a file
                                            try {
                                                writer.println(rawJSON);
                                            } catch (Exception e) {
                                                System.err.println(e.getMessage());
                                                System.exit(0);
                                            }
                                        }

                                        break;
                                    }

                                } catch (TwitterException te) {

                                    // 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 profiles

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

                        }

                    }

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

            // delete file if processed
            File fileToDelete = new File(inputPath + "/" + "/" + fileName);
            fileToDelete.delete();

            // to write output in a file
            System.out.flush();
        } // all my files

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

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

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

            RemainingCalls = AppOAuths.RemainingCalls;
            RemainingCallsCounter = 0;

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

    } catch (TwitterException te) {
        // te.printStackTrace();
        System.err.println("Failed to get Profiles: " + 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 ww  w  .  ja  v  a2s.  c  om
    }

    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:bb.mcmc.analysis.ConvergeStatUtils.java

public static <T> List<T> getSubList(ArrayList<T> list, int burnin) {
    List<T> subList = list.subList(burnin, list.size());
    return subList;
}

From source file:bb.mcmc.analysis.ConvergeStatUtils.java

public static <T> List<T> getSubList(ArrayList<T> list, int start, int subListLength) {
    List<T> subList = list.subList(start, subListLength);
    return subList;
}

From source file:com.espe.distribuidas.pmaldito.servidorbdd.operaciones.Archivo.java

/**
 * permite separar la lista de detalles en registros de listas
 *
 * @param valosCampos//from   w w w . j  a v a  2 s .co m
 * @return
 */
public static ArrayList<String> detalle(ArrayList<String> valosCampos) {
    int contador = 0;
    ArrayList<String> detalleParse = new ArrayList<>();
    while (contador < valosCampos.size()) {
        detalleParse.add(parsearCampos(valosCampos.subList(contador, contador + 5)));
        contador = contador + 5;
    }
    return detalleParse;
}