Example usage for java.util ArrayList clear

List of usage examples for java.util ArrayList clear

Introduction

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

Prototype

public void clear() 

Source Link

Document

Removes all of the elements from this list.

Usage

From source file:org.opendatakit.security.server.SecurityServiceUtil.java

/**
 * Method to enforce an access configuration constraining only registered users, authenticated
 * users and anonymous access.//from ww w. ja v  a 2  s .  com
 * 
 * Add additional checks of the incoming parameters and patch things up if the incoming list of
 * users omits the super-user.
 * 
 * @param users
 * @param anonGrants
 * @param allGroups
 * @param cc
 * @throws DatastoreFailureException
 * @throws AccessDeniedException
 */
public static final void setStandardSiteAccessConfiguration(ArrayList<UserSecurityInfo> users,
        ArrayList<GrantedAuthorityName> allGroups, CallingContext cc)
        throws DatastoreFailureException, AccessDeniedException {

    // remove anonymousUser from the set of users and collect its
    // permissions (anonGrantStrings) which will be placed in
    // the granted authority hierarchy table.
    List<String> anonGrantStrings = new ArrayList<String>();
    {
        UserSecurityInfo anonUser = null;
        for (UserSecurityInfo i : users) {
            if (i.getType() == UserType.ANONYMOUS) {
                anonUser = i;
                // clean up grants for anonymousUser --
                // ignore anonAuth (the grant under which we will place things)
                // and forbid Site Admin
                for (GrantedAuthorityName a : i.getAssignedUserGroups()) {
                    if (anonAuth.getAuthority().equals(a.name()))
                        continue; // avoid circularity...
                    // only allow ROLE_ATTACHMENT_VIEWER and GROUP_ assignments.
                    if (!a.name().startsWith(GrantedAuthorityName.GROUP_PREFIX)) {
                        continue;
                    }
                    // do not allow Site Admin assignments for Anonymous --
                    // or Tables super-user or Tables Administrator.
                    // those all give access to the full set of users on the system
                    // and giving that information to Anonymous is a security
                    // risk.
                    if (GrantedAuthorityName.GROUP_SITE_ADMINS.equals(a)
                            || GrantedAuthorityName.GROUP_ADMINISTER_TABLES.equals(a)
                            || GrantedAuthorityName.GROUP_SUPER_USER_TABLES.equals(a)) {
                        continue;
                    }
                    anonGrantStrings.add(a.name());
                }
                break;
            }
        }
        if (anonUser != null) {
            users.remove(anonUser);
        }
    }

    // scan through the users and remove any entries under assigned user groups
    // that do not begin with GROUP_.
    //
    // Additionally, if the user is an e-mail, remove the GROUP_DATA_COLLECTORS
    // permission since ODK Collect does not support oauth2 authentication.
    {
        TreeSet<GrantedAuthorityName> toRemove = new TreeSet<GrantedAuthorityName>();
        for (UserSecurityInfo i : users) {
            // only working with registered users
            if (i.getType() != UserType.REGISTERED) {
                continue;
            }
            // get the list of assigned groups
            // -- this is not a copy -- we can directly manipulate this.
            TreeSet<GrantedAuthorityName> assignedGroups = i.getAssignedUserGroups();

            // scan the set of assigned groups and remove any that don't begin with GROUP_
            toRemove.clear();
            for (GrantedAuthorityName name : assignedGroups) {
                if (!name.name().startsWith(GrantedAuthorityName.GROUP_PREFIX)) {
                    toRemove.add(name);
                }
            }
            if (!toRemove.isEmpty()) {
                assignedGroups.removeAll(toRemove);
            }
            // for e-mail accounts, remove the Data Collector permission since ODK Collect
            // does not support an oauth2 authentication mechanism.
            if (i.getEmail() != null) {
                assignedGroups.remove(GrantedAuthorityName.GROUP_DATA_COLLECTORS);
            }
        }
    }

    // find the entry(entries) for the designated super-user(s)
    String superUserUsername = cc.getUserService().getSuperUserUsername();
    int expectedSize = ((superUserUsername != null) ? 1 : 0);
    ArrayList<UserSecurityInfo> superUsers = new ArrayList<UserSecurityInfo>();
    for (UserSecurityInfo i : users) {
        if (i.getType() == UserType.REGISTERED) {
            if (i.getUsername() != null && superUserUsername != null
                    && i.getUsername().equals(superUserUsername)) {
                superUsers.add(i);
            }
        }
    }

    if (superUsers.size() != expectedSize) {
        // we are missing one or both super-users.
        // remove any we have and recreate them from scratch.
        users.removeAll(superUsers);
        superUsers.clear();

        // Synthesize a UserSecurityInfo object for the super-user(s)
        // and add it(them) to the list.

        try {
            List<RegisteredUsersTable> tList = RegisteredUsersTable.assertSuperUsers(cc);

            for (RegisteredUsersTable t : tList) {
                UserSecurityInfo i = new UserSecurityInfo(t.getUsername(), t.getFullName(), t.getEmail(),
                        UserSecurityInfo.UserType.REGISTERED);
                superUsers.add(i);
                users.add(i);
            }

        } catch (ODKDatastoreException e) {
            e.printStackTrace();
            throw new DatastoreFailureException("Incomplete update");
        }
    }

    // reset super-user privileges to have (just) site admin privileges
    // even if caller attempts to change, add, or remove them.
    for (UserSecurityInfo i : superUsers) {
        TreeSet<GrantedAuthorityName> grants = new TreeSet<GrantedAuthorityName>();
        grants.add(GrantedAuthorityName.GROUP_SITE_ADMINS);
        grants.add(GrantedAuthorityName.ROLE_SITE_ACCESS_ADMIN);
        // override whatever the user gave us.
        i.setAssignedUserGroups(grants);
    }

    try {
        // enforce our fixed set of groups and their inclusion hierarchy.
        // this is generally a no-op during normal operations.
        GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(siteAuth,
                SecurityServiceUtil.siteAdministratorGrants, cc);
        GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(administerTablesAuth,
                SecurityServiceUtil.administerTablesGrants, cc);
        GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(superUserTablesAuth,
                SecurityServiceUtil.superUserTablesGrants, cc);
        GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(synchronizeTablesAuth,
                SecurityServiceUtil.synchronizeTablesGrants, cc);
        GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(dataOwnerAuth,
                SecurityServiceUtil.dataOwnerGrants, cc);
        GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(dataViewerAuth,
                SecurityServiceUtil.dataViewerGrants, cc);
        GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(dataCollectorAuth,
                SecurityServiceUtil.dataCollectorGrants, cc);

        // place the anonymous user's permissions in the granted authority table.
        GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(anonAuth, anonGrantStrings, cc);

        // get all granted authority names
        TreeSet<String> authorities = GrantedAuthorityHierarchyTable
                .getAllPermissionsAssignableGrantedAuthorities(cc.getDatastore(), cc.getCurrentUser());
        // remove the groups that have structure (i.e., those defined above).
        authorities.remove(siteAuth.getAuthority());
        authorities.remove(administerTablesAuth.getAuthority());
        authorities.remove(superUserTablesAuth.getAuthority());
        authorities.remove(synchronizeTablesAuth.getAuthority());
        authorities.remove(dataOwnerAuth.getAuthority());
        authorities.remove(dataViewerAuth.getAuthority());
        authorities.remove(dataCollectorAuth.getAuthority());
        authorities.remove(anonAuth.getAuthority());

        // delete all hierarchy structures under anything else.
        // i.e., if somehow USER_IS_REGISTERED had been granted GROUP_FORM_MANAGER
        // then this loop would leave USER_IS_REGISTERED without any grants.
        // (it repairs the database to conform to our privilege hierarchy expectations).
        List<String> empty = Collections.emptyList();
        for (String s : authorities) {
            GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(new SimpleGrantedAuthority(s), empty,
                    cc);
        }

        // declare all the users (and remove users that are not in this set)
        Map<UserSecurityInfo, String> pkMap = setUsers(users, cc);

        // now, for each GROUP_..., update the user granted authority
        // table with the users that have that GROUP_... assignment.
        setUsersOfGrantedAuthority(pkMap, siteAuth, cc);
        setUsersOfGrantedAuthority(pkMap, administerTablesAuth, cc);
        setUsersOfGrantedAuthority(pkMap, superUserTablesAuth, cc);
        setUsersOfGrantedAuthority(pkMap, synchronizeTablesAuth, cc);
        setUsersOfGrantedAuthority(pkMap, dataOwnerAuth, cc);
        setUsersOfGrantedAuthority(pkMap, dataViewerAuth, cc);
        setUsersOfGrantedAuthority(pkMap, dataCollectorAuth, cc);
        // all super-users would already have their site admin role and
        // we leave that unchanged. The key is to ensure that the
        // super users are in the users list so they don't get
        // accidentally removed and that they have siteAuth group
        // membership. I.e., we don't need to manage ROLE_SITE_ACCESS_ADMIN
        // here. it is done elsewhere.

    } catch (ODKDatastoreException e) {
        e.printStackTrace();
        throw new DatastoreFailureException("Incomplete update");
    } finally {
        Datastore ds = cc.getDatastore();
        User user = cc.getCurrentUser();
        try {
            SecurityRevisionsTable.setLastRegisteredUsersRevisionDate(ds, user);
        } catch (ODKDatastoreException e) {
            // if it fails, use RELOAD_INTERVAL to force reload.
            e.printStackTrace();
        }
        try {
            SecurityRevisionsTable.setLastRoleHierarchyRevisionDate(ds, user);
        } catch (ODKDatastoreException e) {
            // if it fails, use RELOAD_INTERVAL to force reload.
            e.printStackTrace();
        }
    }
}

