Example usage for java.util Set remove

List of usage examples for java.util Set remove

Introduction

In this page you can find the example usage for java.util Set remove.

Prototype

boolean remove(Object o);

Source Link

Document

Removes the specified element from this set if it is present (optional operation).

Usage

From source file:com.microsoft.tfs.client.common.repository.cache.pendingchange.PendingChangeCollection.java

private PendingChange removeInternal(final PendingChange changeToRemove) {
    Check.notNull(changeToRemove, "changeToRemove"); //$NON-NLS-1$
    Check.notNull(changeToRemove.getServerItem(), "changeToRemove.serverItem"); //$NON-NLS-1$

    String serverPath = ServerPath.canonicalize(changeToRemove.getServerItem());
    PendingChange removedChange = changesByServerPath.remove(ServerPath.canonicalize(serverPath));

    /*/*from www  . j a  v a  2 s . c  om*/
     * See if this is a rename pending change - we may need to remove the
     * source item
     */
    if (removedChange == null && changeToRemove.getSourceServerItem() != null) {
        serverPath = ServerPath.canonicalize(changeToRemove.getSourceServerItem());
        removedChange = changesByServerPath.remove(ServerPath.canonicalize(serverPath));
    }

    if (removedChange == null && changeToRemove.getSourceLocalItem() != null) {
        serverPath = workspace.getMappedServerPath(changeToRemove.getSourceLocalItem());

        if (serverPath != null) {
            serverPath = ServerPath.canonicalize(serverPath);
            removedChange = changesByServerPath.remove(serverPath);
        }
    }

    if (removedChange == null) {
        return null;
    }

    /* Update the server path hierarchy */
    final String[] serverHierarchy = ServerPath.getHierarchy(serverPath);
    for (int i = 0; i < serverHierarchy.length; i++) {
        final Set<PendingChange> changesForPath = changesByParentServerPath.get(serverHierarchy[i]);
        changesForPath.remove(removedChange);

        if (changesForPath.size() == 0) {
            changesByParentServerPath.remove(serverHierarchy[i]);
        }
    }

    if (removedChange.getLocalItem() != null) {
        final String localPath = LocalPath.canonicalize(removedChange.getLocalItem());
        final String[] localHierarchy = LocalPath.getHierarchy(localPath);

        changesByLocalPath.remove(localPath);

        for (int i = 0; i < localHierarchy.length; i++) {
            final Set<PendingChange> changesForPath = changesByParentLocalPath.get(localHierarchy[i]);
            changesForPath.remove(removedChange);

            if (changesForPath.size() == 0) {
                changesByParentLocalPath.remove(localHierarchy[i]);
            }
        }
    }

    return removedChange;
}

From source file:fungus.MycoGraph.java

public Set<Set<MycoNode>> findConnectedComponents() {
    Set<Set<MycoNode>> components = new HashSet<Set<MycoNode>>();
    Set<MycoNode> unseen = new HashSet<MycoNode>(this.getVertices());
    Queue<MycoNode> queue = new LinkedList<MycoNode>();

    Set<MycoNode> workingComponent = null;
    MycoNode current;//  w ww .  ja va  2  s.  com
    while ((!unseen.isEmpty()) || (!queue.isEmpty())) {
        if (queue.isEmpty()) {
            // Queue an arbitary unvisited node
            MycoNode n = unseen.iterator().next();
            queue.offer(n);
            unseen.remove(n);
            // Start new component
            workingComponent = new HashSet<MycoNode>();
            components.add(workingComponent);
        }
        current = queue.remove();
        workingComponent.add(current);
        for (MycoNode neighbor : current.getHyphaLink().getNeighbors()) {
            if (unseen.contains(neighbor)) {
                queue.offer(neighbor);
                unseen.remove(neighbor);
            }
        }
    }
    return components;
}

From source file:com.thoughtworks.go.server.service.AdminsConfigService.java

