Example usage for java.util Set retainAll

List of usage examples for java.util Set retainAll

Introduction

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

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

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

Usage

From source file:org.alfresco.repo.node.getchildren.GetChildrenCannedQuery.java

private boolean includeAspects(NodeRef nodeRef, Set<QName> inclusiveAspects, Set<QName> exclusiveAspects) {
    if (inclusiveAspects == null && exclusiveAspects == null) {
        return true;
    }//www.  jav a2s .co  m

    Set<QName> nodeAspects = nodeService.getAspects(nodeRef);
    if (inclusiveAspects != null) {
        Set<QName> includedIntersect = new HashSet<QName>(nodeAspects);
        includedIntersect.retainAll(inclusiveAspects);
        if (includedIntersect.isEmpty()) {
            return false;
        }
    }
    if (exclusiveAspects != null) {
        Set<QName> excludedIntersect = new HashSet<QName>(nodeAspects);
        excludedIntersect.retainAll(exclusiveAspects);
        if (excludedIntersect.isEmpty() == false) {
            return false;
        }
    }
    return true;

}

From source file:nl.spellenclubeindhoven.dominionshuffle.data.CardSelector.java

/**
 * Check the current results to determine if need to pick a Bane
 *///  w  w  w. j  ava 2 s  .c  o m
private void addBaneIfNeeded(final Result result, final Set<Card> availableCards) throws SolveError {
    // Firstly have we already done the bane card
    if (result.getBaneCard() != null) {
        return;
    }

    // Check if Young Witch is in the selection
    boolean youngWitchInSelection = false;
    Card youngWitch = data.getCard(YOUNG_WITCH_CARD);
    for (Card card : result.getCards()) {
        if (card == youngWitch) {
            youngWitchInSelection = true;
            break;
        }
    }
    if (!youngWitchInSelection) {
        // Young Witch isn't in selection, don't do anything.
        return;
    }

    final Group cost2 = data.getGroup(COST_2_Group);
    final Group cost3 = data.getGroup(COST_3_Group);
    final Set<Card> cost2Or3Cards = new HashSet<>(cost2.getCards());
    cost2Or3Cards.addAll(cost3.getCards());
    cost2Or3Cards.retainAll(availableCards);

    // Filter out Basic and Non-Supply Cards
    // While it means looping through again before we find our random card, we have to so we know how many to count from.
    for (Iterator<Card> i = cost2Or3Cards.iterator(); i.hasNext();) {
        if (i.next().isBasicOrNonSupply()) {
            i.remove();
        }
    }

    if (cost2Or3Cards.isEmpty()) {
        throw new SolveError(R.string.solveerror_not_enough_cards,
                "Not enough cost 2 or 3 cards for selecting a bane card");
    }

    // Randomise selection from the set
    final int cardToFetch = this.random.nextInt(cost2Or3Cards.size());
    final Iterator<Card> iterator = cost2Or3Cards.iterator();
    for (int i = 0; i < cardToFetch; i++) {
        iterator.next();
    }
    final Card baneCard = iterator.next();

    result.setBaneCard(baneCard);
    result.addCard(baneCard);

    availableCards.remove(baneCard);
}

From source file:org.apache.hyracks.algebricks.rewriter.rules.AbstractIntroduceGroupByCombinerRule.java

/**
 * Find the set of used free variables along the pipeline from <code>topOpRef</code> (exclusive)
 * to <code>bottomOpRef</code> (inclusive).
 *
 * @param topOpRef,// w  ww .  j  a v  a  2 s . c  o m
 *            the top root of the pipeline.
 * @param bottomOpRef,
 *            the bottom of the pipeline.
 * @return the set of used variables.
 * @throws AlgebricksException
 */
