Example usage for java.util Set removeAll

List of usage examples for java.util Set removeAll

Introduction

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

Prototype

boolean removeAll(Collection<?> c);

Source Link

Document

Removes from this set all of its elements that are contained in the specified collection (optional operation).

Usage

From source file:edu.umass.cs.reconfiguration.Reconfigurator.java

/**
 * @param changeActives/*from  ww  w .  jav  a  2s .  c o m*/
 * @param ptasks
 * @return Messaging task if any.
 */
public GenericMessagingTask<?, ?>[] handleReconfigureActiveNodeConfig(
        ReconfigureActiveNodeConfig<NodeIDType> changeActives,
        ProtocolTask<NodeIDType, ReconfigurationPacket.PacketType, String>[] ptasks) {

    assert (changeActives.getServiceName().equals(AbstractReconfiguratorDB.RecordNames.AR_NODES.toString()));
    log.log(Level.INFO, "\n\n{0}\n{1} received {2} request {3} from initiator {4}\n{5}",
            new Object[] { separator, this, changeActives.getType(), changeActives.getSummary(),
                    changeActives.getIssuer(), separator });

    if (!this.isPermitted(changeActives)) {
        String errorMessage = " Impermissible node config change request";
        log.severe(this + errorMessage + ": " + changeActives);
        // this.sendRCReconfigurationErrorToInitiator(changeRC).setFailed().setResponseMessage(errorMessage);
        return (new GenericMessagingTask<InetSocketAddress, ServerReconfigurationPacket<NodeIDType>>(
                changeActives.getIssuer(), changeActives.setFailed().setResponseMessage(errorMessage)))
                        .toArray();
    } else if (this.nothingToDo(changeActives)) {
        String errorMessage = " Requested node additions or deletions already in place";
        log.log(Level.INFO, "{0} {1} : {2}", new Object[] { this, errorMessage, changeActives });
        // do not setFailed() in this case
        return (new GenericMessagingTask<InetSocketAddress, ServerReconfigurationPacket<NodeIDType>>(
                changeActives.getIssuer(), changeActives.setResponseMessage(errorMessage))).toArray();

    }
    // check first if NC is ready for reconfiguration
    ReconfigurationRecord<NodeIDType> activeNCRecord = this.DB
            .getReconfigurationRecord(changeActives.getServiceName());
    if (activeNCRecord == null)
        return null; // possible if startCleanSlate

    if (!activeNCRecord.isReady()) {
        String errorMessage = " Trying to conduct concurrent node config changes";
        log.warning(this + errorMessage + ": " + changeActives.getSummary() + "\n when activeNCRecord = "
                + activeNCRecord.getSummary());
        return (new GenericMessagingTask<InetSocketAddress, ServerReconfigurationPacket<NodeIDType>>(
                changeActives.getIssuer(), changeActives.setFailed().setResponseMessage(errorMessage)))
                        .toArray();
    }

    // else try to reconfigure even though it may still fail
    Set<NodeIDType> curActives = activeNCRecord.getActiveReplicas();
    Set<NodeIDType> newActives = new HashSet<NodeIDType>(curActives);
    newActives.addAll(changeActives.getAddedNodeIDs());
    newActives.removeAll(changeActives.getDeletedNodeIDs());
    // will use the nodeConfig before the change below.
    if (changeActives.newlyAddedNodes != null || changeActives.deletedNodes != null)
        this.initiateReconfiguration(AbstractReconfiguratorDB.RecordNames.AR_NODES.toString(), activeNCRecord,
                newActives, // this.consistentNodeConfig.getNodeSocketAddress
                (changeActives.getIssuer()), changeActives.getMyReceiver(), null, null, null,
                changeActives.newlyAddedNodes);

    return null;
}

From source file:org.openmrs.module.rheapocadapter.impl.HL7MessageTransformer.java

