List of usage examples for com.google.common.collect Sets difference
public static <E> SetView<E> difference(final Set<E> set1, final Set<?> set2)
From source file:com.palantir.atlasdb.keyvalue.impl.TieredKeyValueService.java
public Set<String> getTieredTablenames() { if (tieredTables.isEmpty()) { return Sets.difference(getAllTableNames(), AtlasDbConstants.hiddenTables); } else {/*w w w .j ava 2 s . c om*/ return tieredTables; } }
From source file:org.abs_models.backend.erlang.Vars.java
/** * Removes all vars,which are not contained in vars */// w w w . ja v a 2s. c om public void retainAll(Vars vars) { for (String k : Sets.difference(this.keySet(), vars.keySet()).immutableCopy()) remove(k); }
From source file:org.mitre.oauth2.web.OAuthConfirmationController.java
@PreAuthorize("hasRole('ROLE_USER')") @RequestMapping("/oauth/confirm_access") public String confimAccess(Map<String, Object> model, @ModelAttribute("authorizationRequest") AuthorizationRequest authRequest, Principal p) { // Check the "prompt" parameter to see if we need to do special processing String prompt = (String) authRequest.getExtensions().get("prompt"); List<String> prompts = Splitter.on(" ").splitToList(Strings.nullToEmpty(prompt)); if (prompts.contains("none")) { // we're not supposed to prompt, so "return an error" logger.info("Client requested no prompt, returning 403 from confirmation endpoint"); model.put("code", HttpStatus.FORBIDDEN); return HttpCodeView.VIEWNAME; }//from ww w . j a v a 2 s . c om //AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest"); ClientDetailsEntity client = null; try { client = clientService.loadClientByClientId(authRequest.getClientId()); } catch (OAuth2Exception e) { logger.error("confirmAccess: OAuth2Exception was thrown when attempting to load client", e); model.put("code", HttpStatus.BAD_REQUEST); return HttpCodeView.VIEWNAME; } catch (IllegalArgumentException e) { logger.error("confirmAccess: IllegalArgumentException was thrown when attempting to load client", e); model.put("code", HttpStatus.BAD_REQUEST); return HttpCodeView.VIEWNAME; } if (client == null) { logger.error("confirmAccess: could not find client " + authRequest.getClientId()); model.put("code", HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME; } model.put("auth_request", authRequest); model.put("client", client); String redirect_uri = authRequest.getRedirectUri(); model.put("redirect_uri", redirect_uri); // pre-process the scopes Set<SystemScope> scopes = scopeService.fromStrings(authRequest.getScope()); Set<SystemScope> sortedScopes = new LinkedHashSet<SystemScope>(scopes.size()); Set<SystemScope> systemScopes = scopeService.getAll(); // sort scopes for display based on the inherent order of system scopes for (SystemScope s : systemScopes) { if (scopes.contains(s)) { sortedScopes.add(s); } } // add in any scopes that aren't system scopes to the end of the list sortedScopes.addAll(Sets.difference(scopes, systemScopes)); model.put("scopes", sortedScopes); // get the userinfo claims for each scope UserInfo user = userInfoService.getByUsername(p.getName()); JsonObject userJson = user.toJson(); Map<String, Map<String, String>> claimsForScopes = new HashMap<String, Map<String, String>>(); for (SystemScope systemScope : sortedScopes) { Map<String, String> claimValues = new HashMap<String, String>(); Set<String> claims = scopeClaimTranslationService.getClaimsForScope(systemScope.getValue()); for (String claim : claims) { if (userJson.has(claim) && userJson.get(claim).isJsonPrimitive()) { // TODO: this skips the address claim claimValues.put(claim, userJson.get(claim).getAsString()); } } claimsForScopes.put(systemScope.getValue(), claimValues); } model.put("claims", claimsForScopes); // client stats Integer count = statsService.getCountForClientId(client.getId()); model.put("count", count); // contacts if (client.getContacts() != null) { String contacts = Joiner.on(", ").join(client.getContacts()); model.put("contacts", contacts); } // if the client is over a week old and has more than one registration, don't give such a big warning // instead, tag as "Generally Recognized As Safe (gras) Date lastWeek = new Date(System.currentTimeMillis() + (60 * 60 * 24 * 7 * 1000)); //Date lastWeek = new Date(System.currentTimeMillis() - (60 * 60 * 24 * 7 * 1000)); if (count > 1 && client.getCreatedAt() != null && client.getCreatedAt().before(lastWeek)) { model.put("gras", true); } else { model.put("gras", false); } // inject a random value for CSRF purposes model.put("csrf", authRequest.getExtensions().get("csrf")); return "approve"; }
From source file:org.apache.cassandra.security.SSLFactory.java
private static String[] filterCipherSuites(String[] supported, String[] desired) { Set<String> des = Sets.newHashSet(desired); Set<String> toReturn = Sets.intersection(Sets.newHashSet(supported), des); if (des.size() > toReturn.size()) logger.warn("Filtering out {} as it isnt supported by the socket", StringUtils.join(Sets.difference(des, toReturn), ",")); return toReturn.toArray(new String[toReturn.size()]); }
From source file:com.getbase.android.schema.Schemas.java
private ImmutableMap<String, ImmutableList<? extends TableDefinitionOperation>> merge( ImmutableMap<String, ImmutableList<? extends TableDefinitionOperation>> schema, ImmutableMap<String, ImmutableList<? extends TableDowngradeOperation>> downgrades, int targetRevision) { ImmutableMap.Builder<String, ImmutableList<? extends TableDefinitionOperation>> builder = ImmutableMap .builder();/*from w w w . j a v a 2s. co m*/ for (String unchangedTable : Sets.difference(schema.keySet(), downgrades.keySet())) { builder.put(unchangedTable, schema.get(unchangedTable)); } for (String alteredTable : Sets.intersection(downgrades.keySet(), schema.keySet())) { ImmutableList<? extends TableDefinitionOperation> mergedOperations = MERGER.merge( schema.get(alteredTable), downgrades.get(alteredTable), alteredTable, targetRevision, mRevisionDescriptionBuilder); if (!mergedOperations.isEmpty()) { builder.put(alteredTable, mergedOperations); } } for (String addedTable : Sets.difference(downgrades.keySet(), schema.keySet())) { builder.put(addedTable, CONVERTER.convert(downgrades.get(addedTable), addedTable, targetRevision, mRevisionDescriptionBuilder)); } return builder.build(); }
From source file:io.galeb.router.sync.Updater.java
private void cleanup(final List<VirtualHost> virtualhosts) { final Set<String> virtualhostSet = virtualhosts.stream().map(AbstractEntity::getName) .collect(Collectors.toSet()); synchronized (cache) { Set<String> diff = Sets.difference(cache.getAll(), virtualhostSet); diff.forEach(virtualhostName -> { expireHandlers(virtualhostName); cache.remove(virtualhostName); logger.warn("Virtualhost " + virtualhostName + " not exist. Removed."); });/*from ww w.j a v a 2 s .c o m*/ } Set<String> diff = Sets.difference(nameVirtualHostHandler.getHosts().keySet(), virtualhostSet); diff.forEach(this::expireHandlers); }
From source file:cern.entwined.TransactionalMultimap.java
/** * Removes the given value from the entry with the given key. If there are no more values for the key, removes the * whole entry from the map.//w w w . j av a2 s .c o m * * @param key The key to retrieve the set. * @param value Value to be removed from the set. * @return The replaced set or an empty set if there was no entry with the given key. */ public Set<V> remove(K key, V value) { Set<V> oldSet = this.delegate.get(key); if (null != oldSet) { Set<V> newSet = Sets.difference(oldSet, Collections.singleton(value)).immutableCopy(); return this.unsafePut(key, newSet); } return this.remove(key); }
From source file:ai.grakn.graql.internal.reasoner.query.ReasonerAtomicQuery.java
@Override public Unifier getUnifier(ReasonerQuery p) { if (p == this) return new UnifierImpl(); ReasonerAtomicQuery parent = (ReasonerAtomicQuery) p; Unifier unifier = getAtom().getUnifier(parent.getAtom()); //get type unifiers Set<Atom> unified = new HashSet<>(); getAtom().getTypeConstraints().forEach(type -> { Set<Atom> toUnify = Sets.difference(parent.getEquivalentAtoms(type), unified); Atom equiv = toUnify.stream().findFirst().orElse(null); //only apply if unambiguous if (equiv != null && toUnify.size() == 1) { unifier.merge(type.getUnifier(equiv)); unified.add(equiv);/*from w ww .jav a2 s . c o m*/ } }); return unifier; }
From source file:uk.ac.open.kmi.iserve.discovery.disco.impl.GenericLogicDiscoverer.java
/** * Generic implementation for finding all the Services or Operations that have ALL the given types as inputs or outputs. * * @param entityType the MSM URI of the type of entity we are looking for. Only supports Service and Operation. * @param relationship the MSM URI of the relationship we are looking for. Only supports hasInput and hasOutput. * @param types the input/output types (modelReferences that is) we are looking for * @return a Map mapping operation/services URIs to MatchResults. *//*from w w w .jav a2 s . c o m*/ private Map<URI, MatchResult> findAll(URI entityType, URI relationship, Set<URI> types) { // Ensure that we have been given correct parameters if (types == null || types.isEmpty() || (!entityType.toASCIIString().equals(MSM.Service.getURI()) && !entityType.toASCIIString().equals(MSM.Operation.getURI())) || (!relationship.toASCIIString().equals(MSM.hasInput.getURI()) && !entityType.toASCIIString().equals(MSM.hasOutput.getURI()) && !relationship.toASCIIString().equals(SAWSDL.modelReference.getURI()))) { return ImmutableMap.of(); } // Expand the input types to get all that match enough to be consumed // The structure is: <OriginalType, MatchingType, MatchResult> Table<URI, URI, MatchResult> expandedTypes; if (relationship.toASCIIString().equals(SAWSDL.modelReference.getURI())) { expandedTypes = HashBasedTable.create(); for (URI type : types) { expandedTypes.putAll(this.conceptMatcher.listMatchesAtMostOfType(ImmutableSet.of(type), LogicConceptMatchType.Subsume)); expandedTypes.putAll( this.conceptMatcher.listMatchesOfType(ImmutableSet.of(type), LogicConceptMatchType.Exact)); } } else { expandedTypes = this.conceptMatcher.listMatchesAtLeastOfType(types, LogicConceptMatchType.Plugin); } // Track all the results in a multimap to push the details up the stack ListMultimap<URI, MatchResult> result = ArrayListMultimap.create(); // Do the intersection of those operations that can consume each of the inputs separately boolean firstTime = true; Map<URI, MatchResult> intermediateMatches; Map<URI, Map<URI, MatchResult>> rowMap = expandedTypes.rowMap(); // For each original type for (URI inputType : rowMap.keySet()) { // obtain those entities that match any of the expanded matching types intermediateMatches = findSome(entityType, relationship, rowMap.get(inputType).keySet()); if (firstTime) { // Add all entries firstTime = false; for (Map.Entry<URI, MatchResult> entry : intermediateMatches.entrySet()) { result.put(entry.getKey(), entry.getValue()); } } else { // Put all the values from the intersection Set<URI> intersection = Sets.intersection(result.keySet(), intermediateMatches.keySet()); for (URI opUri : intersection) { result.put(opUri, intermediateMatches.get(opUri)); } // Drop all the values from the difference // Use an immutable copy since the views will be changed Set<URI> difference = Sets.difference(result.keySet(), intermediateMatches.keySet()) .immutableCopy(); for (URI opUri : difference) { result.removeAll(opUri); } } } // Merge the results into a single map using Union return Maps.transformValues(result.asMap(), MatchResultsMerger.INTERSECTION); }
From source file:org.codice.ddf.catalog.ui.security.accesscontrol.AccessControlPreQueryPlugin.java
@Override public QueryRequest process(QueryRequest input) { if (!configuration.isPolicyToFilterEnabled()) { LOGGER.debug("Will not modify filter because policy to filter mapping is disabled; " + "refer to Catalog UI Search Workspace Security config to enable this behavior"); return input; }//from w w w.j a v a2s. c o m final String subjectIdentifier = getSubjectIdentifier(); final Set<String> groups = new HashSet<>(getSubjectGroups()); final String groupThatCanSeeEverything = configuration.getSystemUserAttributeValue(); if (groups.contains(groupThatCanSeeEverything)) { LOGGER.debug("Will not modify filter; subject ({}) had at least one group [{}] that was exempt [{}]", subjectIdentifier, groups, groupThatCanSeeEverything); return input; } final Query query = input.getQuery(); LOGGER.trace("Received query [{}]", query); final TagAggregationVisitor tagVisitor = new TagAggregationVisitor(); query.accept(tagVisitor, null); final Set<String> discoveredTags = tagVisitor.getTags(); if (CollectionUtils.isEmpty(discoveredTags)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Will not modify filter; subject's ({}) query [{}] did not imply all results had tags", subjectIdentifier, filterOnly(query)); } return input; } final Set<String> tagsThatAreAccessControlled = tagSet.getAccessControlledTags(); final Set<String> tagsNotAccessControlled = Sets.difference(discoveredTags, tagsThatAreAccessControlled); if (CollectionUtils.isNotEmpty(tagsNotAccessControlled)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Will not modify filter; subject's ({}) query [{}] referenced tags " + "[{}] that are not in access controlled set [{}]", subjectIdentifier, filterOnly(query), tagsNotAccessControlled, tagsThatAreAccessControlled); } return input; } final Filter policyBranch = createSecurityPolicySubset(subjectIdentifier, groups); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Query filter [{}] will be modified with access control policy [{}]", filterOnly(query), policyBranch); } final Filter combined = filterBuilder.allOf(query, policyBranch); return new QueryRequestImpl( new QueryImpl(combined, query.getStartIndex(), query.getPageSize(), query.getSortBy(), query.requestsTotalResultsCount(), query.getTimeoutMillis()), input.isEnterprise(), input.getSourceIds(), input.getProperties()); }