From source file:org.sonar.runner.Main.java

private int executeTask() {
    Stats stats = new Stats().start();
    try {/*from   w w w . j  a  v a  2 s.  co  m*/
        if (cli.isDisplayStackTrace()) {
            Logs.info("Error stacktraces are turned on.");
        }
        runnerFactory.create(conf.properties()).execute();

    } catch (Exception e) {
        displayExecutionResult(stats, "FAILURE");
        showError("Error during Sonar runner execution", e, cli.isDisplayStackTrace());
        return Exit.ERROR;
    }

    // add permission to buildUserId
    try {
        String buildUserId = System.getProperty("build.user.id");
        Properties props = conf.properties();
        String login = props.getProperty("sonar.login");

        String hostUrl = (String) props.get("sonar.host.url");
        Map<String, String> env = System.getenv();

        String password = SonarContext.getInstance(props).getSonarPassword();
        String project_key = props.getProperty("sonar.projectKey");
        String command;
        Process proc;
        BufferedReader reader;
        String line = "";
        //String tid = (new Long(Thread.currentThread())).toString();
        String tid = String.valueOf(Thread.currentThread().getId());
        String cookie = "cookie-" + Long.toString(new SecureRandom().nextLong());

        // login
        HttpPost httpRequest;
        ArrayList<BasicNameValuePair> postParameters = new ArrayList<BasicNameValuePair>();

        String reqUrl = URIUtils.extractHost(new URI(hostUrl)).toString() + "/dologin";
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("username", login));
        postParameters.add(new BasicNameValuePair("password", password));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Login succeed");

        //user permission remove anyone
        reqUrl = hostUrl + "/api/permissions/remove"; //permission=user&group=anyone&component=" + project_key ;
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "user"));
        postParameters.add(new BasicNameValuePair("group", "anyone"));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Removed permission 'user' from group anyone");

        //user permission to sonar-users
        reqUrl = hostUrl + "/api/permissions/add"; //?permission=user&group=sonar-users&component=" + project_key;
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "user"));
        postParameters.add(new BasicNameValuePair("group", "sonar-users"));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Added permission 'user' to group sonar-users");

        //admin permission to sonar-administrators
        reqUrl = hostUrl + "/api/permissions/add"; //?permission=admin&group=sonar-administrators&component=" + project_key + "'";
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "admin"));
        postParameters.add(new BasicNameValuePair("group", "sonar-administrators"));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Added permission 'admin' to group sonar-administrators");

        //admin permission to self
        reqUrl = hostUrl + "/api/permissions/add"; //?permission=admin&user=" + buildUserId + "&component=" + project_key + "'";
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "admin"));
        postParameters.add(new BasicNameValuePair("user", buildUserId));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Added permission 'admin' to user " + buildUserId);

        //codeviewer permission to self, maybe unnecessary
        reqUrl = hostUrl + "/api/permissions/add"; //?permission=codeviewer&user=" + buildUserId + "&component=" + project_key;
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "codeviewer"));
        postParameters.add(new BasicNameValuePair("user", buildUserId));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Added permission 'codeviewer' to user " + buildUserId);

        //remove codeviewer permission from anyone
        reqUrl = hostUrl + "/api/permissions/remove"; //?permission=codeviewer&group=anyone&component=" + project_key + "'";
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "codeviewer"));
        postParameters.add(new BasicNameValuePair("group", "anyone"));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Removed permission 'codeviewer' from group anyone");

    } catch (Exception e) {
        showError("Error during Sonar runner execution", e, cli.isDisplayStackTrace());
        return Exit.ERROR;
    }

    displayExecutionResult(stats, "SUCCESS");
    return Exit.SUCCESS;
}