private Set<LogicalVariable> collectUsedFreeVariables(Mutable<ILogicalOperator> topOpRef,
        Mutable<ILogicalOperator> bottomOpRef) throws AlgebricksException {
    Set<LogicalVariable> usedVars = new HashSet<>();
    Mutable<ILogicalOperator> currentOpRef = topOpRef;
    while (currentOpRef != bottomOpRef) {
        currentOpRef = currentOpRef.getValue().getInputs().get(0);
        VariableUtilities.getUsedVariables(currentOpRef.getValue(), usedVars);
    }
    Set<LogicalVariable> freeVars = new HashSet<>();
    OperatorPropertiesUtil.getFreeVariablesInSelfOrDesc((AbstractLogicalOperator) topOpRef.getValue(),
            freeVars);
    usedVars.retainAll(freeVars);
    return usedVars;
}

From source file:uk.gov.gchq.gaffer.spark.operation.dataframe.FiltersToOperationConverter.java

private Set<String> getGroupsFromFilter(final Filter filter) {
    if (filter instanceof EqualTo) {
        return getGroupsThatHaveProperty(((EqualTo) filter).attribute());
    } else if (filter instanceof EqualNullSafe) {
        return getGroupsThatHaveProperty(((EqualNullSafe) filter).attribute());
    } else if (filter instanceof GreaterThan) {
        return getGroupsThatHaveProperty(((GreaterThan) filter).attribute());
    } else if (filter instanceof GreaterThanOrEqual) {
        return getGroupsThatHaveProperty(((GreaterThanOrEqual) filter).attribute());
    } else if (filter instanceof LessThan) {
        return getGroupsThatHaveProperty(((LessThan) filter).attribute());
    } else if (filter instanceof LessThanOrEqual) {
        return getGroupsThatHaveProperty(((LessThanOrEqual) filter).attribute());
    } else if (filter instanceof In) {
        return getGroupsThatHaveProperty(((In) filter).attribute());
    } else if (filter instanceof IsNull) {
        // Return null to indicate all groups as the user could be deliberately finding rows for one group by
        // specifying that a field from another group should be null
        return null;
    } else if (filter instanceof IsNotNull) {
        return getGroupsThatHaveProperty(((IsNotNull) filter).attribute());
    } else if (filter instanceof And) {
        final And and = (And) filter;
        final Set<String> groups = new HashSet<>();
        final Set<String> leftGroups = getGroupsFromFilter(and.left());
        final Set<String> rightGroups = getGroupsFromFilter(and.right());
        if (leftGroups != null) {
            groups.addAll(leftGroups);//from w ww. j av a2 s  .  co m
        }
        if (rightGroups != null) {
            groups.retainAll(rightGroups);
        }
        return groups;
    }
    return null;
}

From source file:com.digitalpebble.storm.crawler.protocol.http.HttpResponse.java

/**
 * Default public constructor./*from   w  w w.  ja v a2  s .c om*/
 * 
 * @param http
 * @param url
 * @param knownMetadata
 * @throws IOException
 * @throws HttpException
 */
