Example usage for java.util List retainAll

List of usage examples for java.util List retainAll

Introduction

In this page you can find the example usage for java.util List retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this list that are contained in the specified collection (optional operation).

Usage

From source file:com.threewks.thundr.route.cors.CorsFilter.java

protected List<String> determineAllowedHeaders(List<String> headers, HttpServletRequest req) {
    List<String> requestedHeadersCombined = lowerCaseAll
            .from(Header.getHeaders(Header.AccessControlRequestHeaders, req));
    List<String> requestedHeaders = new ArrayList<String>();
    for (String combined : requestedHeadersCombined) {
        String[] uncombined = StringUtils.split(combined, ", ");
        requestedHeaders.addAll(Arrays.asList(uncombined));
    }// www.j a v a 2 s.  co  m
    if (headers != null) {
        requestedHeaders.retainAll(headers);
    }
    return requestedHeaders;
}

From source file:opendial.inference.exact.VariableElimination.java

/**
 * Reduces the Bayesian network by retaining only a subset of variables and
 * marginalising out the rest./*from   w  w w .  j a  v  a2s . com*/
 * 
 * @param query the query containing the network to reduce, the variables 
 *        to retain, and possible evidence.
 * @return the probability distributions for the retained variables
 * @throws DialException if the reduction operation failed
 */
@Override
public BNetwork reduce(Query.ReduceQuery query) throws DialException {

    BNetwork network = query.getNetwork();
    Collection<String> queryVars = query.getQueryVars();

    // create the query factor
    DoubleFactor queryFactor = createQueryFactor(query);

    BNetwork reduced = new BNetwork();

    List<String> sortedNodesIds = network.getSortedNodesIds();
    sortedNodesIds.retainAll(queryVars);
    Collections.reverse(sortedNodesIds);

    for (String var : sortedNodesIds) {

        Set<String> directAncestors = network.getNode(var).getAncestorsIds(queryVars);
        // create the factor and distribution for the variable
        DoubleFactor factor = getRelevantFactor(queryFactor, var, directAncestors);
        ProbDistribution distrib = createProbDistribution(factor, var);

        // create the new node
        ChanceNode cn = new ChanceNode(var);
        cn.setDistrib(distrib);
        for (String ancestor : directAncestors) {
            cn.addInputNode(reduced.getNode(ancestor));
        }
        reduced.addNode(cn);
    }

    return reduced;
}

From source file:opennlp.tools.jsmlearning.FeatureSpaceCoverageProcessor.java

public Map<String, String> computeIntersection(Map<String, String> rule1, Map<String, String> rule2) {
    Map<String, String> attr_value = new HashMap<String, String>();
    for (String attr : attributes) {
        int attrIndex = getIdForAttributeName(attr);
        String v1 = rule1.get(attr);
        String v2 = rule2.get(attr);
        if (v1 == null || v2 == null)
            continue;
        String valArr1Str = StringUtils.substringBetween(v1, "{", "}");
        String valArr2Str = StringUtils.substringBetween(v2, "{", "}");
        if (valArr1Str == null || valArr2Str == null) { // we assume single value, not an array of values
            if (v1.equals(v2)) {
                attr_value.put(attr, v1);
            }/*from   ww  w . ja va  2  s .c  o m*/
        } else {
            valArr1Str = valArr1Str.replaceAll(", ", ",");
            valArr2Str = valArr2Str.replaceAll(", ", ",");
            String[] valArr1 = valArr1Str.split(",");
            String[] valArr2 = valArr2Str.split(",");
            List<String> valList1 = new ArrayList<String>(Arrays.asList(valArr1));
            List<String> valList2 = new ArrayList<String>(Arrays.asList(valArr2));
            valList1.retainAll(valList2);
            if (!valList1.isEmpty()) {
                v1 = "{" + valList1.toString().replace("[", " ").replace("]", " ").trim() + "}";
                attr_value.put(attr, v1);
            }

        }
    }
    return attr_value;
}

From source file:opennlp.tools.jsmlearning.FeatureSpaceCoverageProcessor.java

