Example usage for java.util Collection addAll

List of usage examples for java.util Collection addAll

Introduction

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

Prototype

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

Source Link

Document

Adds all of the elements in the specified collection to this collection (optional operation).

Usage

From source file:com.haulmont.cuba.gui.data.impl.DsContextImpl.java

protected Map<DataSupplier, Collection<Datasource<Entity>>> collectCommitData() {
    Collection<Datasource> datasources = new ArrayList<>();

    for (DsContext childDsContext : children) {
        datasources.addAll(childDsContext.getAll());
    }/* w  ww .  java2  s. c om*/
    datasources.addAll(datasourceMap.values());

    final Map<DataSupplier, Collection<Datasource<Entity>>> commitDatasources = new HashMap<>();

    for (Datasource datasource : datasources) {
        if (Datasource.CommitMode.DATASTORE == datasource.getCommitMode() && datasource.isAllowCommit()
                && (datasource.isModified()
                        || !((DatasourceImplementation) datasource).getItemsToCreate().isEmpty())) {

            final DataSupplier dataservice = datasource.getDataSupplier();
            Collection<Datasource<Entity>> collection = commitDatasources.get(dataservice);
            if (collection == null) {
                collection = new ArrayList<>();
                commitDatasources.put(dataservice, collection);
            }
            collection.add(datasource);
        }
    }
    return commitDatasources;
}

From source file:net.ontopia.topicmaps.impl.basic.index.OccurrenceIndex.java

/**
 * INTERNAL: utility method used to extract all keys from the sorted
 * map that matches the prefix and aggregate all values stores as
 * entry values./* ww w.j a  v a  2s. c o  m*/
 */
private <E> Collection<E> extractPrefixValues(CollectionSortedMap<String, E> map, String prefix) {
    Collection<E> result = null;
    SortedMap<String, Collection<E>> tail = map.tailMap(prefix);
    Iterator<String> iter = tail.keySet().iterator();
    while (iter.hasNext()) {
        String key = iter.next();
        if (key == null || !key.startsWith(prefix)) {
            break;
        }
        // add values to result
        if (result == null)
            result = new HashSet<E>();
        Collection<E> c = map.get(key);
        result.addAll(c);

    }
    return (result == null ? new HashSet<E>() : result);
}

From source file:org.biopax.validator.rules.NextStepShareParticipantsRule.java

Collection<Entity> getParticipants(Process process, Collection<Process> visited) {
    Collection<Entity> ret = new HashSet<Entity>();

    // escape infinite loop
    if (visited.contains(process)) {
        //"Step Processes Form a Loop!"
        return ret; // empty
    }//from   ww  w .j  av  a  2s  . co  m
    visited.add(process);

    if (process instanceof Interaction) {
        for (Entity pat : ((Interaction) process).getParticipant()) {
            if (pat instanceof PhysicalEntity || pat instanceof Gene)
                ret.add(pat);
        }
    } else { // a pathway
        for (Process p : ((Pathway) process).getPathwayComponent()) {
            ret.addAll(getParticipants(p, visited));
        }
    }

    return ret;
}

From source file:ar.com.fluxit.jqa.JQASensor.java

@Override
public void analyse(Project project, SensorContext context) {
    try {/* www . java2  s . co m*/
        final RulesContext rulesContext = RulesContextLoader.INSTANCE.load();
        final File buildDirectory = project.getFileSystem().getBuildOutputDir();
        final Collection<File> classFiles = FileUtils.listFiles(buildDirectory,
                new SuffixFileFilter(RulesContextChecker.CLASS_SUFFIX), TrueFileFilter.INSTANCE);
        final Collection<File> classPath = new ArrayList<File>();
        @SuppressWarnings("unchecked")
        final Set<Artifact> artifacts = getProject().getArtifacts();
        for (final Artifact artifact : artifacts) {
            classPath.add(artifact.getFile());
        }
        // Add project classes to classpath
        if (project.getFileSystem().getBuildOutputDir() != null) {
            classPath.add(project.getFileSystem().getBuildOutputDir());
        }
        if (project.getFileSystem().getTestDirs() != null) {
            classPath.addAll(project.getFileSystem().getTestDirs());
        }
        final File sourcesDir = new File((String) getProject().getCompileSourceRoots().get(0));
        LOGGER.info("SourcesDir = " + sourcesDir.getPath());
        final CheckingResult check = RulesContextChecker.INSTANCE.check(getProject().getArtifactId(),
                classFiles, classPath, rulesContext, new File[] { sourcesDir },
                getSourceJavaVersion(getProject()), LOGGER);
        addViolations(context, check);
    } catch (final Exception e) {
        LOGGER.error("An error occurred", e);
        throw new IllegalStateException(e);
    }
}