private void createOBRGroup(ORU_R01 r01, int orderObsCount, Encounter encounter) throws HL7Exception {

    Set<Obs> allObs = encounter.getAllObs();
    Set<Obs> rejectedObs = new HashSet<Obs>();
    Set<Obs> unrelatedObs = new HashSet<Obs>();
    Set<Obs> acceptedObs = new HashSet<Obs>();

    Iterator<Obs> it = allObs.iterator();

    while (it.hasNext()) {
        Obs obs = it.next();//from w  w w .  j  av a  2 s. co m
        if (obs.getObsGroup() != null && !rejectedObs.contains(obs)) {
            Obs parentObs = obs.getObsGroup();
            Set<Obs> childObs = parentObs.getGroupMembers();

            acceptedObs.add(parentObs);
            acceptedObs.addAll(childObs);

            it.remove();
            rejectedObs.addAll(childObs);

            parentObs.setVoided(true);
            createOBRGroupSegment(r01, encounter, parentObs, childObs, orderObsCount);
            orderObsCount++;

        }
    }

    allObs.removeAll(acceptedObs);

    if (allObs.size() > 0) {
        createOBRGroupSegment(r01, encounter, null, allObs, orderObsCount);
    }

}

From source file:com.evolveum.polygon.scim.GenericDataBuilder.java

/**
 * Builds a json object representation out of a provided set of
 * "multi value attributes". This type of attributes represent a complex
 * json object containing other key value pairs.
 * /*from  w  ww .  j a  va  2 s .c  om*/
 * @param multiValueAttribute
 *            A provided set of attributes.
 * @param json
 *            A json representation of the provided data set.
 * 
 * @return A json representation of the provided data set.
 */
public JSONObject buildMultivalueAttribute(Set<Attribute> multiValueAttribute, JSONObject json) {

    String mainAttributeName = "";

    List<String> checkedNames = new ArrayList<String>();

    Set<Attribute> specialMlAttributes = new HashSet<Attribute>();
    for (Attribute i : multiValueAttribute) {
        String attributeName = i.getName();
        String[] attributeNameParts = attributeName.split(DELIMITER); // e.g.
        // name.givenName

        if (checkedNames.contains(attributeNameParts[0])) {
        } else {
            JSONObject jObject = new JSONObject();
            mainAttributeName = attributeNameParts[0];
            checkedNames.add(mainAttributeName);
            for (Attribute j : multiValueAttribute) {
                String secondLoopAttributeName = j.getName();
                String[] secondLoopAttributeNameParts = secondLoopAttributeName.split(DELIMITER); // e.g.
                // name.givenName
                if (secondLoopAttributeNameParts[0].equals(mainAttributeName)
                        && !mainAttributeName.equals(SCHEMA)) {
                    jObject.put(secondLoopAttributeNameParts[1], AttributeUtil.getSingleValue(j));
                } else if (secondLoopAttributeNameParts[0].equals(mainAttributeName)
                        && mainAttributeName.equals(SCHEMA)) {
                    specialMlAttributes.add(j);

                }
            }
            if (specialMlAttributes.isEmpty()) {
                json.put(attributeNameParts[0], jObject);
            }
            //
            else {
                String sMlAttributeName = "No schema type";
                Boolean nameWasSet = false;

                for (Attribute specialAttribute : specialMlAttributes) {
                    String innerName = specialAttribute.getName();
                    String[] innerKeyParts = innerName.split(DELIMITER); // e.g.
                    // name.givenName
                    if (innerKeyParts[1].equals(TYPE) && !nameWasSet) {
                        sMlAttributeName = AttributeUtil.getAsStringValue(specialAttribute);
                        nameWasSet = true;
                    } else if (!innerKeyParts[1].equals(TYPE)) {

                        jObject.put(innerKeyParts[1], AttributeUtil.getSingleValue(specialAttribute));
                    }
                }
                if (nameWasSet) {

                    json.put(sMlAttributeName, jObject);
                    specialMlAttributes.removeAll(specialMlAttributes);

                } else {
                    LOGGER.error(
                            "Schema type not specified {0}. Error occurrence while translating user object attribute set: {0}",
                            sMlAttributeName);
                    throw new InvalidAttributeValueException(
                            "Schema type not specified. Error occurrence while translating user object attribute set");
                }

            }
        }
    }

    return json;
}

From source file:com.cloud.network.NetworkModelImpl.java

