Example usage for java.util HashSet addAll

List of usage examples for java.util HashSet addAll

Introduction

In this page you can find the example usage for java.util HashSet addAll.

Prototype

boolean addAll(Collection<? extends E> c);

Source Link

Document

Adds all of the elements in the specified collection to this set if they're not already present (optional operation).

Usage

From source file:com.dell.asm.asmcore.asmmanager.client.util.ServiceTemplateClientUtil.java

/**
 * Returns all of the NetworkIds that are assigned in the ServiceTemplate.
 *
 * @param serviceTemplate the template whose NetworkIds will be returned.
 * @return all of the NetworkIds that are assigned in the ServiceTemplate.
 *//*w w  w . java2  s.com*/
public static Set<String> getNetworkIds(ServiceTemplate serviceTemplate) {

    HashSet<String> networkIds = new HashSet<String>();

    if (serviceTemplate != null) {
        for (ServiceTemplateComponent component : serviceTemplate.getComponents()) {

            if (ServiceTemplateComponent.ServiceTemplateComponentType.SERVER.equals(component.getType())
                    || ServiceTemplateComponent.ServiceTemplateComponentType.VIRTUALMACHINE
                            .equals(component.getType())) {
                for (ServiceTemplateCategory resource : component.getResources()) {
                    // if server networking category or esxi vm category or hyperv vm category
                    if (ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_NETWORKING_COMP_ID
                            .equals(resource.getId())
                            || ServiceTemplateSettingIDs.SERVICE_TEMPLATE_VM_RESOURCE.equals(resource.getId())
                            || ServiceTemplateSettingIDs.SERVICE_TEMPLATE_HV_VM_RESOURCE
                                    .equals(resource.getId())) {
                        for (ServiceTemplateSetting param : resource.getParameters()) {
                            // if server networking configuration parameter
                            if (ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_NETWORK_CONFIG_ID
                                    .equals(param.getId())) {
                                NetworkConfiguration configuration = ServiceTemplateClientUtil
                                        .deserializeNetwork(param.getValue());
                                networkIds.addAll(configuration.getAllNetworkIds());
                            } else if (ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_HYPERVISOR_NETWORK_ID
                                    .equals((param.getId()))
                                    || ServiceTemplateSettingIDs.SERVICE_TEMPLATE_VM_NETWORK_ID
                                            .equals(param.getId())) {
                                if (!(param.getValue().isEmpty() || param.getValue().equals("-1"))) {
                                    // value may be a comma-separated list, but if that is the case it will lead with a comma,
                                    // e.g. ,1,2,3.  The reject below gets rid of the initial empty element
                                    if (param != null && param.getNetworks() != null) {
                                        for (Network network : param.getNetworks()) {
                                            if (network != null && network.getId() != null) {
                                                networkIds.add(network.getId());
                                            }
                                        }
                                    }
                                    // NetworkIds are stored in a comma separated list as values of this param 
                                    for (String guid : param.getValue().split(",")) {
                                        if (!guid.isEmpty()) {
                                            networkIds.add(guid);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    return networkIds;
}

From source file:edu.ucla.cs.scai.canali.core.index.BuildIndex.java

private void propagatePropertiesToAncestorClasses(HashSet<Integer>[] classProperties, int claz) {
    for (int childClass : classChildren[claz]) {
        propagatePropertiesToAncestorClasses(classProperties, childClass);
    }/*from w  ww .  j av a  2  s  . co  m*/
    HashSet<Integer> properties = classProperties[claz];
    if (properties == null) {
        properties = new HashSet<>();
        classProperties[claz] = properties;
    }
    for (Integer child : classChildren[claz]) {
        properties.addAll(classProperties[child]);
    }
}

From source file:com.activecq.samples.workflow.impl.TagExplosionProcessWorkflow.java

/**
 * Work flow execute method *//from   w w  w. ja va 2s . c o m
 */

@Override
public void execute(WorkItem workItem, WorkflowSession workflowSession, MetaDataMap args)
        throws WorkflowException {
    log.debug("TAG EXPLODE");
    final WorkflowData workflowData = workItem.getWorkflowData();
    final String type = workflowData.getPayloadType();

    // Check if the payload is a path in the JCR
    if (!StringUtils.equals(type, "JCR_PATH")) {
        return;
    }

    Session session = workflowSession.getSession();
    // Get the path to the JCR resource from the payload
    String path = workflowData.getPayload().toString();

    // Get a ResourceResolver using the same permission set as the Workflow's executing Session
    ResourceResolver resolver = null;
    Map<String, Object> authInfo = new HashMap<String, Object>();
    authInfo.put(JcrResourceConstants.AUTHENTICATION_INFO_SESSION, session);

    // Initialize some variables
    final HashSet<String> newExplodedTags = new HashSet<String>();

    try {
        // Get the Workflow Sessions' resource resolver using the authInfo created above
        resolver = resourceResolverFactory.getResourceResolver(authInfo);

        // Get the Resource representing the WF payload
        final Resource resource = resolver.getResource(path);

        // Get the TagManager (using the same permission level as the Workflow's Session)
        final TagManager tagManager = resolver.adaptTo(TagManager.class);

        // Use custom implementation to find the resource to look for cq:tags and write the
        // custom property "tag-titles" to
        final Resource contentResource = getContentResource(resource);

        if (contentResource == null) {
            log.error("Could not find a valid content resource node for payload: {}", resource.getPath());
            return;
        }

        // Gain access to the content resource's properties
        final ValueMap properties = contentResource.adaptTo(ValueMap.class);

        // Get the full tag paths (namespace:path/to/tag) from the content resource
        // This only works on the cq:tags property
        final List<Tag> tags = getStringPropertyToTag(contentResource, FROM_PROPERTY, tagManager);

        // Get any previously applied Localized Tag Titles.
        // This is used to determine if changes if any updates are needed to this node.
        final String[] previousExplodedTags = properties.get(TO_PROPERTY, new String[] {});

        if (!tags.isEmpty()) {
            newExplodedTags.addAll(getExplodedTags(tags, newExplodedTags));
        }

        try {
            // Get the node in the JCR the payload points to
            final Node node = session.getNode(contentResource.getPath());

            // If the currently applied Tag Titles are the same as the derived Tag titles then skip!
            if (!isSame(newExplodedTags.toArray(new String[] {}), previousExplodedTags)) {
                // If changes have been made to the Tag Names, then apply to the tag-titles property
                // on the content resource.
                node.setProperty(TO_PROPERTY, newExplodedTags.toArray(new String[] {}));
            } else {
                log.debug("No change in Tags. Do not update this content resource.");
            }

        } catch (PathNotFoundException ex) {
            log.error(ex.getMessage());
        } catch (RepositoryException ex) {
            log.error(ex.getMessage());
        }
    } catch (LoginException ex) {
        log.error(ex.getMessage());
    } finally {
        // Clean up after yourself please!!!
        if (resolver != null) {
            resolver.close();
            resolver = null;
        }
    }
}

From source file:com.joyent.manta.http.MantaHttpHeaders.java

/**
 * Gets the header defining RBAC roles used for this object.
 *
 * @return roles associated with object//from  www.j  a  v a2s .  co  m
 */
public Set<String> getRoles() {
    final Object value = get(HTTP_ROLE_TAG);

    if (value == null) {
        return Collections.emptySet();
    }

    final HashSet<String> roles = new HashSet<>();

    if (value instanceof Iterable<?>) {
        ((Iterable<?>) value).forEach(o -> {
            if (o != null) {
                roles.add(o.toString());
            }
        });
    } else if (value.getClass().isArray()) {
        for (Object o : (Object[]) value) {
            if (o != null) {
                roles.add(o.toString());
            }
        }
    } else {
        String line = value.toString();
        roles.addAll(MantaUtils.fromCsv(line));
    }

    /* The result may come to us as a CSV. In that case we treat each
     * value separated by a comma as a single role.
     */
    if (roles.size() == 1) {
        String line = roles.iterator().next();
        roles.clear();
        roles.addAll(MantaUtils.fromCsv(line));
    }

    return Collections.unmodifiableSet(roles);
}

From source file:gr.demokritos.iit.cru.creativity.reasoning.diagrammatic.DiagrammaticComputationalTools.java

public HashSet<String> FindRelations(ArrayList<String> tri, int difficulty, String category)
        throws InstantiationException, IllegalAccessException, SQLException, ClassNotFoundException, Exception {
    HashSet<String> relations = new HashSet<String>();
    HashSet<String> TempRelations = new HashSet<String>();
    HashSet<String> newConcepts = new HashSet<String>();
    ArrayList<String> triple = new ArrayList<String>();

    ///---------translate
    for (String s : tri) {
        String h = Translator.bingTranslate(s, this.language, "en", "general");
        if (wn.getCommonPos(h) == null) {
            // System.out.println(s + " out " + h);
            return newConcepts; //if any element of the triple cannot be translated, relations cannot be found
        }//from w w  w  .j av a 2  s .  com
        triple.add(h);
    }
    // System.out.println(triple);
    //run abstraction for relation to find new relations and work with them
    String relation = triple.get(2);
    for (int i = 0; i < difficulty; i++) {
        TempRelations = ConceptGraphAbstractionEngine(relation);
        if (TempRelations.isEmpty()) {
            break;
        }
        relations = TempRelations;
        int pointer = new Random().nextInt(relations.size());
        int c = 0;
        for (String k : relations) {
            if (c == pointer) {
                relation = k;
            }
            c = c + 1;
        }
    }
    //take the similar concepts to the subject and the object of the triple
    if (category.equalsIgnoreCase("subsumption")) {
        newConcepts = ConceptGraphPolymerismEngine(triple.get(0));//wn.getMeronyms(triple.get(0));
        newConcepts.addAll(ConceptGraphPolymerismEngine(triple.get(1)));//wn.getMeronyms(triple.get(1));
    } else if (category.equalsIgnoreCase("supersumption")) {
        newConcepts = ConceptGraphAbstractionEngine(triple.get(0));// wn.getHyponymsAndHypernyms(triple.get(0));
        newConcepts.addAll(ConceptGraphAbstractionEngine(triple.get(1)));//wn.getHyponymsAndHypernyms(triple.get(1)));
    }
    System.out.println("new concepts " + newConcepts);
    //take concepts that have the relations found
    //  System.out.println("newConc " + newConcepts);
    for (String r : relations) {
        System.out.println(r);
        //System.out.println("relations " + r);
        HashSet<String> temp = FactRetriever(r, "relation");
        for (String g : temp) {
            //keep the subject and the object of the triples
            newConcepts.add(g.split("---")[0]);
            newConcepts.add(g.split("---")[1]);///////////////!!!!!!check if subj/obj=''
        }
    }

    //find relations based on the new concepts
    HashSet<String> newRelations = new HashSet<String>();
    for (String s : newConcepts) {
        // System.out.println("concepts " + s);
        newRelations.addAll(FactRetriever(s, "object"));
        newRelations.addAll(FactRetriever(s, "subject"));
    }
    // System.out.println("newRels " + newRelations);
    /*
     HashSet<String> rels = new HashSet<String>();
     ///---------translate
     if (!this.language.equalsIgnoreCase("en")) {
     for (String s : newRelations) {
     System.out.println(s);
     String n = Translator.bingTranslate(s, "en", this.language, "general");
     if (wn.getCommonPos(n) == null) {//if the word is not english
     rels.add(n);
     }
     }
     } else {
     rels.addAll(newRelations);
     }*/
    return newRelations;
}

From source file:org.alfresco.repo.tagging.UpdateTagScopesQuartzJob.java

protected void execute(final ActionService actionService,
        final UpdateTagScopesActionExecuter updateTagsAction) {
    // Process/*from www  .  jav  a  2 s  .c  om*/
    final ArrayList<NodeRef> tagNodes = new ArrayList<NodeRef>();
    final HashSet<NodeRef> handledTagNodes = new HashSet<NodeRef>();

    while (true) {
        // Fetch a batch of the pending changes
        AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>() {
            public Void doWork() throws Exception {
                tagNodes.clear();
                tagNodes.addAll(updateTagsAction.searchForTagScopesPendingUpdates());
                return null;
            }
        }, AuthenticationUtil.getSystemUserName());

        // If we're on our 2nd loop round for any of them, then skip them from now on
        // (This can happen if another thread is already processing one of them)
        Iterator<NodeRef> it = tagNodes.iterator();
        while (it.hasNext()) {
            NodeRef nodeRef = it.next();
            if (handledTagNodes.contains(nodeRef)) {
                it.remove();
                if (logger.isDebugEnabled())
                    logger.debug("Tag scope " + nodeRef
                            + " must be being processed by another Thread, not updating it");
            }
        }

        // Log what we found to process
        if (logger.isDebugEnabled()) {
            logger.debug("Checked for tag scopes with pending tag updates, found " + tagNodes);
        }

        // If we're out of tag scopes, stop!
        if (tagNodes.size() == 0)
            break;

        // Have the action run for these tag scope nodes
        // Needs to run synchronously
        Action action = actionService.createAction(UpdateTagScopesActionExecuter.NAME);
        action.setParameterValue(UpdateTagScopesActionExecuter.PARAM_TAG_SCOPES, (Serializable) tagNodes);
        actionService.executeAction(action, null, false, false);

        // Record the scopes we've just done
        handledTagNodes.addAll(tagNodes);
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.infomodel.RegistryObjectImpl.java

/**
 * Gest all Associations and their targets for which this object is a source.
 * Used by LifeCycleManagerImpl.saveObjects
 *
 *///ww w.  jav  a 2s.c  o  m
public HashSet<ExtensibleObject> getAssociationsAndAssociatedObjects() throws JAXRException {
    HashSet<ExtensibleObject> assObjects = new HashSet<ExtensibleObject>();

    // Automatically save any Association-s with an object in the save
    // list along with the target object of the Association per JAXR 1.0 spec.
    Collection<Association> asses = getAssociations();

    // Add the Association targets
    for (Iterator<Association> j = asses.iterator(); j.hasNext();) {
        AssociationImpl ass = (AssociationImpl) j.next();
        try {
            RegistryObject target = ass.getTargetObject();
            assObjects.add(target);
        } catch (UnresolvedReferenceException e) {
            //This happens when the targetObject is a remote ObjectRef
            //Handle this by adding the RegistryObjectRef instead
            RegistryObjectRef target = ass.getTargetObjectRef();
            assObjects.add(target);
        }
    }

    // Add also the Association-s themselves
    assObjects.addAll(asses);

    return assObjects;
}

From source file:com.impetus.ankush2.framework.monitor.AbstractMonitor.java

/**
 * Method to save graph view data.//from   w w  w .j  a  v  a  2s  .  c  om
 * 
 * @param legends
 *            the legends
 * @param publicIp
 *            the public ip
 * @param add
 *            the add
 */
private void saveGraphViewData(List<String> legends, String publicIp, boolean add) {
    // get Current user.
    User userDetails = getCurrentUser();
    // username.
    String userName = userDetails.getUsername();
    // monitoring manager objcet.
    MonitoringManager monitoringManager = new MonitoringManager();
    // node monitoring object.
    NodeMonitoring nodeMonitoring = monitoringManager.getMonitoringData(publicIp);

    HashMap userGraphViewMap = nodeMonitoring.getGraphViewData();
    // hash set of saved legends.
    HashSet graphViewData = (HashSet) userGraphViewMap.get(userName);
    // if set in null assign new hash set.
    if (graphViewData == null) {
        graphViewData = new HashSet();
    }

    if (add) {
        // adding new legends.
        graphViewData.addAll(legends);
    } else {
        // adding new legends.
        graphViewData.removeAll(legends);
    }

    userGraphViewMap.put(userName, graphViewData);
    // setting graphViewData.
    nodeMonitoring.setGraphViewData(userGraphViewMap);
    // saving in database
    monitoringManager.save(nodeMonitoring);
}

From source file:org.apache.ctakes.ytex.kernel.IntrinsicInfoContentEvaluatorImpl.java

/**
 * recursively compute the number of leaves. fill in the icInfoMap as we go
 * along//w  w  w  .  j  a  v  a 2s. c  o  m
 * 
 * @param concept
 *            concept for which we should get the leaves
 * @param leafCache
 *            cache of concept's leaves
 * @param icInfoMap
 *            to be updated with leaf counts
 * @param cg
 * @param w
 * @param visitedNodes
 *            list of nodes that have already been visited - we don't need
 *            to revisit them when getting the leaves
 * @return
 * @throws IOException
 */
private HashSet<Integer> getLeaves(ConcRel concept, SoftReference<HashSet<Integer>>[] leafCache,
        Map<String, IntrinsicICInfo> icInfoMap, ConceptGraph cg, BufferedWriter w,
        HashSet<Integer> visitedNodes) throws IOException {
    // look in cache
    SoftReference<HashSet<Integer>> refLeaves = leafCache[concept.getNodeIndex()];
    if (refLeaves != null && refLeaves.get() != null) {
        return refLeaves.get();
    }
    // not in cache - compute recursively
    HashSet<Integer> leaves = new HashSet<Integer>();
    leafCache[concept.getNodeIndex()] = new SoftReference<HashSet<Integer>>(leaves);
    if (concept.isLeaf()) {
        // for leaves, just add the concept id
        leaves.add(concept.getNodeIndex());
    } else {
        IntrinsicICInfo icInfo = icInfoMap.get(concept.getConceptID());
        // have we already computed the leaf count for this node?
        // if yes, then we can ignore previously visited nodes
        // if no, then compute it now and revisit previously visited nodes
        // if we have to
        boolean needLeaves = (icInfo != null && icInfo.getLeafCount() == 0);
        HashSet<Integer> visitedNodesLocal = visitedNodes;
        if (needLeaves || visitedNodesLocal == null) {
            // allocate a set to keep track of nodes we've already visited
            // so that we don't revisit them. if we have already computed
            // this node's leaf count then we reuse whatever the caller gave
            // us if non null, else allocate a new one.
            // if we haven't already computed this node's leaf count,
            // allocate a new set to avoid duplications in the traversal for
            // this node
            visitedNodesLocal = new HashSet<Integer>();
        }
        // for inner nodes, recurse
        for (ConcRel child : concept.getChildren()) {
            // if we've already visited a node, then don't bother adding
            // that node's leaves - we already have them
            if (!visitedNodesLocal.contains(child.getNodeIndex())) {
                leaves.addAll(getLeaves(child, leafCache, icInfoMap, cg, w, visitedNodesLocal));
            }
        }
        // add this node to the set of visited nodes so we know not to
        // revisit. This is only of importance if the caller gave us
        // a non-empty set.
        if (visitedNodes != null && visitedNodes != visitedNodesLocal) {
            visitedNodes.add(concept.getNodeIndex());
            visitedNodes.addAll(visitedNodesLocal);
        }
        // update the leaf count if we haven't done so already
        if (needLeaves) {
            icInfo.setLeafCount(leaves.size());
            // output leaves if desired
            if (w != null) {
                w.write(concept.getConceptID());
                w.write("\t");
                w.write(Integer.toString(leaves.size()));
                w.write("\t");
                Iterator<Integer> iter = leaves.iterator();
                while (iter.hasNext()) {
                    w.write(cg.getConceptList().get(iter.next()).getConceptID());
                    w.write(" ");
                }
                w.newLine();
            }
        }
    }
    return leaves;
}

From source file:com.chinamobile.bcbsp.bspcontroller.JobInProgress.java

@Override
public int getCheckNum() {
    // ljn add for migrate staff.
    if (this.openMigrateMode && this.migrateFlag) {
        LOG.info("ljn test : migrateFlag is true");
    }//from   ww w  .j av a  2  s  . c  om
    HashSet<String> workersAfter = new HashSet<String>();
    workersAfter.addAll(convert().values());
    // if (this.openMigrateMode && this.migrateFlag) {
    if (workersAfter.size() == this.workersToStaffs.size()) {
        return this.workersToStaffs.size();
    } else {
        return workersAfter.size();
    }
    // } else {
    // return this.workersToStaffs.size();
    // }

}