public HttpResponse(HttpProtocol http, URL url, Metadata knownMetadata) throws IOException, HttpException {

    this.http = http;
    this.url = url;

    Scheme scheme = null;

    if ("http".equals(url.getProtocol())) {
        scheme = Scheme.HTTP;
    } else if ("https".equals(url.getProtocol())) {
        scheme = Scheme.HTTPS;
    } else {
        throw new IOException("Unknown scheme (not http/https) for url:" + url);
    }

    String path = "".equals(url.getFile()) ? "/" : url.getFile();

    // some servers will redirect a request with a host line like
    // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they
    // don't want the :80...

    String host = url.getHost();
    int port;
    String portString;
    if (url.getPort() == -1) {
        if (scheme == Scheme.HTTP) {
            port = 80;
        } else {
            port = 443;
        }
        portString = "";
    } else {
        port = url.getPort();
        portString = ":" + port;
    }
    Socket socket = null;

    try {
        socket = new Socket(); // create the socket
        socket.setSoTimeout(http.getTimeout());

        // connect
        String sockHost = http.useProxy() ? http.getProxyHost() : host;
        int sockPort = http.useProxy() ? http.getProxyPort() : port;
        InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort);
        socket.connect(sockAddr, http.getTimeout());

        if (scheme == Scheme.HTTPS) {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true);
            sslsocket.setUseClientMode(true);

            // Get the protocols and ciphers supported by this JVM
            Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols()));
            Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites()));

            // Intersect with preferred protocols and ciphers
            protocols.retainAll(http.getTlsPreferredProtocols());
            ciphers.retainAll(http.getTlsPreferredCipherSuites());

            sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
            sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()]));

            sslsocket.startHandshake();
            socket = sslsocket;
        }

        this.conf = http.getConf();
        if (ConfUtils.getBoolean(conf, "store.ip.address", false) == true) {
            headers.setValue("_ip_", sockAddr.getAddress().getHostAddress());
        }

        // make request
        OutputStream req = socket.getOutputStream();

        StringBuffer reqStr = new StringBuffer("GET ");
        if (http.useProxy()) {
            reqStr.append(url.getProtocol() + "://" + host + portString + path);
        } else {
            reqStr.append(path);
        }

        reqStr.append(" HTTP/1.0\r\n");

        reqStr.append("Host: ");
        reqStr.append(host);
        reqStr.append(portString);
        reqStr.append("\r\n");

        reqStr.append("Accept-Encoding: x-gzip, gzip, deflate\r\n");

        String userAgent = http.getUserAgent();
        if ((userAgent == null) || (userAgent.length() == 0)) {
            if (HttpProtocol.LOGGER.isErrorEnabled()) {
                HttpProtocol.LOGGER.error("User-agent is not set!");
            }
        } else {
            reqStr.append("User-Agent: ");
            reqStr.append(userAgent);
            reqStr.append("\r\n");
        }

        reqStr.append("Accept-Language: ");
        reqStr.append(this.http.getAcceptLanguage());
        reqStr.append("\r\n");

        reqStr.append("Accept: ");
        reqStr.append(this.http.getAccept());
        reqStr.append("\r\n");

        if (knownMetadata != null) {
            String ifModifiedSince = knownMetadata.getFirstValue("cachedLastModified");
            if (StringUtils.isNotBlank(ifModifiedSince)) {
                reqStr.append("If-Modified-Since: ");
                reqStr.append(ifModifiedSince);
                reqStr.append("\r\n");
            }

            String ifNoneMatch = knownMetadata.getFirstValue("cachedEtag");
            if (StringUtils.isNotBlank(ifNoneMatch)) {
                reqStr.append("If-None-Match: ");
                reqStr.append(ifNoneMatch);
                reqStr.append("\r\n");
            }
        }

        reqStr.append("\r\n");

        // @see http://www.w3.org/Protocols/rfc2068/rfc2068.txt for default
        // charset
        // TODO use UTF-8 and set a charset value explicitely
        byte[] reqBytes = reqStr.toString().getBytes(StandardCharsets.ISO_8859_1);

        req.write(reqBytes);
        req.flush();

        PushbackInputStream in = // process response
                new PushbackInputStream(
                        new BufferedInputStream(socket.getInputStream(), HttpProtocol.BUFFER_SIZE),
                        HttpProtocol.BUFFER_SIZE);

        StringBuffer line = new StringBuffer();

        boolean haveSeenNonContinueStatus = false;
        while (!haveSeenNonContinueStatus) {
            // parse status code line
            this.code = parseStatusLine(in, line);
            // parse headers
            parseHeaders(in, line);
            haveSeenNonContinueStatus = code != 100; // 100 is
                                                     // "Continue"
        }
        String transferEncoding = getHeader(HttpHeaders.TRANSFER_ENCODING);
        if (transferEncoding != null && "chunked".equalsIgnoreCase(transferEncoding.trim())) {
            readChunkedContent(in, line);
        } else {
            readPlainContent(in);
        }

        String contentEncoding = getHeader(HttpHeaders.CONTENT_ENCODING);
        if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) {
            content = http.processGzipEncoded(content, url);
        } else if ("deflate".equals(contentEncoding)) {
            content = http.processDeflateEncoded(content, url);
        } else {
            HttpProtocol.LOGGER.trace("fetched {}  bytes from {}", content.length, url);
        }

    } finally {
        if (socket != null)
            socket.close();
    }

}

From source file:org.apache.syncope.core.spring.security.AuthDataAccessor.java