@Override
public Map<Provider, ArrayList<PublicIpAddress>> getProviderToIpList(Network network,
        Map<PublicIpAddress, Set<Service>> ipToServices) {
    NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
    if (!offering.isConserveMode()) {
        for (PublicIpAddress ip : ipToServices.keySet()) {
            Set<Service> services = new HashSet<Service>();
            services.addAll(ipToServices.get(ip));
            if (services != null && services.contains(Service.Firewall)) {
                services.remove(Service.Firewall);
            }// w w w .  ja  v a2s .c  om
            if (services != null && services.size() > 1) {
                throw new CloudRuntimeException("Ip " + ip.getAddress() + " is used by multiple services!");
            }
        }
    }
    Map<Service, Set<PublicIpAddress>> serviceToIps = new HashMap<Service, Set<PublicIpAddress>>();
    for (PublicIpAddress ip : ipToServices.keySet()) {
        for (Service service : ipToServices.get(ip)) {
            Set<PublicIpAddress> ips = serviceToIps.get(service);
            if (ips == null) {
                ips = new HashSet<PublicIpAddress>();
            }
            ips.add(ip);
            serviceToIps.put(service, ips);
        }
    }
    // TODO Check different provider for same IP
    Map<Provider, Set<Service>> providerToServices = getProviderServicesMap(network.getId());
    Map<Provider, ArrayList<PublicIpAddress>> providerToIpList = new HashMap<Provider, ArrayList<PublicIpAddress>>();
    for (Provider provider : providerToServices.keySet()) {
        if (!(getElementImplementingProvider(provider.getName()) instanceof IpDeployingRequester)) {
            continue;
        }
        Set<Service> services = providerToServices.get(provider);
        ArrayList<PublicIpAddress> ipList = new ArrayList<PublicIpAddress>();
        Set<PublicIpAddress> ipSet = new HashSet<PublicIpAddress>();
        for (Service service : services) {
            Set<PublicIpAddress> serviceIps = serviceToIps.get(service);
            if (serviceIps == null || serviceIps.isEmpty()) {
                continue;
            }
            ipSet.addAll(serviceIps);
        }
        Set<PublicIpAddress> sourceNatIps = serviceToIps.get(Service.SourceNat);
        if (sourceNatIps != null && !sourceNatIps.isEmpty()) {
            ipList.addAll(0, sourceNatIps);
            ipSet.removeAll(sourceNatIps);
        }
        ipList.addAll(ipSet);
        providerToIpList.put(provider, ipList);
    }
    return providerToIpList;
}

From source file:au.org.ala.delta.intkey.model.IntkeyContext.java

/**
 * Set what characters are excluded. All characters aside from those
 * specified will be included./*from   w ww.  jav  a 2s  .  co  m*/
 * 
 * @param excludedCharacters
 *            The set of excluded characters.
 */
public synchronized void setExcludedTaxa(Set<Integer> excludedTaxa) {
    Set<Integer> includedTaxa = new HashSet<Integer>();
    for (int i = 1; i < _dataset.getNumberOfTaxa() + 1; i++) {
        includedTaxa.add(i);
    }

    includedTaxa.removeAll(excludedTaxa);

    doSetIncludedTaxa(includedTaxa);

    if (excludedTaxa.size() == 1) {
        appendToLog(UIUtils.getResourceString("OneTaxonExcluded.log"));
    } else {
        appendToLog(UIUtils.getResourceString("MultipleTaxaExcluded.log", excludedTaxa.size()));
    }
}

From source file:au.org.ala.delta.intkey.model.IntkeyContext.java

/**
 * Set what characters are excluded. All characters aside from those
 * specified will be included./*from w w w  .  ja v a  2  s.  c  om*/
 * 
 * @param excludedCharacters
 *            The set of excluded characters.
 */
public synchronized void setExcludedCharacters(Set<Integer> excludedCharacters) {
    Set<Integer> includedCharacters = new HashSet<Integer>();
    for (int i = 1; i < _dataset.getNumberOfCharacters() + 1; i++) {
        includedCharacters.add(i);
    }

    includedCharacters.removeAll(excludedCharacters);

    doSetIncludedCharacters(includedCharacters);

    if (excludedCharacters.size() == 1) {
        appendToLog(UIUtils.getResourceString("OneCharacterExcluded.log"));
    } else {
        appendToLog(UIUtils.getResourceString("MultipleCharactersExcluded.log", excludedCharacters.size()));
    }
}