public BulkUpdateAdminsResult bulkUpdate(Username currentUser, List<String> usersToAdd,
        List<String> usersToRemove, List<String> rolesToAdd, List<String> rolesToRemove, String md5) {
    Set<Admin> existingAdmins = new HashSet<>(systemAdmins());
    BulkUpdateAdminsResult result = validateUsersAndRolesForBulkUpdate(usersToRemove, rolesToRemove,
            existingAdmins);/*from  w w w  .j a v  a2 s . c  o m*/
    if (!result.isSuccessful()) {
        return result;
    }

    usersToAdd.forEach(user -> existingAdmins.add(new AdminUser(user)));
    rolesToAdd.forEach(role -> existingAdmins.add(new AdminRole(role)));
    usersToRemove.forEach(user -> existingAdmins.remove(new AdminUser(new CaseInsensitiveString(user))));
    rolesToRemove.forEach(role -> existingAdmins.remove(new AdminRole(new CaseInsensitiveString(role))));
    AdminsConfigUpdateCommand command = new AdminsConfigUpdateCommand(goConfigService,
            new AdminsConfig(existingAdmins), currentUser, result, entityHashingService, md5);
    updateConfig(currentUser, result, command);
    result.setAdminsConfig(command.getEntity());
    return result;
}

From source file:com.idega.slide.authentication.AuthenticationBusinessBean.java

/**
 * @param loginName/* w  ww. j  a v a 2  s  .co m*/
 * @param roleNamesForUser
 * @param loginNameOfAllLoggedOnUsers
 *            Set of all users that are logged on, other users are removed from roles. If the
 *            set is null no users are removed from roles.
 * @throws IOException
 * @throws RemoteException
 * @throws HttpException
 */
public void updateRoleMembershipForUser(String userLoginName, Set roleNamesForUser,
        Set loginNamesOfAllLoggedOnUsers) throws HttpException, RemoteException, IOException {

    if (userLoginName != null && userLoginName.length() > 0 && !userLoginName.equals(SLIDE_DEFAULT_ROOT_USER)) {
        IWSlideService service = getSlideServiceInstance();
        UsernamePasswordCredentials rCredentials = service.getRootUserCredentials();

        Set newRoles = new HashSet(roleNamesForUser);
        Enumeration e = getAllRoles(rCredentials).getResources();
        String userURI = getUserURI(userLoginName);
        while (e.hasMoreElements()) {
            WebdavResource role = (WebdavResource) e.nextElement();
            newRoles.remove(role.getDisplayName());
            updateRoleMembershipForUser(role, userURI, roleNamesForUser, loginNamesOfAllLoggedOnUsers);
        }

        // Add Roles that don't exist
        for (Iterator iter = newRoles.iterator(); iter.hasNext();) {
            String sRole = (String) iter.next();

            if (!service.getExistence(getRolePath(sRole))) {
                WebdavResource newRole = new WebdavResource(
                        service.getWebdavServerURL(rCredentials, getRolePath(sRole)), WebdavResource.NOACTION,
                        0);
                newRole.mkcolMethod();
                updateRoleMembershipForUser(newRole, userURI, roleNamesForUser, loginNamesOfAllLoggedOnUsers);
                newRole.close();
            }
        }
    }
}

From source file:gr.cti.android.experimentation.controller.ui.RestRankingController.java

@ResponseBody
@RequestMapping(value = { "/results/{experimentId}/csv" }, method = RequestMethod.GET, produces = "text/csv")
public String getResultsCsv(@PathVariable("experimentId") final int experimentId) {
    final Set<Result> results = resultRepository.findByExperimentId(experimentId);
    final StringBuilder resResponse = new StringBuilder();
    final Set<String> headers = new HashSet<>();
    for (final Result result : results) {
        try {/* ww  w.  j  a  v a 2  s.c  o m*/
            final HashMap<String, Object> dataMap = new ObjectMapper().readValue(result.getMessage(),
                    new HashMap<String, Object>().getClass());
            headers.addAll(dataMap.keySet());
        } catch (IOException ignore) {
        }
    }
    headers.remove(LONGITUDE);
    headers.remove(LATITUDE);

    resResponse.append("timestamp,longitude,latitude,");
    resResponse.append(String.join(",", headers)).append("\n");
    for (final Result result : results) {
        final List<String> values = new ArrayList<>();
        values.add(String.valueOf(result.getTimestamp()));
        try {
            final HashMap<String, Object> dataMap = new ObjectMapper().readValue(result.getMessage(),
                    new HashMap<String, Object>().getClass());
            values.add(String.valueOf(dataMap.get(LONGITUDE)));
            values.add(String.valueOf(dataMap.get(LATITUDE)));
            for (final String key : headers) {
                if (dataMap.containsKey(key)) {
                    values.add(String.valueOf(dataMap.get(key)));
                } else {
                    values.add(null);
                }
            }
            resResponse.append(String.join(",", values)).append("\n");
        } catch (IOException e) {
            LOGGER.warn(e, e);
        }
    }
    return resResponse.toString();
}

From source file:com.fluidops.iwb.widget.admin.WikiManagementWidget.java

