List of usage examples for java.util Collection removeAll
boolean removeAll(Collection<?> c);
From source file:org.openmrs.module.providermanagement.api.impl.ProviderSuggestionServiceImpl.java
@Override @Transactional(readOnly = true)/*from www.java 2s. co m*/ public List<Person> suggestProvidersForPatient(Patient patient, RelationshipType relationshipType) throws InvalidRelationshipTypeException, SuggestionEvaluationException { if (patient == null) { throw new APIException("Patient cannot be null"); } if (relationshipType == null) { throw new APIException("Relationship type cannot be null"); } if (!Context.getService(ProviderManagementService.class).getAllProviderRoleRelationshipTypes(false) .contains(relationshipType)) { throw new InvalidRelationshipTypeException("Invalid relationship type: " + relationshipType + " is not a valid provider relationship type"); } // first, see if there are any suggestion rules if not, just return null List<ProviderSuggestion> suggestions = getProviderSuggestionsByRelationshipType(relationshipType); if (suggestions == null || suggestions.size() == 0) { return null; } // otherwise, get all the providers that match the suggestion rules Collection<Person> suggestedProviders = new HashSet<Person>(); for (ProviderSuggestion suggestion : suggestions) { try { SuggestionEvaluator evaluator = suggestion.instantiateEvaluator(); Set<Person> p = evaluator.evaluate(suggestion, patient, relationshipType); if (p != null) { // note that we are doing union, not intersection, here if there are multiple rules suggestedProviders.addAll(p); } } catch (Exception e) { throw new SuggestionEvaluationException("Unable to evaluate suggestion " + suggestion, e); } } // only keep those providers that are valid (ie, support the specified relationship type // TODO: might want to test the performance of this suggestedProviders.retainAll(Context.getService(ProviderManagementService.class) .getProvidersAsPersonsByRelationshipType(relationshipType)); // finally, remove any providers that are already assigned to this patient suggestedProviders.removeAll(Context.getService(ProviderManagementService.class) .getProvidersAsPersonsForPatient(patient, relationshipType, new Date())); return new ArrayList<Person>(suggestedProviders); }
From source file:com.facebook.model.GraphObjectFactoryTests.java
@SmallTest @MediumTest/* ww w. ja v a 2 s.c o m*/ @LargeTest public void testCollectionRemoveAllThrows() throws JSONException { try { Collection<Integer> collection = GraphObject.Factory.createList(Integer.class); collection.removeAll(Arrays.asList()); fail("Expected exception"); } catch (UnsupportedOperationException exception) { } }
From source file:org.wso2.carbon.identity.authenticator.saml2.sso.SAML2SSOAuthenticator.java
/** * Provision/Create user on the server(SP) and update roles accordingly * * @param username/* w ww . j a v a 2 s . c om*/ * @param realm * @param xmlObject * @throws UserStoreException * @throws SAML2SSOAuthenticatorException */ private void provisionUser(String username, UserRealm realm, XMLObject xmlObject) throws UserStoreException, SAML2SSOAuthenticatorException { AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance(); AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration .getAuthenticatorConfig(AUTHENTICATOR_NAME); if (authenticatorConfig != null) { Map<String, String> configParameters = authenticatorConfig.getParameters(); boolean isJITProvisioningEnabled = false; if (configParameters .containsKey(SAML2SSOAuthenticatorBEConstants.PropertyConfig.JIT_USER_PROVISIONING_ENABLED)) { isJITProvisioningEnabled = Boolean.parseBoolean(configParameters .get(SAML2SSOAuthenticatorBEConstants.PropertyConfig.JIT_USER_PROVISIONING_ENABLED)); } if (isJITProvisioningEnabled) { String userstoreDomain = null; if (configParameters.containsKey( SAML2SSOAuthenticatorBEConstants.PropertyConfig.PROVISIONING_DEFAULT_USERSTORE)) { userstoreDomain = configParameters .get(SAML2SSOAuthenticatorBEConstants.PropertyConfig.PROVISIONING_DEFAULT_USERSTORE); } UserStoreManager userstore = null; // TODO : Get userstore from asserstion // TODO : remove user store domain name from username if (userstoreDomain != null && !userstoreDomain.isEmpty()) { userstore = realm.getUserStoreManager().getSecondaryUserStoreManager(userstoreDomain); } // If default user store is invalid or not specified use primary user store if (userstore == null) { userstore = realm.getUserStoreManager(); } String[] newRoles = getRoles(xmlObject); // Load default role if asserstion didnt specify roles if (newRoles == null || newRoles.length == 0) { if (configParameters.containsKey( SAML2SSOAuthenticatorBEConstants.PropertyConfig.PROVISIONING_DEFAULT_ROLE)) { newRoles = new String[] { configParameters .get(SAML2SSOAuthenticatorBEConstants.PropertyConfig.PROVISIONING_DEFAULT_ROLE) }; } } if (newRoles == null) { newRoles = new String[] {}; } if (log.isDebugEnabled()) { log.debug("User " + username + " contains roles : " + Arrays.toString(newRoles) + " as per response and (default role) config"); } // addingRoles = newRoles AND allExistingRoles Collection<String> addingRoles = new ArrayList<String>(); Collections.addAll(addingRoles, newRoles); Collection<String> allExistingRoles = Arrays.asList(userstore.getRoleNames()); addingRoles.retainAll(allExistingRoles); if (userstore.isExistingUser(username)) { // Update user Collection<String> currentRolesList = Arrays.asList(userstore.getRoleListOfUser(username)); // addingRoles = (newRoles AND existingRoles) - currentRolesList) addingRoles.removeAll(currentRolesList); Collection<String> deletingRoles = new ArrayList<String>(); deletingRoles.addAll(currentRolesList); // deletingRoles = currentRolesList - newRoles deletingRoles.removeAll(Arrays.asList(newRoles)); // Exclude Internal/everyonerole from deleting role since its cannot be deleted deletingRoles.remove(realm.getRealmConfiguration().getEveryOneRoleName()); // Check for case whether superadmin login if (userstore.getRealmConfiguration().isPrimary() && username.equals(realm.getRealmConfiguration().getAdminUserName())) { boolean isSuperAdminRoleRequired = false; if (configParameters.containsKey( SAML2SSOAuthenticatorBEConstants.PropertyConfig.IS_SUPER_ADMIN_ROLE_REQUIRED)) { isSuperAdminRoleRequired = Boolean.parseBoolean(configParameters.get( SAML2SSOAuthenticatorBEConstants.PropertyConfig.IS_SUPER_ADMIN_ROLE_REQUIRED)); } // Whether superadmin login without superadmin role is permitted if (!isSuperAdminRoleRequired && deletingRoles.contains(realm.getRealmConfiguration().getAdminRoleName())) { // Avoid removing superadmin role from superadmin user. deletingRoles.remove(realm.getRealmConfiguration().getAdminRoleName()); log.warn( "Proceeding with allowing super admin to be logged in, eventhough response doesn't include superadmin role assiged for the superadmin user."); } } if (log.isDebugEnabled()) { log.debug("Deleting roles : " + Arrays.toString(deletingRoles.toArray(new String[0])) + " and Adding roles : " + Arrays.toString(addingRoles.toArray(new String[0]))); } userstore.updateRoleListOfUser(username, deletingRoles.toArray(new String[0]), addingRoles.toArray(new String[0])); if (log.isDebugEnabled()) { log.debug("User: " + username + " is updated via SAML authenticator with roles : " + Arrays.toString(newRoles)); } } else { userstore.addUser(username, generatePassword(username), addingRoles.toArray(new String[0]), null, null); if (log.isDebugEnabled()) { log.debug("User: " + username + " is provisioned via SAML authenticator with roles : " + Arrays.toString(addingRoles.toArray(new String[0]))); } } } else { if (log.isDebugEnabled()) { log.debug("User provisioning diabled"); } } } else { if (log.isDebugEnabled()) { log.debug("Cannot find authenticator config for authenticator : " + AUTHENTICATOR_NAME); } throw new SAML2SSOAuthenticatorException( "Cannot find authenticator config for authenticator : " + AUTHENTICATOR_NAME); } }
From source file:org.openmrs.module.providermanagement.api.impl.ProviderSuggestionServiceImpl.java
private List<Person> suggestSupervisionForProviderHelper(Person provider, SupervisionSuggestionType type) throws PersonIsNotProviderException, SuggestionEvaluationException { if (provider == null) { throw new APIException("Provider cannot be null"); }/*from w w w .j a v a 2 s . c om*/ // fail if the person is not a provider if (!Context.getService(ProviderManagementService.class).isProvider(provider)) { throw new PersonIsNotProviderException(provider + " is not a provider"); } // first, get all the roles for this provider List<ProviderRole> roles = Context.getService(ProviderManagementService.class).getProviderRoles(provider); // if the provider has no roles, return null if (roles == null || roles.size() == 0) { return null; } // now get all the roles that this provider can supervise or be supervisors by (depending on type) List<ProviderRole> validRoles; if (type.equals(SupervisionSuggestionType.SUPERVISEE_SUGGESTION)) { validRoles = Context.getService(ProviderManagementService.class) .getProviderRolesThatProviderCanSupervise(provider); } else { validRoles = Context.getService(ProviderManagementService.class) .getProviderRolesThatCanSuperviseThisProvider(provider); } // get any suggestions based on the provider roles Set<SupervisionSuggestion> suggestions = new HashSet<SupervisionSuggestion>(); for (ProviderRole role : roles) { List<SupervisionSuggestion> s = getSupervisionSuggestionsByProviderRoleAndSuggestionType(role, type); if (s != null && s.size() > 0) { suggestions.addAll(s); } } // if there are no suggestions, or no valid roles, just return null if (suggestions.size() == 0 || validRoles == null || validRoles.size() == 0) { return null; } // otherwise, get all the providers that match the suggestion rules Collection<Person> suggestedProviders = new HashSet<Person>(); for (SupervisionSuggestion suggestion : suggestions) { try { SuggestionEvaluator evaluator = suggestion.instantiateEvaluator(); Set<Person> p = evaluator.evaluate(suggestion, provider); if (p != null) { // note that we are doing union, not intersection, here if there are multiple rules suggestedProviders.addAll(p); } } catch (Exception e) { throw new SuggestionEvaluationException("Unable to evaluate suggestion " + suggestion, e); } } // only keep providers that are valid for this provider to supervise or be supervised by suggestedProviders.retainAll( Context.getService(ProviderManagementService.class).getProvidersAsPersonsByRoles(validRoles)); // finally, remove any providers that this provider is already supervising or being supervised by if (type.equals(SupervisionSuggestionType.SUPERVISEE_SUGGESTION)) { suggestedProviders.removeAll(Context.getService(ProviderManagementService.class) .getSuperviseesForSupervisor(provider, new Date())); } else { suggestedProviders.removeAll(Context.getService(ProviderManagementService.class) .getSupervisorsForProvider(provider, new Date())); } // return the result set return new ArrayList<Person>(suggestedProviders); }
From source file:org.apache.hadoop.mapred.WorkflowTaskScheduler.java
@Override public synchronized Collection<JobInProgress> getJobs(String queueName) { Collection<JobInProgress> jobCollection = new ArrayList<JobInProgress>(); WorkflowSchedulerQueue queue = queueInfoMap.get(queueName); Collection<JobInProgress> runningJobs = queue.getRunningJobs(); jobCollection.addAll(queue.getInitializingJobs()); if (runningJobs != null) { jobCollection.addAll(runningJobs); }// w ww .j av a 2s. co m Collection<JobInProgress> waitingJobs = queue.getWaitingJobs(); Collection<JobInProgress> tempCollection = new ArrayList<JobInProgress>(); if (waitingJobs != null) { tempCollection.addAll(waitingJobs); } tempCollection.removeAll(runningJobs); if (!tempCollection.isEmpty()) { jobCollection.addAll(tempCollection); } return jobCollection; }
From source file:org.sipfoundry.sipxconfig.phonebook.PhonebookManagerImpl.java
public Collection<Phonebook> getPhonebooks() { Collection<Phonebook> books = getHibernateTemplate().loadAll(Phonebook.class); if (!books.isEmpty()) { Collection<Phonebook> privatePhonebooks = new ArrayList<Phonebook>(); for (Phonebook book : books) { if (book.getUser() != null) { privatePhonebooks.add(book); }// w ww . j av a 2 s. c o m } if (!privatePhonebooks.isEmpty()) { // remove private phone books books.removeAll(privatePhonebooks); } } return books; }
From source file:com.knowbout.cc2nlp.server.CCEventServiceImpl.java
private void removeStopWordsAndLengthCheck(Collection<Keyword> keywords) { List<Keyword> toRemove = new ArrayList<Keyword>(); Set<String> stopWords = new HashSet<String>(this.getConfigStrings("stopWords.word")); for (Keyword kw : keywords) { if (!kw.isMultiword() && stopWords.contains(kw.getKeyword())) { toRemove.add(kw);//from w ww . j a v a2 s. c o m } else if (!kw.isMultiword() && kw.getKeyword().length() > this.getConfigInt("maximumKeywordLength", 30)) { log.warn("Removed excessively long keyword " + kw.getKeyword()); toRemove.add(kw); } else if (kw.isMultiword() && kw.getKeyword().length() > this.getConfigInt("maximumMultiwordKeywordLength", 120)) { log.warn("Removed excessively long keyword " + kw.getKeyword()); toRemove.add(kw); } } if (!toRemove.isEmpty()) { if (log.isDebugEnabled()) { log.debug("removing stopwords: " + toRemove); } keywords.removeAll(toRemove); } }
From source file:com.nextep.designer.vcs.services.impl.DependencyService.java
@Override public Collection<IReferencer> getReferencersAfterDeletion(IReferenceable ref, Collection<IReferencer> deps, Collection<IReferencer> deletedReferencers) { // Copying collection because we will alter it Collection<IReferencer> dependencies = new ArrayList<IReferencer>(deps); if (dependencies != null && dependencies.size() > 0) { // If the removed object is a reference container, we remove dependencies // which are declared by the removed object. Only to allow removal of objects // which have only dependencies to themselves. if (ref instanceof IReferenceContainer) { Collection<IReference> declaredRefs = new ArrayList<IReference>(); declaredRefs.addAll(((IReferenceContainer) ref).getReferenceMap().keySet()); declaredRefs.add(ref.getReference()); for (IReferencer depRef : new ArrayList<IReferencer>(dependencies)) { if (depRef instanceof IReferenceable && declaredRefs.contains(((IReferenceable) depRef).getReference())) { dependencies.remove(depRef); }//from w ww. ja va 2s . c o m // Also removing residual container references if (depRef instanceof ITypedObject && ((ITypedObject) depRef).getType() == IElementType .getInstance(IVersionContainer.TYPE_ID)) { dependencies.remove(depRef); } } } dependencies.removeAll(deletedReferencers); // Removing encapsulating dependencies: // A table containing a FK will generate 2 dependencies, one from the table, the // other from the FK // For all remaining dependencies for (IReferencer r : new ArrayList<IReferencer>(dependencies)) { // If one is a container of referenceable instances if (r instanceof IReferenceContainer) { // Then we check if this instance is one of the deleted referencers, // in which case we "assume" // that the upper dependency is no longer valid final Collection<IReferenceable> containedItems = ((IReferenceContainer) r).getReferenceMap() .values(); for (IReferenceable item : containedItems) { if (deletedReferencers.contains(item)) { dependencies.remove(r); } if (dependencies.contains(item)) { dependencies.remove(r); } } } } } return dependencies; }
From source file:org.onosproject.t3.impl.TroubleshootManager.java
/** * Traces the packet inside a device starting from an input connect point. * * @param trace the trace we are building * @param packet the packet we are tracing * @param in the input connect point. * @param isDualHomed true if the trace we are doing starts or ends in a dual homed host * @param completePath the path up until this device * @return updated trace//from www .j a v a 2 s. c om */ private StaticPacketTrace traceInDevice(StaticPacketTrace trace, TrafficSelector packet, ConnectPoint in, boolean isDualHomed, List<ConnectPoint> completePath) { boolean multipleRoutes = false; if (trace.getGroupOuputs(in.deviceId()) != null) { multipleRoutes = multipleRoutes(trace); } if (trace.getGroupOuputs(in.deviceId()) != null && !isDualHomed && !multipleRoutes) { log.debug("Trace already contains device and given outputs"); return trace; } log.debug("Packet {} coming in from {}", packet, in); //if device is not available exit here. if (!deviceService.isAvailable(in.deviceId())) { trace.addResultMessage("Device is offline " + in.deviceId()); computePath(completePath, trace, null); return trace; } //handle when the input is the controller //NOTE, we are using the input port as a convenience to carry the CONTROLLER port number even if // a packet in from the controller will not actually traverse the pipeline and have no such notion // as the input port. if (in.port().equals(PortNumber.CONTROLLER)) { StaticPacketTrace outputTrace = inputFromController(trace, in); if (outputTrace != null) { return trace; } } List<FlowEntry> flows = new ArrayList<>(); List<FlowEntry> outputFlows = new ArrayList<>(); List<Instruction> deferredInstructions = new ArrayList<>(); FlowEntry nextTableIdEntry = findNextTableIdEntry(in.deviceId(), -1); if (nextTableIdEntry == null) { trace.addResultMessage("No flow rules for device " + in.deviceId() + ". Aborting"); computePath(completePath, trace, null); trace.setSuccess(false); return trace; } TableId tableId = nextTableIdEntry.table(); FlowEntry flowEntry; boolean output = false; while (!output) { log.debug("Searching a Flow Entry on table {} for packet {}", tableId, packet); //get the rule that matches the incoming packet flowEntry = matchHighestPriority(packet, in, tableId); log.debug("Found Flow Entry {}", flowEntry); boolean isOfdpaHardware = TroubleshootUtils.hardwareOfdpaMap .getOrDefault(driverService.getDriver(in.deviceId()).name(), false); //if the flow entry on a table is null and we are on hardware we treat as table miss, with few exceptions if (flowEntry == null && isOfdpaHardware) { log.debug("Ofdpa Hw setup, no flow rule means table miss"); if (((IndexTableId) tableId).id() == 27) { //Apparently a miss but Table 27 on OFDPA is a fixed table packet = handleOfdpa27FixedTable(trace, packet); } //Finding next table to go In case of miss nextTableIdEntry = findNextTableIdEntry(in.deviceId(), ((IndexTableId) tableId).id()); log.debug("Next table id entry {}", nextTableIdEntry); //FIXME find better solution that enable granularity greater than 0 or all rules //(another possibility is max tableId) if (nextTableIdEntry == null && flows.size() == 0) { trace.addResultMessage("No matching flow rules for device " + in.deviceId() + ". Aborting"); computePath(completePath, trace, null); trace.setSuccess(false); return trace; } else if (nextTableIdEntry == null) { //Means that no more flow rules are present output = true; } else if (((IndexTableId) tableId).id() == 20) { //if the table is 20 OFDPA skips to table 50 log.debug("A miss on Table 20 on OFDPA means that we skip directly to table 50"); tableId = IndexTableId.of(50); } else if (((IndexTableId) tableId).id() == 40) { //if the table is 40 OFDPA skips to table 60 log.debug("A miss on Table 40 on OFDPA means that we skip directly to table 60"); tableId = IndexTableId.of(60); } else { tableId = nextTableIdEntry.table(); } } else if (flowEntry == null) { trace.addResultMessage( "Packet has no match on table " + tableId + " in device " + in.deviceId() + ". Dropping"); computePath(completePath, trace, null); trace.setSuccess(false); return trace; } else { //IF the table has a transition if (flowEntry.treatment().tableTransition() != null) { //update the next table we transitions to tableId = IndexTableId.of(flowEntry.treatment().tableTransition().tableId()); log.debug("Flow Entry has transition to table Id {}", tableId); flows.add(flowEntry); } else { //table has no transition so it means that it's an output rule if on the last table log.debug("Flow Entry has no transition to table, treating as last rule {}", flowEntry); flows.add(flowEntry); outputFlows.add(flowEntry); output = true; } //update the packet according to the immediate actions of this flow rule. packet = updatePacket(packet, flowEntry.treatment().immediate()).build(); //save the deferred rules for later deferredInstructions.addAll(flowEntry.treatment().deferred()); //If the flow requires to clear deferred actions we do so for all the ones we encountered. if (flowEntry.treatment().clearedDeferred()) { deferredInstructions.clear(); } //On table 10 OFDPA needs two rules to apply the vlan if none and then to transition to the next table. if (needsSecondTable10Flow(flowEntry, isOfdpaHardware)) { //Let's get the packet vlanId instruction VlanIdCriterion packetVlanIdCriterion = (VlanIdCriterion) packet .getCriterion(Criterion.Type.VLAN_VID); //Let's get the flow entry vlan mod instructions ModVlanIdInstruction entryModVlanIdInstruction = (ModVlanIdInstruction) flowEntry.treatment() .immediate().stream().filter(instruction -> instruction instanceof ModVlanIdInstruction) .findFirst().orElse(null); //If the entry modVlan is not null we need to make sure that the packet has been updated and there // is a flow rule that matches on same criteria and with updated vlanId if (entryModVlanIdInstruction != null) { FlowEntry secondVlanFlow = getSecondFlowEntryOnTable10(packet, in, packetVlanIdCriterion, entryModVlanIdInstruction); //We found the flow that we expected if (secondVlanFlow != null) { flows.add(secondVlanFlow); } else { trace.addResultMessage("Missing forwarding rule for tagged packet on " + in); computePath(completePath, trace, null); return trace; } } } } } //Creating a modifiable builder for the output packet Builder builder = DefaultTrafficSelector.builder(); packet.criteria().forEach(builder::add); //Adding all the flows to the trace trace.addFlowsForDevice(in.deviceId(), ImmutableList.copyOf(flows)); List<PortNumber> outputPorts = new ArrayList<>(); List<FlowEntry> outputFlowEntries = handleFlows(trace, packet, in, outputFlows, builder, outputPorts); log.debug("Handling Groups"); //Analyze Groups List<Group> groups = new ArrayList<>(); Collection<FlowEntry> nonOutputFlows = flows; nonOutputFlows.removeAll(outputFlowEntries); //Handling groups pointed at by immediate instructions for (FlowEntry entry : flows) { getGroupsFromInstructions(trace, groups, entry.treatment().immediate(), entry.deviceId(), builder, outputPorts, in, completePath); } //If we have deferred instructions at this point we handle them. if (deferredInstructions.size() > 0) { builder = handleDeferredActions(trace, packet, in, deferredInstructions, outputPorts, groups, completePath); } packet = builder.build(); log.debug("Output Packet {}", packet); return trace; }
From source file:org.apache.kylin.measure.topn.TopNMeasureType.java
@Override public CapabilityInfluence influenceCapabilityCheck(Collection<TblColRef> unmatchedDimensions, Collection<FunctionDesc> unmatchedAggregations, SQLDigest digest, MeasureDesc topN) { // TopN measure can (and only can) provide one numeric measure and one literal dimension // e.g. select seller, sum(gmv) from ... group by seller order by 2 desc limit 100 List<TblColRef> literalCol = getTopNLiteralColumn(topN.getFunction()); for (TblColRef colRef : literalCol) { if (digest.filterColumns.contains(colRef) == true) { // doesn't allow filtering by topn literal column return null; }/*from w w w. j av a 2 s . c o m*/ } if (digest.groupbyColumns.containsAll(literalCol) == false) return null; // check digest requires only one measure if (digest.aggregations.size() == 1) { // the measure function must be SUM FunctionDesc onlyFunction = digest.aggregations.iterator().next(); if (isTopNCompatibleSum(topN.getFunction(), onlyFunction) == false) return null; unmatchedDimensions.removeAll(literalCol); unmatchedAggregations.remove(onlyFunction); return new CapabilityInfluence() { @Override public double suggestCostMultiplier() { return 0.3; // make sure TopN get ahead of other matched realizations } }; } if (digest.aggregations.size() == 0) { // directly query the UHC column without sorting unmatchedDimensions.removeAll(literalCol); return new CapabilityInfluence() { @Override public double suggestCostMultiplier() { return 2.0; // topn can answer but with a higher cost } }; } return null; }