public Map<String, String> computeIntersection(String[] line1, String[] line2) {

    Map<String, String> attr_value = new HashMap<String, String>();
    for (String attr : attributes) {
        int attrIndex = getIdForAttributeName(attr);
        String v1 = line1[attrIndex].toLowerCase().replace("\"", "").replace(",  ", ", ").replace(", ", ",");
        ;/*  w  w  w. j av  a 2 s .c  o m*/
        String v2 = line2[attrIndex].toLowerCase().replace("\"", "").replace(",  ", ", ").replace(", ", ",");
        ;
        String valArr1Str = StringUtils.substringBetween(v1, "{", "}");
        String valArr2Str = StringUtils.substringBetween(v2, "{", "}");
        if (valArr1Str == null || valArr2Str == null) { // we assume single value, not an array of values
            if (v1.equals(v2)) {
                attr_value.put(attr, v1);
            }
        } else {
            valArr1Str = valArr1Str.replaceAll(", ", ",");
            valArr2Str = valArr2Str.replaceAll(", ", ",");
            String[] valArr1 = valArr1Str.split(",");
            String[] valArr2 = valArr2Str.split(",");
            List<String> valList1 = new ArrayList<String>(Arrays.asList(valArr1));
            List<String> valList2 = new ArrayList<String>(Arrays.asList(valArr2));
            valList1.retainAll(valList2);
            /* verification of coverage
            valList1.retainAll(valList2);
                    
            List<String> vl1 = new ArrayList<String>(Arrays.asList(valArr1));
            valList1.retainAll(vl1); */

            if (!valList1.isEmpty()) {
                v1 = "{" + valList1.toString().replace("[", " ").replace("]", " ").trim() + "}";
                attr_value.put(attr, v1);
            }

        }
    }
    return attr_value;
}

From source file:org.obiba.mica.search.JoinQueryExecutor.java

private List<String> joinStudyIds(List<String> studyIds, List<String> joinedStudyIds) {
    if (studyIds != null) {
        joinedStudyIds.retainAll(studyIds);
    }/*w  w  w.  java  2s.c  o  m*/

    return joinedStudyIds;
}

From source file:com.cloudbees.plugins.deployer.engines.Engine.java

public boolean perform() throws Throwable {
    final List<DeploySourceOrigin> validOrigins = new ArrayList<DeploySourceOrigin>(
            DeploySourceOrigin.allInPreferenceOrder());
    validOrigins.retainAll(sources);

    logDetails();/*w  w  w .j  a v  a  2s.  com*/
    for (T target : set.getTargets()) {
        log("Deploying " + target.getDisplayName());
        boolean found = false;
        DeployEvent event = createEvent(target);
        try {
            DeploySource source = target.getArtifact();
            if (source == null) {
                throw new DeploySourceNotFoundException(null,
                        "Undefined source for " + target.getDisplayName());
            }
            DeployedApplicationLocation location = null;
            findSource: for (DeploySourceOrigin origin : validOrigins) {
                if (source.getDescriptor().isSupported(origin)) {
                    switch (origin) {
                    case WORKSPACE: {
                        FilePath workspace = build.getWorkspace();
                        if (workspace != null) {
                            FilePath applicationFile = source.getApplicationFile(workspace);
                            if (applicationFile != null) {
                                found = true;
                                validate(applicationFile);
                                log("  Resolved from workspace as " + applicationFile);
                                location = process(applicationFile, target);
                                DeployListener.notifySuccess(set, target, event);
                                break findSource;
                            }
                        }
                    }
                        break;
                    case RUN: {
                        File applicationFile = source.getApplicationFile(build);
                        if (applicationFile != null) {
                            found = true;
                            validate(applicationFile);
                            log("  Resolved from archived artifacts as " + applicationFile);
                            location = process(applicationFile, target);
                            DeployListener.notifySuccess(set, target, event);
                            break findSource;
                        }
                    }
                        break;
                    default:
                        DeployListener.notifyFailure(set, target, event);
                        throw new UnsupportedOperationException(
                                "Unknown DeploySourceOrigin instance: " + origin);
                    }
                }
            }
            if (!found) {
                throw new DeploySourceNotFoundException(source,
                        "Cannot find source for " + target.getDisplayName());
            }
            if (location != null) {
                boolean haveAction = false;
                for (DeployedApplicationAction action : build.getActions(DeployedApplicationAction.class)) {
                    if (action.getLocation().equals(location)) {
                        haveAction = true;
                        break;
                    }
                }
                if (!haveAction) {
                    build.addAction(new DeployedApplicationAction<DeployedApplicationLocation>(location));
                }
            }
        } catch (RuntimeException e) {
            DeployListener.notifyFailure(set, target, event);
            throw e;
        } catch (DeployException e) {
            DeployListener.notifyFailure(set, target, event);
            throw e;
        }
    }
    return true;
}