protected Set<? extends ExternalResource> getPassthroughResources(final User user) {
    Set<? extends ExternalResource> result = null;

    // 1. look for assigned resources, pick the ones whose account policy has authentication resources
    for (ExternalResource resource : userDAO.findAllResources(user)) {
        if (resource.getAccountPolicy() != null && !resource.getAccountPolicy().getResources().isEmpty()) {
            if (result == null) {
                result = resource.getAccountPolicy().getResources();
            } else {
                result.retainAll(resource.getAccountPolicy().getResources());
            }/* w w w  . ja va  2  s . c  o  m*/
        }
    }

    // 2. look for realms, pick the ones whose account policy has authentication resources
    for (Realm realm : realmDAO.findAncestors(user.getRealm())) {
        if (realm.getAccountPolicy() != null && !realm.getAccountPolicy().getResources().isEmpty()) {
            if (result == null) {
                result = realm.getAccountPolicy().getResources();
            } else {
                result.retainAll(realm.getAccountPolicy().getResources());
            }
        }
    }

    return result == null ? Collections.emptySet() : result;
}

From source file:org.sakaiproject.lessonbuildertool.service.LessonsGradeInfoProvider.java

Set<String> usersInPath(Collection<String> userIds, Set<Path> paths, String siteId) {

    Set<String> retUsers = new HashSet<String>();

    for (Path path : paths) {
        if (path.groups == null) // no constraint
            return new HashSet<String>(userIds);

        // users for this path. It's users who are in all the groups
        Set<String> pathUsers = new HashSet<String>(userIds);

        for (Set<String> groupIds : path.groups) {
            Set<String> groups = new HashSet<String>();
            for (String groupId : groupIds)
                groups.add("/site/" + siteId + "/group/" + groupId);
            Set<String> okUsers = new HashSet<String>(authzGroupService.getAuthzUsersInGroups(groups));
            pathUsers.retainAll(okUsers);
        }//from  ww w . ja  v  a  2  s .  c  om

        // these users are in all path elements, add them to be returned
        retUsers.addAll(pathUsers);
    }

    return retUsers;
}

From source file:org.apache.solr.client.solrj.impl.CloudSolrServer.java