From source file:hoot.services.controllers.osm.ChangesetDbWriter.java

/**
 * Performs the OSM element database update portion for a changeset upload
 * request and returns the elements modified
 * <p>//ww  w .ja  v a2  s  .  com
 * Unlike OSM, we don't keep track of multiple versions of the same element.
 * <p>
 * OSM element udpate process
 * <p>
 * create = insert new modify = update existing + insert new
 * <p>
 * hoot element update process
 * <p>
 * create = insert new modify = update existing
 *
 * @param changesetId
 *            ID of the changeset being uploaded to
 * @param changesetDoc
 *            changeset contents
 * @return changeset upload response
 */
public Document write(long mapId, long changesetId, Document changesetDoc) throws Exception {
    logger.debug("Uploading data for changeset with ID: {} ...", changesetId);

    changeset = new Changeset(mapId, changesetId, conn);
    this.requestChangesetId = changeset.getId();
    changeset.verifyAvailability();

    if (changeset.requestChangesExceedMaxElementThreshold(changesetDoc)) {
        throw new RuntimeException("Changeset maximum element threshold exceeded.");
    }

    requestChangesetMapId = mapId;

    Collection<XmlSerializable> changesetDiffElements = new ArrayList<>();
    changesetDiffElements.addAll(write(changesetDoc));

    return writeResponse(changesetId, (List<XmlSerializable>) changesetDiffElements);
}

From source file:de.tbuchloh.kiskis.gui.treeview.TreeView.java

/**
 * @return gets all the displayed tree nodes
 *//*w ww  .j  av a 2  s.  com*/
protected Collection<MyTreeNode> getAllNodes() {
    final Queue<MyTreeNode> treeNodes = new LinkedList<MyTreeNode>();
    treeNodes.add(getRoot());
    final Collection<MyTreeNode> r = new LinkedList<MyTreeNode>();
    r.add(getRoot());
    while (!treeNodes.isEmpty()) {
        final MyTreeNode node = treeNodes.poll();
        final List<MyTreeNode> children = Collections.list(node.children());
        treeNodes.addAll(children);
        r.addAll(children);
    }
    return r;
}

From source file:gmusic.api.impl.GoogleMusicAPI.java

private final Collection<Song> getSongs(String continuationToken)
        throws ClientProtocolException, IOException, URISyntaxException {
    Collection<Song> chunkedCollection = new ArrayList<Song>();

    Map<String, String> fields = new HashMap<String, String>();
    fields.put("json", "{\"continuationToken\":\"" + continuationToken + "\"}");

    FormBuilder form = new FormBuilder();
    form.addFields(fields);/*from w  w  w  .  j ava2  s . c  o  m*/
    form.close();

    Playlist chunk = JSON.Deserialize(
            client.dispatchPost(new URI("https://play.google.com/music/services/loadalltracks"), form),
            Playlist.class);
    chunkedCollection.addAll(chunk.getPlaylist());

    if (!Strings.isNullOrEmpty(chunk.getContinuationToken())) {
        chunkedCollection.addAll(getSongs(chunk.getContinuationToken()));
    }
    return chunkedCollection;
}

From source file:com.clarkparsia.empire.annotation.RdfGenerator.java

/**
 * Return the given Java bean as a set of RDF triples
 * @param theObj the object//from   ww w  .ja  v a 2s .co m
 * @return the object represented as RDF triples
 * @throws InvalidRdfException thrown if the object cannot be transformed into RDF.
 */