From source file:edu.cudenver.bios.power.test.paper.TestConditionalOrthogonalPolynomial3Factor.java

/**
 * Test GLMM(F) with 1,2, and 3 Factor polynomial 
 * contrasts in C and U matrices//from  w  w w  .j  a v  a 2 s  .c  o  m
 */
public void testOneToThreeFactorPolynomialContrasts() {
    // set up the matrices
    GLMMPowerParameters params = buildInputsWithoutContrasts();
    // run over all tests
    boolean first = true;
    for (Test test : Test.values()) {
        params.clearTestList();
        params.addTest(test);
        // calculate all of the 3 factor polynomial contrasts
        ArrayList<Factor> withinFactorList = new ArrayList<Factor>();
        withinFactorList.add(factorD);
        withinFactorList.add(factorE);
        withinFactorList.add(factorF);
        ArrayList<Factor> betweenFactorList = new ArrayList<Factor>();
        betweenFactorList.add(factorA);
        betweenFactorList.add(factorB);
        betweenFactorList.add(factorC);
        OrthogonalPolynomialContrastCollection withinSubjectContrasts = OrthogonalPolynomials
                .withinSubjectContrast(withinFactorList);
        OrthogonalPolynomialContrastCollection betweenSubjectContrasts = OrthogonalPolynomials
                .betweenSubjectContrast(betweenFactorList);
        // run power for 1 factor contrasts      
        RealMatrix U = withinSubjectContrasts.getMainEffectContrast(factorD).getContrastMatrix();
        RealMatrix C = betweenSubjectContrasts.getMainEffectContrast(factorA).getContrastMatrix();
        RealMatrix thetaNull = MatrixUtils.getRealMatrixWithFilledValue(C.getRowDimension(),
                U.getColumnDimension(), 0);
        params.setWithinSubjectContrast(U);
        params.setBetweenSubjectContrast(new FixedRandomMatrix(C.getData(), null, true));
        params.setTheta(thetaNull);
        checker.checkPower(params);
        if (first) {
            matrixAltStringBuffer
                    .append("\\newpage\\textbf{Contrasts for the test of the A x D interaction}\n\n");
            appendMatrix("\\mathbf{C}'", C.transpose());
            appendMatrix("\\mathbf{U}", U);
        }
        // run power for 2 factor contrasts
        ArrayList<Factor> intFactors = new ArrayList<Factor>();
        intFactors.add(factorD);
        intFactors.add(factorE);
        U = withinSubjectContrasts.getInteractionContrast(intFactors).getContrastMatrix();
        intFactors.clear();
        intFactors.add(factorA);
        intFactors.add(factorB);
        C = betweenSubjectContrasts.getInteractionContrast(intFactors).getContrastMatrix();
        thetaNull = MatrixUtils.getRealMatrixWithFilledValue(C.getRowDimension(), U.getColumnDimension(), 0);
        params.setWithinSubjectContrast(U);
        params.setBetweenSubjectContrast(new FixedRandomMatrix(C.getData(), null, true));
        params.setTheta(thetaNull);
        checker.checkPower(params);
        if (first) {
            matrixAltStringBuffer
                    .append("\\newpage\\textbf{Contrasts for the test of the A x B x D x E interaction}\n\n");
            appendMatrix("\\mathbf{C}'", C.transpose());
            appendMatrix("\\mathbf{U}", U);
        }

        // run power for 3 factor contrasts
        intFactors.clear();
        intFactors.add(factorD);
        intFactors.add(factorE);
        intFactors.add(factorF);
        U = withinSubjectContrasts.getInteractionContrast(intFactors).getContrastMatrix();
        intFactors.clear();
        intFactors.add(factorA);
        intFactors.add(factorB);
        intFactors.add(factorC);
        C = betweenSubjectContrasts.getInteractionContrast(intFactors).getContrastMatrix();
        thetaNull = MatrixUtils.getRealMatrixWithFilledValue(C.getRowDimension(), U.getColumnDimension(), 0);
        params.setWithinSubjectContrast(U);
        params.setBetweenSubjectContrast(new FixedRandomMatrix(C.getData(), null, true));
        params.setTheta(thetaNull);
        checker.checkPower(params);
        if (first) {
            matrixAltStringBuffer.append(
                    "\\newpage\\textbf{Contrasts for the test of the A x B x C x D x E x F interaction}\n\n");
            appendMatrix("\\mathbf{C}'", C.transpose());
            appendMatrix("\\mathbf{U}", U);
            first = false;
        }
    }

    // output the results
    try {
        // we reset the tests to include all
        params.clearTestList();
        for (Test test : Test.values()) {
            params.addTest(test);
        }
        ValidationReportBuilder reportBuilder = new ValidationReportBuilder();
        reportBuilder.createValidationReportAsStdout(checker, TITLE, false);
        reportBuilder.createValidationReportAsLaTex(OUTPUT_FILE, TITLE, AUTHOR, STUDY_DESIGN_DESCRIPTION,
                params, matrixAltStringBuffer.toString(), checker);
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    assertTrue(checker.isSASDeviationBelowTolerance());
    checker.reset();
}

From source file:com.kimbrelk.privileges.Privileges.java

/**
 * Will process (add and removed) privileges appropriately as based on the PrivilegeHolder's allowances and denials 
 * @param privs An ArrayList of already allowed privileges
 * @param entity The PrivilegeHolder to process denials and allowances from
 *///w ww. ja  va 2  s.  com
private final void processPrivileges(ArrayList<String> privs, PrivilegeHolder entity) {
    if (entity == null || privs == null)
        return;

    // Denials
    ArrayList<String> denials = entity.getDenials();
    for (String denial : denials) {
        if (denial.equals("*")) {
            privs.clear();
            break;
        }

        privs.remove(denial);
    }

    // Allowances
    ArrayList<String> allowances = entity.getAllowances();
    for (String allowance : allowances) {
        if (allowance.equals("*")) {
            ArrayList<String> t = getRegisteredPrivileges();
            if (t != null) {
                privs.clear();
                privs.addAll(t);
                return;
            } else {
                onError(ERROR_ALLOWANCE_WILDCARD_WITHOUT_KNOWN_PRIVS);
            }
        } else {
            privs.add(allowance);
        }
    }
}

From source file:hd3gtv.mydmam.useraction.fileoperation.CopyMove.java

private static void dirListing(File source, ArrayList<File> list_to_copy) throws IOException {
    ArrayList<File> bucket = new ArrayList<File>();
    ArrayList<File> next_bucket = new ArrayList<File>();
    bucket.add(source);//from w  w  w .j  av a  2  s. c  o  m

    File bucket_item;
    File[] list_content;

    while (true) {
        for (int pos_b = 0; pos_b < bucket.size(); pos_b++) {
            bucket_item = bucket.get(pos_b).getCanonicalFile();

            if (FileUtils.isSymlink(bucket_item)) {
                continue;
            }

            if (list_to_copy.contains(bucket_item)) {
                continue;
            }
            if (bucket_item.isDirectory()) {
                list_content = bucket_item.listFiles();
                for (int pos_lc = 0; pos_lc < list_content.length; pos_lc++) {
                    next_bucket.add(list_content[pos_lc]);
                }
            }
            list_to_copy.add(bucket_item);
        }
        if (next_bucket.isEmpty()) {
            return;
        }
        bucket.clear();
        bucket.addAll(next_bucket);
        next_bucket.clear();
    }
}

From source file:UserInterface.Supplier.SalesOverviewJPanel.java

private void findTopProduct() {
    int max = 0;//from   ww w.ja va  2s .co  m
    int current = 0;
    String currentPName = "null";
    ArrayList<String> currentPList = new ArrayList<>();
    currentPList.add("null");
    DefaultTableModel dtm = (DefaultTableModel) performanceJTable.getModel();
    for (int i = 0; i < dtm.getRowCount(); i++) {
        current = (int) dtm.getValueAt(i, 1);
        if (max < current) {
            max = current;
            currentPName = (String) dtm.getValueAt(i, 0);
            currentPList.clear();
            currentPList.add(currentPName);
        } else if (max == current) {
            currentPName = (String) dtm.getValueAt(i, 0);
            currentPList.add(currentPName);
        }
    }
    topSellingJLabel.setText(currentPList.toString());

}

From source file:net.flutterflies.fwapaderp.game.TeamManager.java

/**
 * Converts a .csv spreadsheet template into a UHCTeam object
 *
 * @param teamsList Used purely as a reference to an earlier object, overwriting it
 * @return A list of all UHCTeams//from  w ww . j  a  v  a2s  .c om
 */
public ArrayList<UHCTeam> createTeamsFromCSV(ArrayList<UHCTeam> teamsList) {
    ArrayList<String[]> rows = new ArrayList<>();
    File teamsFile = new File(plugin.getDataFolder(), "teams.csv");
    CsvMapper mapper = new CsvMapper();

    //Clear any existing teams on the team list
    teamsList.clear();

    mapper.enable(CsvParser.Feature.WRAP_AS_ARRAY);

    //Try to load values from teams.csv
    try {
        MappingIterator<String[]> iterator = mapper.readerFor(String[].class).readValues(teamsFile);
        while (iterator.hasNext()) {
            rows.add(rows.size(), iterator.next());
        }
    } catch (IOException e) {
        plugin.getLogger().log(Level.SEVERE, "Could not find the file teams.csv! Please either supply"
                + "a teams.csv file or disable usePreMadeTeams in the plugin's config file.");
        System.exit(0);
    }

    //For each row in the csv file create a new team
    for (int i = 1; i < rows.size(); i++) {
        String[] team = rows.get(i);
        List<String> teamPlayerList = new ArrayList<>();
        for (int j = 2; j < team.length; j++) {
            if (!team[j].equals("")) {
                teamPlayerList.add(teamPlayerList.size(), team[j]);
            }
        }
        teamsList.add(teamsList.size(),
                new UHCTeam(team[0], team[1].toUpperCase().replace(' ', '_'), teamPlayerList));
    }

    //Write Teams to a yaml file
    for (int i = 0; i < teamList.size(); i++) {
        //Get the team
        UHCTeam team = teamList.get(i);

        //Write the team name
        plugin.getTeamConfig().set("teams.team" + (i + 1) + ".name", team.getTeamName(false));
        //Write the team's color
        plugin.getTeamConfig().set("teams.team" + (i + 1) + ".color", team.getTeamColor());
        //Write all the players in the team
        for (int j = 0; j < team.getTeamSize(); j++) {
            plugin.getTeamConfig().set("teams.team" + (i + 1) + ".players.player" + (j + 1),
                    team.getPlayers().get(j));
        }
    }
    plugin.saveTeamsConfig();

    return teamsList;
}

From source file:com.android.calendar.Event.java

private static void doComputePositions(ArrayList<Event> eventsList, long minimumDurationMillis,
        boolean doAlldayEvents) {
    final ArrayList<Event> activeList = new ArrayList<Event>();
    final ArrayList<Event> groupList = new ArrayList<Event>();

    if (minimumDurationMillis < 0) {
        minimumDurationMillis = 0;//  w w  w  .j  a  v  a  2 s .c o m
    }

    long colMask = 0;
    int maxCols = 0;
    for (Event event : eventsList) {
        // Process all-day events separately
        if (event.drawAsAllday() != doAlldayEvents)
            continue;

        if (!doAlldayEvents) {
            colMask = removeNonAlldayActiveEvents(event, activeList.iterator(), minimumDurationMillis, colMask);
        } else {
            colMask = removeAlldayActiveEvents(event, activeList.iterator(), colMask);
        }

        // If the active list is empty, then reset the max columns, clear
        // the column bit mask, and empty the groupList.
        if (activeList.isEmpty()) {
            for (Event ev : groupList) {
                ev.setMaxColumns(maxCols);
            }
            maxCols = 0;
            colMask = 0;
            groupList.clear();
        }

        // Find the first empty column.  Empty columns are represented by
        // zero bits in the column mask "colMask".
        int col = findFirstZeroBit(colMask);
        if (col == 64)
            col = 63;
        colMask |= (1L << col);
        event.setColumn(col);
        activeList.add(event);
        groupList.add(event);
        int len = activeList.size();
        if (maxCols < len)
            maxCols = len;
    }
    for (Event ev : groupList) {
        ev.setMaxColumns(maxCols);
    }
}

From source file:dbseer.gui.actions.ExplainChartAction.java

@Override
public void actionPerformed(ActionEvent actionEvent) {
    if (type == DBSeerConstants.EXPLAIN_SELECT_NORMAL_REGION) {
        Set<XYItemEntity> selectedItems = panel.getSelectedItems();
        ArrayList<Double> region = panel.getNormalRegion();
        region.clear();

        for (XYItemEntity item : selectedItems) {
            region.add(item.getDataset().getX(item.getSeriesIndex(), item.getItem()).doubleValue());
        }//from  ww w .  j a  v a2s  . c o  m
        ArrayList<Double> otherRegion = panel.getAnomalyRegion();
        otherRegion.removeAll(region);
        DBSeerXYLineAndShapeRenderer renderer = (DBSeerXYLineAndShapeRenderer) panel.getChart().getXYPlot()
                .getRenderer();
        renderer.setSelectedNormal(selectedItems);
        panel.clearRectangle();
        panel.setRefreshBuffer(true);
        panel.repaint();
    } else if (type == DBSeerConstants.EXPLAIN_APPEND_NORMAL_REGION) {
        DBSeerXYLineAndShapeRenderer renderer = (DBSeerXYLineAndShapeRenderer) panel.getChart().getXYPlot()
                .getRenderer();
        Set<XYItemEntity> previousItems = renderer.getSelectedNormal();
        Set<XYItemEntity> selectedItems = panel.getSelectedItems();
        ArrayList<Double> region = panel.getNormalRegion();

        for (XYItemEntity item : selectedItems) {
            region.add(item.getDataset().getX(item.getSeriesIndex(), item.getItem()).doubleValue());
        }
        ArrayList<Double> otherRegion = panel.getAnomalyRegion();
        otherRegion.removeAll(region);
        if (previousItems != null) {
            previousItems.addAll(selectedItems);
            renderer.setSelectedNormal(previousItems);
        } else {
            renderer.setSelectedNormal(selectedItems);
        }
        panel.clearRectangle();
        panel.setRefreshBuffer(true);
        panel.repaint();
    } else if (type == DBSeerConstants.EXPLAIN_SELECT_ANOMALY_REGION) {
        Set<XYItemEntity> selectedItems = panel.getSelectedItems();
        ArrayList<Double> region = panel.getAnomalyRegion();
        region.clear();

        for (XYItemEntity item : selectedItems) {
            region.add(item.getDataset().getX(item.getSeriesIndex(), item.getItem()).doubleValue());
        }
        ArrayList<Double> otherRegion = panel.getNormalRegion();
        otherRegion.removeAll(region);
        DBSeerXYLineAndShapeRenderer renderer = (DBSeerXYLineAndShapeRenderer) panel.getChart().getXYPlot()
                .getRenderer();
        renderer.setSelectedAnomaly(selectedItems);
        panel.clearRectangle();
        panel.setRefreshBuffer(true);
        panel.repaint();
    } else if (type == DBSeerConstants.EXPLAIN_APPEND_ANOMALY_REGION) {
        DBSeerXYLineAndShapeRenderer renderer = (DBSeerXYLineAndShapeRenderer) panel.getChart().getXYPlot()
                .getRenderer();
        Set<XYItemEntity> previousItems = renderer.getSelectedAnomaly();
        Set<XYItemEntity> selectedItems = panel.getSelectedItems();
        ArrayList<Double> region = panel.getAnomalyRegion();

        for (XYItemEntity item : selectedItems) {
            region.add(item.getDataset().getX(item.getSeriesIndex(), item.getItem()).doubleValue());
        }
        ArrayList<Double> otherRegion = panel.getNormalRegion();
        otherRegion.removeAll(region);
        if (previousItems != null) {
            previousItems.addAll(selectedItems);
            renderer.setSelectedAnomaly(previousItems);
        } else {
            renderer.setSelectedAnomaly(selectedItems);
        }
        panel.clearRectangle();
        panel.setRefreshBuffer(true);
        panel.repaint();
    } else if (type == DBSeerConstants.EXPLAIN_CLEAR_REGION) {
        ArrayList<Double> region = panel.getNormalRegion();
        region.clear();
        region = panel.getAnomalyRegion();
        region.clear();

        DBSeerXYLineAndShapeRenderer renderer = (DBSeerXYLineAndShapeRenderer) panel.getChart().getXYPlot()
                .getRenderer();
        renderer.clearAnomaly();
        renderer.clearNormal();

        DefaultListModel explanationListModel = panel.getControlPanel().getExplanationListModel();
        explanationListModel.clear();
        DefaultListModel predicateListModel = panel.getControlPanel().getPredicateListModel();
        predicateListModel.clear();

        panel.clearRectangle();
        panel.setRefreshBuffer(true);
        panel.repaint();

    } else if (type == DBSeerConstants.EXPLAIN_EXPLAIN) {
        explain();
    } else if (type == DBSeerConstants.EXPLAIN_TOGGLE_PREDICATES) {
        togglePredicates();
    } else if (type == DBSeerConstants.EXPLAIN_SAVE_PREDICATES) {
        savePredicates();
    } else if (type == DBSeerConstants.EXPLAIN_UPDATE_EXPLANATIONS) {
        updateExplanations();
    }
}

From source file:com.nineash.hutsync.client.NetworkUtilities.java

/**
 * Perform 2-way sync with the server-side contacts. We send a request that
 * includes all the locally-dirty contacts so that the server can process
 * those changes, and we receive (and return) a list of contacts that were
 * updated on the server-side that need to be updated locally.
 *
 * @param account The account being synced
 * @param authtoken The authtoken stored in the AccountManager for this
 *            account//from   w  w  w .java  2 s  . com
 * @param serverSyncState A token returned from the server on the last sync
 * @param dirtyContacts A list of the contacts to send to the server
 * @return A list of contacts that we need to update locally
 */
public static void syncCalendar(Context context, Account account, String authtoken, long serverSyncState)
        throws JSONException, ParseException, IOException, AuthenticationException {
    ArrayList<SerializableCookie> myCookies;
    CookieStore cookieStore = new BasicCookieStore();
    DefaultHttpClient hClient = getHttpClient(context);
    mContentResolver = context.getContentResolver();
    final String[] weeknames = { "rota_this_week", "rota_next_week" };

    long calendar_id = getCalendar(account);
    if (calendar_id == -1) {
        Log.e("CalendarSyncAdapter", "Unable to create HutSync event calendar");
        return;
    }

    try {
        myCookies = (ArrayList<SerializableCookie>) fromString(authtoken);
    } catch (final IOException e) {
        Log.e(TAG, "IOException when expanding authtoken", e);
        return;
    } catch (final ClassNotFoundException e) {
        Log.e(TAG, "ClassNotFoundException when expanding authtoken", e);
        return;
    }

    for (SerializableCookie cur_cookie : myCookies) {
        cookieStore.addCookie(cur_cookie.getCookie());
    }

    hClient.setCookieStore(cookieStore);
    Log.i(TAG, "Syncing to: " + SYNC_CONTACTS_URI);
    HttpGet httpget = new HttpGet(SYNC_CONTACTS_URI);
    final HttpResponse resp = hClient.execute(httpget);
    final String response = EntityUtils.toString(resp.getEntity());
    HashMap<Long, SyncEntry> localEvents = new HashMap<Long, SyncEntry>();
    ArrayList<Event> events = new ArrayList<Event>();
    Pattern p = Pattern.compile("background-color:(#[[a-f][A-F][0-9]]{6})");
    Pattern ps = Pattern
            .compile(".calendar-key span.(\\S+) \\{ background-color:(#[[a-f][A-F][0-9]]{6}); color:#fff; \\}");

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        //check we are still logged in
        //if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        //    Log.e(TAG, "Authentication exception in sending dirty contacts");
        //    throw new AuthenticationException();
        //}

        //if we are logged in
        Map<String, String> shift_types = new HashMap<String, String>();
        int length = weeknames.length;
        Document doc = Jsoup.parse(response);
        String full_name = doc.select("a[href*=" + account.name + "/profile]").first().text();

        AccountManager mAccountManager = AccountManager.get(context);
        Account[] the_accounts = mAccountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
        boolean multiple_accounts = (the_accounts.length > 1);

        Elements the_styles = doc.select("style");
        for (Element the_style : the_styles) {
            String st_txt = the_style.html();
            Matcher ms = ps.matcher(st_txt);
            while (ms.find()) { // Find each match in turn; String can't do this.
                String cname = ms.group(1); // Access a submatch group; String can't do this.
                String ccol = ms.group(2);
                String rname = doc.select("span." + cname).first().text();
                Log.i(TAG, "LOOK: " + cname + ", " + ccol + ", " + rname);
                shift_types.put(ccol, rname);
            }
        }

        for (int w = 0; w < weeknames.length; w++) {

            Elements the_dates = doc.select("div.homepage div.accord-content table[id=" + weeknames[w]
                    + "] tr.heading th:not(.skipStyles)");
            //for (Element hidden : the_dates) { //0 is Mon, 6 is Sun
            Element the_date = the_dates.first(); //figure out the year for the Monday.
            String str_v = the_date.text();
            String[] str_sub = str_v.split(" ");
            str_sub[1] = str_sub[1].trim();
            String[] date_split = str_sub[1].split("/");
            Calendar c = Calendar.getInstance();
            int this_month = c.get(Calendar.MONTH) + 1;
            int monday_month = Integer.parseInt(date_split[1]);
            int this_year = c.get(Calendar.YEAR);
            int monday_year = this_year;
            if (this_month > monday_month) {
                monday_year++;
            } else if (this_month < monday_month) {
                monday_year--;
            }

            SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
            Date date = new Date();
            if (str_v != null && !str_v.isEmpty()) {
                String this_date = str_sub[1] + "/" + monday_year; //we need to figure out the year - sometimes its next year

                try {
                    date = format.parse(this_date);
                } catch (Exception e) {
                    // TODO Auto-generated catch block  
                    e.printStackTrace();
                }
                Log.i(TAG, "Dates: " + this_date + " - " + date);
            }
            //}

            for (int i = 1; i < 8; ++i) { //1 is monday, 7 is sunday
                Elements hiddens = doc.select("div.homepage div.accord-content table[id=" + weeknames[w]
                        + "] td:eq(" + Integer.toString(i) + "):not(.skipStyles) div.timeElem");
                int add_days = i - 1;
                for (Element hidden : hiddens) {
                    String str = hidden.text();
                    if (str != null && !str.isEmpty()) {
                        String style = hidden.attr("style");
                        String bg_col = "";
                        Matcher m = p.matcher(style);
                        if (m.find()) {
                            bg_col = m.group(1); // Access a submatch group; String can't do this.
                        }

                        Log.i(TAG, "Time: " + str + "(" + bg_col + ")");
                        String ev_description = ""; //Location too?
                        if (multiple_accounts)
                            ev_description += full_name + "\n\n";
                        String[] times = str.split(" - ");
                        String[] start_time = times[0].split(":");
                        String[] end_time = times[1].split(":");
                        int add_start_hours = Integer.parseInt(start_time[0]);
                        int add_start_minutes = Integer.parseInt(start_time[1]);
                        int add_finish_hours = Integer.parseInt(end_time[0]);
                        int add_finish_minutes = Integer.parseInt(end_time[1]);
                        String ev_shiftType = "";
                        if (bg_col != null && !bg_col.isEmpty()) {
                            ev_shiftType = (String) shift_types.get(bg_col);
                        } else {
                            ev_shiftType = "Other";
                        }
                        String ev_title = ev_shiftType + " Shift";

                        c.setTime(date);
                        c.add(Calendar.DATE, add_days);
                        c.add(Calendar.HOUR_OF_DAY, add_start_hours);
                        c.add(Calendar.MINUTE, add_start_minutes);
                        Date startDate = c.getTime();
                        long ev_id = startDate.getTime();

                        c.setTime(date);
                        c.add(Calendar.DATE, add_days);
                        if (add_finish_hours < add_start_hours) { //shift rolls to next day
                            c.add(Calendar.HOUR_OF_DAY, 24);
                            ev_description += "Shift finishes at " + times[1] + " on the next day\n\n";
                        } else {
                            c.add(Calendar.HOUR_OF_DAY, add_finish_hours);
                            c.add(Calendar.MINUTE, add_finish_minutes);
                        }
                        Date endDate = c.getTime();

                        Event ev = new Event(ev_id, ev_title, startDate, endDate, ev_description, ev_shiftType);
                        events.add(ev);
                        Log.i(TAG, "Event: " + ev);
                    }
                }
            }
        }

        //next merge adjacent shifts
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        Event prev_event = null;
        for (Iterator<Event> it = events.iterator(); it.hasNext();) {
            Event cur_event = it.next();
            if (prev_event != null) {
                if (prev_event.getEndDate().compareTo(cur_event.getStartDate()) == 0) {
                    prev_event.setDescription(prev_event.getDescription() + "Merged consecutive shifts:\n"
                            + timeFormat.format(prev_event.getStartDate()) + " to "
                            + timeFormat.format(prev_event.getEndDate()) + " (" + prev_event.getShiftType()
                            + ")\n" + timeFormat.format(cur_event.getStartDate()) + " to "
                            + timeFormat.format(cur_event.getEndDate()) + " (" + cur_event.getShiftType()
                            + ")\n\n");
                    prev_event.setEndDate(cur_event.getEndDate()); //TODO: only merge if other + FOH/BOH, note times in new description
                    it.remove();
                }
            }
            prev_event = cur_event;
        }

        //next, load local events
        Cursor c1 = mContentResolver.query(
                Events.CONTENT_URI.buildUpon().appendQueryParameter(Events.ACCOUNT_NAME, account.name)
                        .appendQueryParameter(Events.ACCOUNT_TYPE, account.type).build(),
                new String[] { Events._ID, Events._SYNC_ID }, Events.CALENDAR_ID + "=?",
                new String[] { String.valueOf(calendar_id) }, null);
        while (c1 != null && c1.moveToNext()) {
            //if(is_full_sync) {
            //   deleteEvent(context, account, c1.getLong(0));
            //} else {
            SyncEntry entry = new SyncEntry();
            entry.raw_id = c1.getLong(0);
            localEvents.put(c1.getLong(1), entry);
            //}
        }
        c1.close();
        try {
            ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
            for (Event event : events) {

                if (localEvents.containsKey(Long.valueOf(event.getId()))) {
                    SyncEntry entry = localEvents.get(Long.valueOf(event.getId()));
                    operationList.add(updateEvent(calendar_id, account, event, entry.raw_id));
                } else {
                    operationList.add(updateEvent(calendar_id, account, event, -1));
                }

                if (operationList.size() >= 50) {
                    try {
                        mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    operationList.clear();
                }
            }

            if (operationList.size() > 0) {
                try {
                    mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return;
        }

    } else {
        Log.e(TAG, "Server error in sending dirty contacts: " + resp.getStatusLine());
        throw new IOException();
    }
}