protected static FButton createSelectPresetButton(final WikiStorageBulkServiceImpl wsApi,
        final WikiPageSelectionTable wpTable) {

    return new FButton("b" + Rand.getIncrementalFluidUUID(), "Select preset") {
        @Override/*from   w w  w  .j  a v  a  2  s  .c  om*/
        public void onClick() {
            final FTextArea input = new FTextArea("inp");
            input.cols = 35;
            input.rows = 10;

            StringBuilder currentPreset = new StringBuilder();
            for (WikiPageMeta w : wpTable.getSelectedObjects()) {
                currentPreset.append(w.getPageUri().stringValue()).append("\n");
            }
            input.value = currentPreset.toString();
            FPopupWindow p = getPage().getPopupWindowInstance(
                    "Please configure your preset by adding one valid wiki page URI per line:");

            p.add(input);
            p.addButton("Ok", new Runnable() {
                @Override
                public void run() {
                    Set<String> selectedPreset = Sets.newHashSet(input.getText().split("\r?\n"));
                    List<WikiPageMeta> wm = wsApi
                            .getAllWikipages(new WikiStorageBulkServiceImpl.StringSetFilter(selectedPreset));

                    // retrieve table model to select all
                    FSelectableTableModel<WikiPageMeta> tm = wpTable.getModelSafe();
                    tm.setSelection(wm);

                    wpTable.setSortColumn(0, FTable.SORT_DESCENDING);
                    wpTable.populateView();

                    // the preset contains some invalid url, inform user
                    List<WikiPageMeta> selectedAfter = wpTable.getSelectedObjects();
                    if (selectedPreset.size() != selectedAfter.size()) {
                        for (WikiPageMeta w : selectedAfter)
                            selectedPreset.remove(w.getPageUri().stringValue());
                        throw new IllegalStateException(
                                "Preset contains URIs that are not known to the system: "
                                        + StringEscapeUtils.escapeHtml(selectedPreset.toString())
                                        + ". Please check your preset.");
                    }
                }
            });
            p.addCloseButton("Cancel");
            p.populateAndShow();

        }
    };
}

From source file:com.netflix.genie.server.services.impl.jpa.ClusterConfigServiceJPAImpl.java

/**
 * {@inheritDoc}//from   www .j av a 2 s. co m
 */
@Override
public Cluster deleteCluster(@NotBlank(message = "No id entered unable to delete.") final String id)
        throws GenieException {
    LOG.debug("Called");
    final Cluster cluster = this.clusterRepo.findOne(id);
    if (cluster == null) {
        throw new GenieNotFoundException("No cluster with id " + id + " exists to delete.");
    }
    final List<Command> commands = cluster.getCommands();
    if (commands != null) {
        for (final Command command : commands) {
            final Set<Cluster> clusters = command.getClusters();
            if (clusters != null) {
                clusters.remove(cluster);
            }
        }
    }
    this.clusterRepo.delete(cluster);
    return cluster;
}

From source file:eu.trentorise.smartcampus.permissionprovider.manager.ClientDetailsManager.java

/**
 * Fill in the DB object with the properties of {@link ClientAppBasic} instance. In case of problem, return null.
 * @param client/*from   w ww . j  av a 2  s. c o m*/
 * @param data
 * @return
 * @throws Exception 
 */