public static Graph asRdf(final Object theObj) throws InvalidRdfException {
    if (theObj == null) {
        return null;
    }

    Object aObj = theObj;

    if (aObj instanceof ProxyHandler) {
        aObj = ((ProxyHandler) aObj).mProxy.value();
    } else {
        try {
            if (aObj.getClass().getDeclaredField("handler") != null) {
                Field aProxy = aObj.getClass().getDeclaredField("handler");
                aObj = ((ProxyHandler) BeanReflectUtil.safeGet(aProxy, aObj)).mProxy.value();
            }
        } catch (InvocationTargetException e) {
            // this is probably an error, we know its a proxy object, but can't get the proxied object
            throw new InvalidRdfException("Could not access proxy object", e);
        } catch (NoSuchFieldException e) {
            // this is probably ok.
        }
    }

    RdfsClass aClass = asValidRdfClass(aObj);

    Resource aSubj = id(aObj);

    addNamespaces(aObj.getClass());

    GraphBuilder aBuilder = new GraphBuilder();

    Collection<AccessibleObject> aAccessors = new HashSet<AccessibleObject>();
    aAccessors.addAll(getAnnotatedFields(aObj.getClass()));
    aAccessors.addAll(getAnnotatedGetters(aObj.getClass(), true));

    try {
        ResourceBuilder aRes = aBuilder.instance(
                aBuilder.getValueFactory().createURI(PrefixMapping.GLOBAL.uri(aClass.value())), aSubj);

        for (AccessibleObject aAccess : aAccessors) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Getting rdf for : {}", aAccess);
            }

            AsValueFunction aFunc = new AsValueFunction(aAccess);

            if (aAccess.isAnnotationPresent(Transient.class)
                    || (aAccess instanceof Field && Modifier.isTransient(((Field) aAccess).getModifiers()))) {

                // transient fields or accessors with the Transient annotation do not get converted.
                continue;
            }

            RdfProperty aPropertyAnnotation = BeanReflectUtil.getAnnotation(aAccess, RdfProperty.class);
            String aBase = "urn:empire:clark-parsia:";
            if (aRes instanceof URI) {
                aBase = ((URI) aRes).getNamespace();
            }

            URI aProperty = aPropertyAnnotation != null
                    ? aBuilder.getValueFactory()
                            .createURI(PrefixMapping.GLOBAL.uri(aPropertyAnnotation.value()))
                    : (aAccess instanceof Field
                            ? aBuilder.getValueFactory().createURI(aBase + ((Field) aAccess).getName())
                            : null);

            boolean aOldAccess = aAccess.isAccessible();
            setAccessible(aAccess, true);

            Object aValue = get(aAccess, aObj);

            setAccessible(aAccess, aOldAccess);

            if (aValue == null || aValue.toString().equals("")) {
                continue;
            } else if (Collection.class.isAssignableFrom(aValue.getClass())) {
                @SuppressWarnings("unchecked")
                List<Value> aValueList = asList(aAccess, (Collection<?>) Collection.class.cast(aValue));

                if (aValueList.isEmpty()) {
                    continue;
                }

                if (aPropertyAnnotation.isList()) {
                    aRes.addProperty(aProperty, aValueList);
                } else {
                    for (Value aVal : aValueList) {
                        aRes.addProperty(aProperty, aVal);
                    }
                }
            } else {
                aRes.addProperty(aProperty, aFunc.apply(aValue));
            }
        }
    } catch (IllegalAccessException e) {
        throw new InvalidRdfException(e);
    } catch (RuntimeException e) {
        throw new InvalidRdfException(e);
    } catch (InvocationTargetException e) {
        throw new InvalidRdfException("Cannot invoke method", e);
    }

    return aBuilder.graph();
}

From source file:de.hybris.platform.servicelayer.interceptor.RemoveInterceptorTest.java

@Test
public void testRemovePartOfAttributes() {
    final CountryModel germany = i18nService.getCountry("DE");
    Assert.assertNotNull(germany);/*from www .j  av a  2 s.  c o m*/

    final CountryModel usa = i18nService.getCountry("US");
    Assert.assertNotNull(usa);

    final Collection<RegionModel> beforeCollection = new HashSet<RegionModel>(germany.getRegions());
    beforeCollection.addAll(usa.getRegions());
    Assert.assertFalse(beforeCollection.isEmpty());

    for (final RegionModel reg : beforeCollection) {
        Assert.assertFalse(modelService.isRemoved(reg));
    }

    modelService.removeAll(Arrays.asList(germany, usa));

    for (final RegionModel reg : beforeCollection) {
        Assert.assertTrue(modelService.isRemoved(reg));
    }
    Assert.assertTrue(modelService.isRemoved(germany));
    Assert.assertTrue(modelService.isRemoved(usa));
    Assert.assertEquals(gotRegionInterceptors.size(), beforeCollection.size());
}

From source file:com.stormpath.spring.security.provider.StormpathAuthenticationProvider.java

protected Collection<GrantedAuthority> getGrantedAuthorities(Account account) {
    Collection<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();

    GroupList groups = account.getGroups();

    for (Group group : groups) {
        Set<GrantedAuthority> groupGrantedAuthorities = resolveGrantedAuthorities(group);
        grantedAuthorities.addAll(groupGrantedAuthorities);

        Set<Permission> groupPermissions = resolvePermissions(group);
        grantedAuthorities.addAll(groupPermissions);
    }/*from   w  w  w.  jav  a 2 s.  c  o  m*/

    Set<GrantedAuthority> accountGrantedAuthorities = resolveGrantedAuthorities(account);
    grantedAuthorities.addAll(accountGrantedAuthorities);

    Set<Permission> accountPermissions = resolvePermissions(account);
    for (GrantedAuthority permission : accountPermissions) {
        grantedAuthorities.add(permission);
    }

    return grantedAuthorities;
}