From source file:com.square.core.service.implementations.PersonneServiceImplementation.java

/**
 * Restaure l'email supprim pass en paramtre.
 * @param email l'email  restaurer/*from  ww  w. ja va2 s .c  o  m*/
 * @param nouvellesPersonnes les personnes associes au tlphone  restaurer
 * @param dateRestauration date  laquelle l'email a t restaur
 */
private Email restaurerEmail(Email email, Set<Personne> nouvellesPersonnes, Calendar dateRestauration) {
    email.setDateModification(dateRestauration);
    email.setSupprime(false);
    email.setDateSuppression(null);
    // On enlve liaisons oboltes entre les personnes et le tlphone avant de le restaurer
    final Set<Personne> personnes = new LinkedHashSet<Personne>(email.getPersonnes());
    personnes.removeAll(nouvellesPersonnes);
    for (Personne personne : personnes) {
        personne.removeEmail(email);
    }
    // On ajoute le tlphone pour les nouvelles personnes
    for (Personne personne : nouvellesPersonnes) {
        personne.addEMail(email);
    }
    return email;
}

From source file:com.square.core.service.implementations.PersonneServiceImplementation.java

/**
 * Restaure le tlphone pass en paramtre.
 * @param telephone le tlphone  restaurer
 * @param nouvellesPersonnes les personnes associes au tlphone  restaurer
 * @param dateRestauration la date de restauration
 * @return le tlphone restaur//from  w w  w  . j a  va 2 s . co  m
 */