From source file:de.xwic.sandbox.server.installer.modules.config.ConfigUpgradeScriptHelper.java

/**
 * @param scope//w ww.j  a va  2  s  .c o m
 * @param entityRolesAndRights
 * @param fromRolesAndRights
 * @param rightDao
 */
private void createScopes(final String scope, final Map<IRole, List<IAction>> entityRolesAndRights,
        final Map<IRole, List<IAction>> fromRolesAndRights, final IRightDAO rightDao) {
    final IScope theScope = getScope(scope);
    for (final Entry<IRole, List<IAction>> fromEntry : fromRolesAndRights.entrySet()) {
        final IRole currentRole = fromEntry.getKey();
        final List<IAction> shouldHaveThese = fromEntry.getValue();

        final List<IAction> currentScopeActions;
        if (entityRolesAndRights.containsKey(currentRole)) {
            currentScopeActions = entityRolesAndRights.get(currentRole);
            currentScopeActions.retainAll(shouldHaveThese);
        } else {
            currentScopeActions = Collections.emptyList();
        }

        for (final IAction mustHaveAction : shouldHaveThese) {
            if (currentScopeActions.contains(mustHaveAction)) {
                log.info(String.format("Right %s already exists for %s on %s", mustHaveAction.getName(),
                        currentRole.getName(), scope));
            } else {
                log.info(String.format("Creating %s right for %s on %s", mustHaveAction.getName(),
                        currentRole.getName(), scope));
                rightDao.createRight(currentRole, theScope, mustHaveAction);
            }
        }
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.dao.standard.JdbcScimGroupMembershipManager.java

@Override
public List<ScimGroupMemberInterface> updateOrAddMembers(String groupId, List<ScimGroupMemberInterface> members)
        throws ScimResourceNotFoundException {
    List<ScimGroupMemberInterface> currentMembers = getMembers(groupId);
    logger.debug("current-members: " + currentMembers + ", in request: " + members);

    List<ScimGroupMemberInterface> currentMembersToRemove = new ArrayList<ScimGroupMemberInterface>(
            currentMembers);/*from  w w w  .  j a  v  a2s.  c o  m*/
    currentMembersToRemove.removeAll(members);
    logger.debug("removing members: " + currentMembersToRemove);
    for (ScimGroupMemberInterface member : currentMembersToRemove) {
        removeMemberById(groupId, member.getMemberId());
    }

    List<ScimGroupMemberInterface> newMembersToAdd = new ArrayList<ScimGroupMemberInterface>(members);
    newMembersToAdd.removeAll(currentMembers);
    logger.debug("adding new members: " + newMembersToAdd);
    for (ScimGroupMemberInterface member : newMembersToAdd) {
        addMember(groupId, member);
    }

    List<ScimGroupMemberInterface> membersToUpdate = new ArrayList<ScimGroupMemberInterface>(members);
    membersToUpdate.retainAll(currentMembers);
    logger.debug("updating members: " + membersToUpdate);
    for (ScimGroupMemberInterface member : membersToUpdate) {
        updateMember(groupId, member);
    }

    return getMembers(groupId);
}

From source file:org.wso2.carbon.apimgt.impl.handlers.ScopesIssuer.java

public boolean setScopes(OAuthTokenReqMessageContext tokReqMsgCtx) {
    String[] requestedScopes = tokReqMsgCtx.getScope();
    String[] defaultScope = new String[] { DEFAULT_SCOPE_NAME };

    //If no scopes were requested.
    if (requestedScopes == null || requestedScopes.length == 0) {
        tokReqMsgCtx.setScope(defaultScope);
        return true;
    }//www  .j a  v a2 s.  c o m

    String consumerKey = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();
    String username = tokReqMsgCtx.getAuthorizedUser();
    List<String> reqScopeList = Arrays.asList(requestedScopes);

    try {
        Map<String, String> appScopes = null;
        ApiMgtDAO apiMgtDAO = new ApiMgtDAO();
        //Get all the scopes and roles against the scopes defined for the APIs subscribed to the application.
        appScopes = apiMgtDAO.getScopeRolesOfApplication(consumerKey);

        //If no scopes can be found in the context of the application
        if (appScopes.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug("No scopes defined for the Application "
                        + tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId());
            }

            String[] allowedScopes = getAllowedScopes(reqScopeList);
            tokReqMsgCtx.setScope(allowedScopes);
            return true;
        }

        int tenantId;
        RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
        UserStoreManager userStoreManager = null;
        String[] userRoles = null;

        try {
            tenantId = tokReqMsgCtx.getTenantID();

            // If tenant Id is not set in the tokenReqContext, deriving it from username.
            if (tenantId == 0 || tenantId == -1) {
                tenantId = IdentityUtil.getTenantIdOFUser(username);
            }
            userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
            userRoles = userStoreManager.getRoleListOfUser(MultitenantUtils.getTenantAwareUsername(username));
        } catch (UserStoreException e) {
            //Log and return since we do not want to stop issuing the token in case of scope validation failures.
            log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e);
            return false;
        }

        if (userRoles == null || userRoles.length == 0) {
            if (log.isDebugEnabled()) {
                log.debug("Could not find roles of the user.");
            }
            tokReqMsgCtx.setScope(defaultScope);
            return true;
        }

        List<String> authorizedScopes = new ArrayList<String>();
        List<String> userRoleList = new ArrayList<String>(Arrays.asList(userRoles));

        //Iterate the requested scopes list.
        for (String scope : reqScopeList) {
            //Get the set of roles associated with the requested scope.
            String roles = appScopes.get(scope);
            //If the scope has been defined in the context of the App and if roles have been defined for the scope
            if (roles != null && roles.length() != 0) {
                List<String> roleList = new ArrayList<String>(
                        Arrays.asList(roles.replaceAll(" ", "").split(",")));
                //Check if user has at least one of the roles associated with the scope
                roleList.retainAll(userRoleList);
                if (!roleList.isEmpty()) {
                    authorizedScopes.add(scope);
                }
            }
            //The requested scope is defined for the context of the App but no roles have been associated with the scope
            //OR
            //The scope string starts with 'device_'.
            else if (appScopes.containsKey(scope) || isWhiteListedScope(scope)) {
                authorizedScopes.add(scope);
            }
        }
        if (!authorizedScopes.isEmpty()) {
            String[] authScopesArr = authorizedScopes.toArray(new String[authorizedScopes.size()]);
            tokReqMsgCtx.setScope(authScopesArr);
        } else {
            tokReqMsgCtx.setScope(defaultScope);
        }
    } catch (APIManagementException e) {
        log.error("Error while getting scopes of application " + e.getMessage());
        return false;
    } catch (IdentityException e) {
        //Log and return since we do not want to stop issuing the token in case of scope validation failures.
        log.error("Error when obtaining tenant Id of user " + username, e);
        return false;
    }
    return true;
}

From source file:org.netflux.core.Record.java

/**
 * Removes from this record all the field metadata and all the fields with names included in the supplied collection.
 * //  w w  w  . java  2s.  c o  m
 * @param fieldNames the names of the field metadata and fields to remove.
 * @throws NullPointerException if the specified collection is <code>null</code>.
 */
public void remove(Collection<String> fieldNames) {
    List<String> fieldsToRemove = new LinkedList<String>(this.metadata.getFieldNames());
    fieldsToRemove.retainAll(fieldNames);

    ListIterator<String> fieldIndexIterator = fieldsToRemove.listIterator(fieldsToRemove.size());
    while (fieldIndexIterator.hasPrevious()) {
        this.data.remove(fieldIndexIterator.previous());
    }

    this.metadata.remove(fieldNames);
}