private NamedList directUpdate(AbstractUpdateRequest request, ClusterState clusterState)
        throws SolrServerException {
    UpdateRequest updateRequest = (UpdateRequest) request;
    ModifiableSolrParams params = (ModifiableSolrParams) request.getParams();
    ModifiableSolrParams routableParams = new ModifiableSolrParams();
    ModifiableSolrParams nonRoutableParams = new ModifiableSolrParams();

    if (params != null) {
        nonRoutableParams.add(params);//w  w w  .ja va2s  . com
        routableParams.add(params);
        for (String param : NON_ROUTABLE_PARAMS) {
            routableParams.remove(param);
        }
    }

    String collection = nonRoutableParams.get(UpdateParams.COLLECTION, defaultCollection);
    if (collection == null) {
        throw new SolrServerException(
                "No collection param specified on request and no default collection has been set.");
    }

    //Check to see if the collection is an alias.
    Aliases aliases = zkStateReader.getAliases();
    if (aliases != null) {
        Map<String, String> collectionAliases = aliases.getCollectionAliasMap();
        if (collectionAliases != null && collectionAliases.containsKey(collection)) {
            collection = collectionAliases.get(collection);
        }
    }

    DocCollection col = clusterState.getCollection(collection);

    DocRouter router = col.getRouter();

    if (router instanceof ImplicitDocRouter) {
        // short circuit as optimization
        return null;
    }

    //Create the URL map, which is keyed on slice name.
    //The value is a list of URLs for each replica in the slice.
    //The first value in the list is the leader for the slice.
    Map<String, List<String>> urlMap = buildUrlMap(col);
    if (urlMap == null) {
        // we could not find a leader yet - use unoptimized general path
        return null;
    }

    NamedList<Throwable> exceptions = new NamedList<Throwable>();
    NamedList<NamedList> shardResponses = new NamedList<NamedList>();

    Map<String, LBHttpSolrServer.Req> routes = updateRequest.getRoutes(router, col, urlMap, routableParams,
            this.idField);
    if (routes == null) {
        return null;
    }

    long start = System.nanoTime();

    if (parallelUpdates) {
        final Map<String, Future<NamedList<?>>> responseFutures = new HashMap<>(routes.size());
        for (final Map.Entry<String, LBHttpSolrServer.Req> entry : routes.entrySet()) {
            final String url = entry.getKey();
            final LBHttpSolrServer.Req lbRequest = entry.getValue();
            responseFutures.put(url, threadPool.submit(new Callable<NamedList<?>>() {
                @Override
                public NamedList<?> call() throws Exception {
                    return lbServer.request(lbRequest).getResponse();
                }
            }));
        }

        for (final Map.Entry<String, Future<NamedList<?>>> entry : responseFutures.entrySet()) {
            final String url = entry.getKey();
            final Future<NamedList<?>> responseFuture = entry.getValue();
            try {
                shardResponses.add(url, responseFuture.get());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                exceptions.add(url, e.getCause());
            }
        }

        if (exceptions.size() > 0) {
            throw new RouteException(ErrorCode.SERVER_ERROR, exceptions, routes);
        }
    } else {
        for (Map.Entry<String, LBHttpSolrServer.Req> entry : routes.entrySet()) {
            String url = entry.getKey();
            LBHttpSolrServer.Req lbRequest = entry.getValue();
            try {
                NamedList rsp = lbServer.request(lbRequest).getResponse();
                shardResponses.add(url, rsp);
            } catch (Exception e) {
                throw new SolrServerException(e);
            }
        }
    }

    UpdateRequest nonRoutableRequest = null;
    List<String> deleteQuery = updateRequest.getDeleteQuery();
    if (deleteQuery != null && deleteQuery.size() > 0) {
        UpdateRequest deleteQueryRequest = new UpdateRequest();
        deleteQueryRequest.setDeleteQuery(deleteQuery);
        nonRoutableRequest = deleteQueryRequest;
    }

    Set<String> paramNames = nonRoutableParams.getParameterNames();

    Set<String> intersection = new HashSet<>(paramNames);
    intersection.retainAll(NON_ROUTABLE_PARAMS);

    if (nonRoutableRequest != null || intersection.size() > 0) {
        if (nonRoutableRequest == null) {
            nonRoutableRequest = new UpdateRequest();
        }
        nonRoutableRequest.setParams(nonRoutableParams);
        List<String> urlList = new ArrayList<>();
        urlList.addAll(routes.keySet());
        Collections.shuffle(urlList, rand);
        LBHttpSolrServer.Req req = new LBHttpSolrServer.Req(nonRoutableRequest, urlList);
        try {
            LBHttpSolrServer.Rsp rsp = lbServer.request(req);
            shardResponses.add(urlList.get(0), rsp.getResponse());
        } catch (Exception e) {
            throw new SolrException(ErrorCode.SERVER_ERROR, urlList.get(0), e);
        }
    }

    long end = System.nanoTime();

    RouteResponse rr = condenseResponse(shardResponses, (long) ((end - start) / 1000000));
    rr.setRouteResponses(shardResponses);
    rr.setRoutes(routes);
    return rr;
}

From source file:org.apache.zeppelin.interpreter.InterpreterSetting.java

public boolean isUserAuthorized(List<String> userAndRoles) {
    if (!option.permissionIsSet()) {
        return true;
    }/*from w ww.j av  a 2s  .  c o  m*/
    Set<String> intersection = new HashSet<>(userAndRoles);
    intersection.retainAll(option.getOwners());
    return intersection.isEmpty();
}

From source file:eu.ggnet.dwoss.redtape.entity.Document.java

/**
 * Returns true if none of the condition is at the document.
 * <p>//from w  w  w .  java  2  s .com
 * @param filter the condition to test against.
 * @return true if none of the condition is at the document.
 */
public boolean containsNone(Condition... filter) {
    if (filter == null || filter.length == 0)
        throw new RuntimeException("The filter for contains any must not be null or empty");
    Set<Condition> toRetain = new HashSet<>(conditions);
    toRetain.retainAll(Arrays.asList(filter));
    return toRetain.isEmpty();
}