private Telephone restaurerTelephone(Telephone telephone, Set<Personne> nouvellesPersonnes,
        Calendar dateRestauration) {
    telephone.setDateModification(dateRestauration);
    telephone.setSupprime(false);
    telephone.setDateSuppression(null);
    // On enlve liaisons oboltes entre les personnes et le tlphone avant de le restaurer
    final Set<Personne> personnes = new LinkedHashSet<Personne>(telephone.getPersonnes());
    personnes.removeAll(nouvellesPersonnes);
    for (Personne personne : personnes) {
        personne.removeTelephone(telephone);
    }
    // On ajoute le tlphone pour les nouvelles personnes
    for (Personne personne : nouvellesPersonnes) {
        personne.addTelephone(telephone);
    }
    return telephone;
}

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/deleteBatchInstance/{identifier}", method = RequestMethod.GET)
@ResponseBody/*from   w ww  .  jav  a  2 s .c  o m*/
public String deleteBatchInstance(@PathVariable("identifier") final String identifier,
        final HttpServletResponse resp, final HttpServletRequest req) {
    logger.info("Start processing web service for delete batch instance");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String userName = req.getUserPrincipal().getName(); // ToDo fetch from authentication header.
    Set<String> userRoles = userConnectivityService.getUserGroups(userName);
    boolean isSuccess = false;
    if (identifier != null && !identifier.isEmpty()) {
        final BatchInstance batchInstance = biService.getBatchInstanceByIdentifier(identifier);
        try {
            // Status for which a batch can be deleted:
            if (batchInstance != null && (batchInstance.getStatus().equals(BatchInstanceStatus.ERROR)
                    || batchInstance.getStatus().equals(BatchInstanceStatus.READY_FOR_REVIEW)
                    || batchInstance.getStatus().equals(BatchInstanceStatus.READY_FOR_VALIDATION)
                    || batchInstance.getStatus().equals(BatchInstanceStatus.RUNNING))) {

                Set<String> batchInstanceRoles = biService.getRolesForBatchInstance(batchInstance);
                if (batchInstanceRoles.removeAll(userRoles)) {
                    pluginPropertiesService.clearCache(identifier);
                    jbpmService.deleteProcessInstance(batchInstance.getProcessInstanceKey());
                    batchInstance.setStatus(BatchInstanceStatus.DELETED);
                    biService.updateBatchInstance(batchInstance);
                    final File uncFile = new File(batchInstance.getUncSubfolder());
                    if (null != uncFile) {
                        FileUtils.deleteDirectoryAndContentsRecursive(uncFile);
                    }
                    isSuccess = true;
                } else {
                    respStr = "User is not authorized to perform operation on this batch instance."
                            + identifier;
                }
            } else {
                respStr = "Either Batch instance does not exist with batch instance identifier " + identifier
                        + " or batch exists with incorrect status to be deleted. Batch instance should be of status:-"
                        + "ERROR, READY_FOR_REVIEW, READY_FOR_VALIDATION, RUNNING";
            }
        } catch (final Exception e) {
            respStr = "Error while deleting batch instance id:" + identifier
                    + ".Please check logs for further details." + e;

        }
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {

        }
    }
    return (isSuccess ? "Batch deleted successfully." : "Failure while deleting batch instance.");
}

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/restartBatchInstance/{batchInstanceIdentifier}/{restartAtModuleName}", method = RequestMethod.GET)
@ResponseBody//  www  .  jav  a 2 s  . c  om
public String restartBatchInstance(@PathVariable("batchInstanceIdentifier") final String identifier,
        @PathVariable("restartAtModuleName") String moduleName, final HttpServletResponse resp,
        final HttpServletRequest req) {
    logger.info("Start processing web service for restart batch instance");
    boolean isSuccess = false;
    String userName = req.getUserPrincipal().getName(); // ToDo fetch from authentication header.
    Set<String> userRoles = userConnectivityService.getUserGroups(userName);
    String respStr = WebServiceUtil.EMPTY_STRING;
    if (identifier != null && !identifier.isEmpty()) {
        BatchInstance batchInstance = biService.getBatchInstanceByIdentifier(identifier);
        // only batch instance with these status can be restarted
        if (batchInstance != null && (batchInstance.getStatus().equals(BatchInstanceStatus.ERROR)
                || batchInstance.getStatus().equals(BatchInstanceStatus.READY_FOR_REVIEW)
                || batchInstance.getStatus().equals(BatchInstanceStatus.READY_FOR_VALIDATION)
                || batchInstance.getStatus().equals(BatchInstanceStatus.RUNNING))) {

            Set<String> batchInstanceRoles = biService.getRolesForBatchInstance(batchInstance);
            if (batchInstanceRoles.removeAll(userRoles)) {
                String executedBatchInstanceModules = batchInstance.getExecutedModules();
                String[] executedModulesArray = executedBatchInstanceModules.split(";");
                final String batchClassIdentifier = biService.getBatchClassIdentifier(identifier);
                if (batchClassIdentifier != null) {
                    final BatchClassModule batchClassModuleItem = bcModuleService
                            .getBatchClassModuleByWorkflowName(batchClassIdentifier, moduleName);
                    if (batchClassModuleItem != null) {
                        for (String string : executedModulesArray) {
                            if (string.equalsIgnoreCase(String.valueOf(batchClassModuleItem.getId()))) {
                                isSuccess = true;
                                break;
                            }
                        }
                    }

                }
                final boolean isZipSwitchOn = bsService.isZipSwitchOn();
                logger.info("Zipped Batch XML switch is:" + isZipSwitchOn);

                final String activeModule = workflowService.getActiveModule(batchInstance);

                if (isSuccess) {
                    respStr = processRestartingBatchInternal(identifier, moduleName, respStr, batchInstance,
                            batchClassIdentifier, isZipSwitchOn, activeModule);
                } else {
                    isSuccess = false;
                    respStr = "Invalid parameter for restarting batch instance.";
                }
            } else {
                respStr = "User is not authorized to perform operation on this batch instance." + identifier;
            }
        } else {
            respStr = "Either Batch instance does not exist with batch instance identifier " + identifier
                    + " or batch exists with incorrect status to be restarted. Batch instance should be of status:-"
                    + "ERROR, READY_FOR_REVIEW, READY_FOR_VALIDATION, RUNNING";
            isSuccess = false;
        }
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {
        }
    }
    return (isSuccess ? "Batch restarted successfully." : "Failure while restarting batch instance.");
}