public ClientDetailsEntity convertFromClientApp(ClientDetailsEntity client, ClientAppBasic data) {
    try {
        ClientAppInfo info = null;
        if (client.getAdditionalInformation() == null) {
            info = new ClientAppInfo();
        } else {
            info = ClientAppInfo.convert(client.getAdditionalInformation());
        }
        info.setName(data.getName());
        info.setNativeAppsAccess(data.isNativeAppsAccess());
        info.setNativeAppSignatures(Utils.normalizeValues(data.getNativeAppSignatures()));
        Set<String> types = new HashSet<String>(client.getAuthorizedGrantTypes());
        if (data.isBrowserAccess()) {
            types.add(GT_IMPLICIT);
        } else {
            types.remove(GT_IMPLICIT);
        }
        if (data.isServerSideAccess() || data.isNativeAppsAccess()) {
            types.add(GT_AUTHORIZATION_CODE);
            types.add(GT_REFRESH_TOKEN);
        } else {
            types.remove(GT_AUTHORIZATION_CODE);
            types.remove(GT_REFRESH_TOKEN);
        }
        client.setAuthorizedGrantTypes(StringUtils.collectionToCommaDelimitedString(types));
        if (info.getIdentityProviders() == null) {
            info.setIdentityProviders(new HashMap<String, Integer>());
        }

        for (String key : attributesAdapter.getAuthorityUrls().keySet()) {
            if (data.getIdentityProviders().get(key)) {
                Integer value = info.getIdentityProviders().get(key);
                AuthorityMapping a = attributesAdapter.getAuthority(key);
                if (value == null || value == ClientAppInfo.UNKNOWN) {
                    info.getIdentityProviders().put(key,
                            a.isPublic() ? ClientAppInfo.APPROVED : ClientAppInfo.REQUESTED);
                }
            } else {
                info.getIdentityProviders().remove(key);
            }
        }

        client.setAdditionalInformation(info.toJson());
        client.setRedirectUri(Utils.normalizeValues(data.getRedirectUris()));
    } catch (Exception e) {
        log.error("failed to convert an object: " + e.getMessage(), e);
        return null;
    }
    return client;
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.CoAuthorshipQueryRunner.java

private void removeLowQualityNodesAndEdges(Set<Collaborator> nodes, Map<String, Activity> biboDocumentURLToVO,
        Map<String, Set<Collaborator>> biboDocumentURLToCoAuthors, Set<Collaboration> edges) {

    Set<Collaborator> nodesToBeRemoved = new HashSet<Collaborator>();
    for (Map.Entry<String, Set<Collaborator>> currentBiboDocumentEntry : biboDocumentURLToCoAuthors
            .entrySet()) {/*  ww w.  j av  a2 s . c  om*/

        if (currentBiboDocumentEntry.getValue().size() > MAX_AUTHORS_PER_PAPER_ALLOWED) {

            Activity currentBiboDocument = biboDocumentURLToVO.get(currentBiboDocumentEntry.getKey());

            Set<Collaboration> edgesToBeRemoved = new HashSet<Collaboration>();

            for (Collaboration currentEdge : edges) {
                Set<Activity> currentCollaboratorDocuments = currentEdge.getCollaborationActivities();

                if (currentCollaboratorDocuments.contains(currentBiboDocument)) {
                    currentCollaboratorDocuments.remove(currentBiboDocument);
                    if (currentCollaboratorDocuments.isEmpty()) {
                        edgesToBeRemoved.add(currentEdge);
                    }
                }
            }

            edges.removeAll(edgesToBeRemoved);

            for (Collaborator currentCoAuthor : currentBiboDocumentEntry.getValue()) {
                currentCoAuthor.getCollaboratorActivities().remove(currentBiboDocument);
                if (currentCoAuthor.getCollaboratorActivities().isEmpty()) {
                    nodesToBeRemoved.add(currentCoAuthor);
                }
            }
        }
    }
    nodes.removeAll(nodesToBeRemoved);
}

From source file:com.github.bfour.fpliteraturecollector.service.DefaultLiteratureService.java

@Override
public synchronized void downloadFullTexts(Literature literature) throws ServiceException {

    if (literature.getFulltextURLs() == null)
        return;/*from w w  w . j a  v a 2  s  .  c om*/

    outerloop: for (Link fullTextURL : literature.getFulltextURLs()) {

        if (literature.getFulltextFilePaths() != null)
            // check if already exists
            for (Link alreadyExistingFiles : literature.getFulltextFilePaths()) {
                if (alreadyExistingFiles.getReference().equals(fullTextURL.getUri().toString())) {
                    // check if file actually exists
                    File file = new File(alreadyExistingFiles.getUri());
                    if (file.exists())
                        continue outerloop;
                    else {
                        Set<Link> newFullTextPaths = literature.getFulltextFilePaths();
                        newFullTextPaths.remove(alreadyExistingFiles);
                        update(literature, new LiteratureBuilder(literature)
                                .setFulltextFilePaths(newFullTextPaths).getObject());
                    }
                }
            }

        try {
            Link fullTextFileLink = fileServ.persist(fullTextURL.getUri().toURL(), literature);
            Set<Link> newFileLinks = new HashSet<>();
            if (literature.getFulltextFilePaths() != null)
                newFileLinks.addAll(literature.getFulltextFilePaths());
            newFileLinks.add(fullTextFileLink);
            update(literature,
                    new LiteratureBuilder(literature).setFulltextFilePaths(newFileLinks).getObject());
        } catch (IOException | IllegalArgumentException e) {
            // TODO Auto-generated catch block
            System.err.println(fullTextURL);
            e.printStackTrace();
            throw new ServiceException(e);
        }

    }

}