java.util.Collection

Here are the examples of the java api class java.util.Collection taken from open source projects.

1. FilterTest#testCollection()

Project: jdepend
Source File: FilterTest.java
View license
public void testCollection() throws IOException {
    Collection filters = new ArrayList();
    filters.add("java.*");
    filters.add("javax.*");
    filters.add("sun.*");
    filters.add("com.sun.*");
    filters.add("com.xyz.tests.*");
    PackageFilter filter = new PackageFilter(filters);
    assertEquals(5, filter.getFilters().size());
    assertFiltersExist(filter);
}

2. MetaDataTest#testNestedCollectionSerialization()

Project: bugsnag-android
Source File: MetaDataTest.java
View license
public void testNestedCollectionSerialization() throws JSONException, IOException {
    Collection childList = new LinkedList<String>();
    childList.add("james");
    childList.add("test");
    Collection list = new LinkedList();
    list.add(childList);
    MetaData metaData = new MetaData();
    metaData.addToTab("example", "list", list);
    JSONObject metaDataJson = streamableToJson(metaData);
    assertTrue(metaDataJson.has("example"));
    JSONArray childListJson = metaDataJson.getJSONObject("example").getJSONArray("list").getJSONArray(0);
    assertEquals(2, childListJson.length());
    assertEquals("james", childListJson.get(0));
    assertEquals("test", childListJson.get(1));
}

3. TreeMapTest#test_values()

Project: j2objc
Source File: TreeMapTest.java
View license
/**
     * @tests java.util.TreeMap#values()
     */
public void test_values() {
    // Test for method java.util.Collection java.util.TreeMap.values()
    Collection vals = tm.values();
    vals.iterator();
    assertTrue("Returned collection of incorrect size", vals.size() == objArray.length);
    for (Object element : objArray) {
        assertTrue("Collection contains incorrect elements", vals.contains(element));
    }
    TreeMap myTreeMap = new TreeMap();
    for (int i = 0; i < 100; i++) {
        myTreeMap.put(objArray[i], objArray[i]);
    }
    Collection values = myTreeMap.values();
    new Support_UnmodifiableCollectionTest("Test Returned Collection From TreeMap.values()", values).runTest();
    values.remove(new Integer(0));
    assertTrue("Removing from the values collection should remove from the original map", !myTreeMap.containsValue(new Integer(0)));
}

4. ProjectionsTests#createTestVars()

Project: mvel
Source File: ProjectionsTests.java
View license
private Map createTestVars() {
    Collection users = new ArrayList();
    User user1 = new User("John");
    user1.getFamilyMembers().add(new User("George"));
    User user2 = new User("Bob");
    User user3 = new User("Cindy");
    user3.getFamilyMembers().add(new User("Michael"));
    user3.getFamilyMembers().add(new User("Laura"));
    users.add(user1);
    users.add(user2);
    users.add(user3);
    Map vars = new HashMap();
    vars.put("users", users);
    return vars;
}

5. SpringSecurityUserProviderTest#getCurrentUserWillReturnFeatureAdminWhenAuthoritiesContainFeatureAdminAuthority()

View license
@Test
public void getCurrentUserWillReturnFeatureAdminWhenAuthoritiesContainFeatureAdminAuthority() throws Exception {
    // arrange
    Collection authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority("ROLE_1"));
    authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    authorities.add(new SimpleGrantedAuthority("ROLE_2"));
    when(authentication.getAuthorities()).thenReturn(authorities);
    // act
    FeatureUser user = userProvider.getCurrentUser();
    // assert
    assertThat(user.isFeatureAdmin(), is(true));
}

6. PropertyDescriptorPlus#setList()

View license
/**
     * Set the property value for the collection case.
     *
     * @param targetBean
     * @param propValue
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws JAXBWrapperException
     */
private void setList(Object targetBean, Object propValue) throws InvocationTargetException, IllegalAccessException, JAXBWrapperException {
    // For the List<T> case, there is no setter. 
    // You are supposed to use the getter to obtain access to the collection and then add the collection
    Collection value = asCollection(propValue, descriptor.getPropertyType());
    Collection collection = (Collection) get(targetBean);
    // Now add our our object to the collection
    collection.clear();
    if (propValue != null) {
        collection.addAll(value);
    }
}

7. JDBCWorkerPersistenceTestAbstract#testGetByKey()

View license
public void testGetByKey() throws Exception {
    time = new Date(System.currentTimeMillis());
    period = new Long(1000);
    WorkInfo workInfo1 = new WorkInfo(key, new Long(1), userInfo, time, period, true);
    WorkInfo workInfo2 = new WorkInfo(key, new Long(2), userInfo, time, period, true);
    jdbcWorkerPersistence.save(workInfo1);
    jdbcWorkerPersistence.save(workInfo2);
    Collection idsAll = jdbcWorkerPersistence.getIdsByKey(key, null);
    assertEquals(2, idsAll.size());
    Collection ids1 = jdbcWorkerPersistence.getIdsByKey(key, new Long(1));
    assertEquals(1, ids1.size());
    Collection ids2 = jdbcWorkerPersistence.getIdsByKey(key, new Long(2));
    assertEquals(1, ids2.size());
}

8. HashMapTest#test_values()

Project: j2objc
Source File: HashMapTest.java
View license
/**
     * java.util.HashMap#values()
     */
public void test_values() {
    // Test for method java.util.Collection java.util.HashMap.values()
    Collection c = hm.values();
    assertTrue("Returned collection of incorrect size()", c.size() == hm.size());
    for (int i = 0; i < objArray.length; i++) assertTrue("Returned collection does not contain all keys", c.contains(objArray[i]));
    HashMap myHashMap = new HashMap();
    for (int i = 0; i < 100; i++) myHashMap.put(objArray2[i], objArray[i]);
    Collection values = myHashMap.values();
    new Support_UnmodifiableCollectionTest("Test Returned Collection From HashMap.values()", values).runTest();
    values.remove(new Integer(0));
    assertTrue("Removing from the values collection should remove from the original map", !myHashMap.containsValue(new Integer(0)));
}

9. HashtableTest#test_values()

Project: j2objc
Source File: HashtableTest.java
View license
/**
     * java.util.Hashtable#values()
     */
public void test_values() {
    // Test for method java.util.Collection java.util.Hashtable.values()
    Collection c = ht10.values();
    Enumeration e = elmVector.elements();
    while (e.hasMoreElements()) assertTrue("Returned incorrect values", c.contains(e.nextElement()));
    // BEGIN android-removed
    // implementation dependent
    //        assertEquals("Not synchronized",
    //                "java.util.Collections$SynchronizedCollection", c.getClass().getName());
    // END android-removed
    Hashtable myHashtable = new Hashtable();
    for (int i = 0; i < 100; i++) myHashtable.put(new Integer(i), new Integer(i));
    Collection values = myHashtable.values();
    new Support_UnmodifiableCollectionTest("Test Returned Collection From Hashtable.values()", values).runTest();
    values.remove(new Integer(0));
    assertTrue("Removing from the values collection should remove from the original map", !myHashtable.containsValue(new Integer(0)));
}

10. LinkedHashMapTest#test_values()

Project: j2objc
Source File: LinkedHashMapTest.java
View license
/**
     * java.util.LinkedHashMap#values()
     */
public void test_values() {
    // Test for method java.util.Collection java.util.LinkedHashMap.values()
    Collection c = hm.values();
    assertTrue("Returned collection of incorrect size()", c.size() == hm.size());
    for (int i = 0; i < objArray.length; i++) assertTrue("Returned collection does not contain all keys", c.contains(objArray[i]));
    LinkedHashMap myLinkedHashMap = new LinkedHashMap();
    for (int i = 0; i < 100; i++) myLinkedHashMap.put(objArray2[i], objArray[i]);
    Collection values = myLinkedHashMap.values();
    new Support_UnmodifiableCollectionTest("Test Returned Collection From LinkedHashMap.values()", values).runTest();
    values.remove(new Integer(0));
    assertTrue("Removing from the values collection should remove from the original map", !myLinkedHashMap.containsValue(new Integer(0)));
}

11. VectorTest#test_containsAllLjava_util_Collection()

Project: j2objc
Source File: VectorTest.java
View license
/**
	 * @tests java.util.Vector#containsAll(java.util.Collection)
	 */
public void test_containsAllLjava_util_Collection() {
    // Test for method boolean
    // java.util.Vector.containsAll(java.util.Collection)
    Collection s = new HashSet();
    for (int i = 0; i < 100; i++) s.add("Test " + i);
    assertTrue("Returned false for valid collection", tVector.containsAll(s));
    s.add(null);
    assertTrue("Returned true for invlaid collection containing null", !tVector.containsAll(s));
    tVector.add(25, null);
    assertTrue("Returned false for valid collection containing null", tVector.containsAll(s));
    s = new HashSet();
    s.add(new Object());
    assertTrue("Returned true for invalid collection", !tVector.containsAll(s));
}

12. VectorTest#test_retainAllLjava_util_Collection()

Project: j2objc
Source File: VectorTest.java
View license
/**
	 * @tests java.util.Vector#retainAll(java.util.Collection)
	 */
public void test_retainAllLjava_util_Collection() {
    // Test for method boolean
    // java.util.Vector.retainAll(java.util.Collection)
    Object o = tVector.firstElement();
    tVector.add(null);
    Collection s = new HashSet();
    s.add(o);
    s.add(null);
    tVector.retainAll(s);
    assertTrue("Retained items other than specified", tVector.size() == 2 && tVector.contains(o) && tVector.contains(null));
}

13. ServerGroupFactoryTest#testListNoAssociatedAdmins()

View license
public void testListNoAssociatedAdmins() throws Exception {
    TestUtils.flushAndEvict(managedGroup);
    Collection groups = ServerGroupFactory.listNoAdminGroups(managedGroup.getOrg());
    int initSize = groups.size();
    ServerGroup sg1 = ServerGroupFactory.create(ServerGroupTestUtils.NAME + "ALPHA", ServerGroupTestUtils.DESCRIPTION, user.getOrg());
    Collection groups1 = ServerGroupFactory.listNoAdminGroups(sg1.getOrg());
    assertEquals(initSize + 1, groups1.size());
    groups.add(sg1);
    assertEquals(new HashSet(groups), new HashSet(groups1));
}

14. ServerGroupManagerTest#testListNoAssociatedAdmins()

View license
public void testListNoAssociatedAdmins() throws Exception {
    user.addPermanentRole(RoleFactory.SYSTEM_GROUP_ADMIN);
    ServerGroup sg = manager.create(user, NAME, DESCRIPTION);
    TestUtils.flushAndEvict(sg);
    try {
        manager.listNoAdminGroups(user);
        fail("ORG ADmin permission needed for this!");
    } catch (Exception e) {
    }
    user.addPermanentRole(RoleFactory.ORG_ADMIN);
    Collection groups = manager.listNoAdminGroups(user);
    int initSize = groups.size();
    ServerGroup sg1 = ServerGroupFactory.create(NAME + "ALPHA", DESCRIPTION, user.getOrg());
    TestUtils.flushAndEvict(sg1);
    Collection groups1 = manager.listNoAdminGroups(user);
    assertEquals(initSize + 1, groups1.size());
    groups.add(sg1);
    assertEquals(new HashSet(groups), new HashSet(groups1));
}

15. SpringSecurityUserProviderTest#getCurrentUserWillReturnNormalUserWhenAuthoritiesDoNotContainFeatureAdminAuthority()

View license
@Test
public void getCurrentUserWillReturnNormalUserWhenAuthoritiesDoNotContainFeatureAdminAuthority() throws Exception {
    // arrange
    Collection authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority("ROLE_1"));
    authorities.add(new SimpleGrantedAuthority("ROLE_2"));
    when(authentication.getAuthorities()).thenReturn(authorities);
    // act
    FeatureUser user = userProvider.getCurrentUser();
    // assert
    assertThat(user.isFeatureAdmin(), is(false));
}

16. SpringSecurityUserProviderTest#getCurrentUserWillCopyAuthoritiesFromAuthenticationIntoFeatureUser()

View license
@Test
public void getCurrentUserWillCopyAuthoritiesFromAuthenticationIntoFeatureUser() throws Exception {
    // arrange
    Collection authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority("ROLE_1"));
    authorities.add(new SimpleGrantedAuthority("ROLE_2"));
    when(authentication.getAuthorities()).thenReturn(authorities);
    // act
    FeatureUser user = userProvider.getCurrentUser();
    // assert
    Object authoritiesAttr = user.getAttribute(USER_ATTRIBUTE_ROLES);
    assertThat(authoritiesAttr, notNullValue());
    assertThat(authoritiesAttr, is(Set.class));
    Set<String> authoritySet = (Set<String>) authoritiesAttr;
    assertThat(authoritySet.size(), is(2));
    assertThat(authoritySet.contains("ROLE_1"), is(true));
    assertThat(authoritySet.contains("ROLE_2"), is(true));
}

17. MultiPageEditor#setImportedTypeSystemDescription()

Project: uima-uimaj
Source File: MultiPageEditor.java
View license
private void setImportedTypeSystemDescription() throws ResourceInitializationException {
    Collection tsdc = new ArrayList(1);
    TypeSystemDescription tsd = typeSystemDescription;
    if (null != tsd) {
        tsd = (TypeSystemDescription) tsd.clone();
        tsd.setTypes(typeDescriptionArray0);
    }
    tsdc.clear();
    tsdc.add(tsd);
    importedTypeSystemDescription = CasCreationUtils.mergeTypeSystems(tsdc, createResourceManager());
}

18. CollectionsTest#testListCanBeRootObject()

Project: xstream
Source File: CollectionsTest.java
View license
public void testListCanBeRootObject() {
    Collection list = new ArrayList();
    list.add("hi");
    list.add("bye");
    String expected = "" + "<list>\n" + "  <string>hi</string>\n" + "  <string>bye</string>\n" + "</list>";
    assertBothWays(list, expected);
}

19. CollectionsTest#testSetCanBeRootObject()

Project: xstream
Source File: CollectionsTest.java
View license
public void testSetCanBeRootObject() {
    Collection set = new HashSet();
    set.add("hi");
    set.add("bye");
    String expected = "" + "<set>\n" + "  <string>hi</string>\n" + "  <string>bye</string>\n" + "</set>";
    assertBothWaysNormalized(set, expected, "set", "string", null);
}

20. DefaultDependencyDescriptor#getDependencyArtifacts()

View license
private DependencyArtifactDescriptor[] getDependencyArtifacts(String moduleConfiguration, Map artifactsMap) {
    if (artifactsMap.isEmpty()) {
        return new DependencyArtifactDescriptor[0];
    }
    Collection artifacts = (Collection) artifactsMap.get(moduleConfiguration);
    Collection defArtifacts = (Collection) artifactsMap.get("*");
    Set ret = new HashSet();
    if (artifacts != null) {
        ret.addAll(artifacts);
    }
    if (defArtifacts != null) {
        ret.addAll(defArtifacts);
    }
    return (DependencyArtifactDescriptor[]) ret.toArray(new DependencyArtifactDescriptor[ret.size()]);
}

21. IvyNode#getRoot()

Project: ant-ivy
Source File: IvyNode.java
View license
public static IvyNode getRoot(IvyNode parent) {
    IvyNode root = parent;
    Collection path = new HashSet();
    path.add(root);
    while (root.getParent() != null && !root.isRoot()) {
        if (path.contains(root.getParent())) {
            return root;
        }
        root = root.getParent();
        path.add(root);
    }
    return root;
}

22. MultiRevDependencyDescriptor#addDependencyDescriptor()

View license
/**
     * @param project
     *            revision
     * @param dependencyDescriptor
     *            current descriptor
     */
public void addDependencyDescriptor(IvyClasspathContainerImpl container, DependencyDescriptor dependencyDescriptor) {
    Collection /* <DependencyDescriptor> */
    dependencies = (Collection) dependenciesByContainer.get(container);
    if (dependencies == null) {
        dependencies = new HashSet();
        dependenciesByContainer.put(container, dependencies);
    }
    dependencies.add(dependencyDescriptor);
}

23. SOAPElementImpl#getAllAttributes()

Project: axis2-java
Source File: SOAPElementImpl.java
View license
/**
     * Returns an iterator over all of the attribute names in this <CODE>SOAPElement</CODE> object.
     * The iterator can be used to get the attribute names, which can then be passed to the method
     * <CODE>getAttributeValue</CODE> to retrieve the value of each attribute.
     *
     * @return an iterator over the names of the attributes
     */
public Iterator getAllAttributes() {
    final Iterator attribIter = omTarget.getAllAttributes();
    Collection attribName = new ArrayList();
    Attr attr;
    while (attribIter.hasNext()) {
        attr = (Attr) attribIter.next();
        PrefixedQName qname;
        if (attr.getNamespaceURI() == null || attr.getNamespaceURI().trim().length() == 0) {
            qname = new PrefixedQName(attr.getNamespaceURI(), attr.getName(), attr.getPrefix());
        } else {
            qname = new PrefixedQName(attr.getNamespaceURI(), attr.getLocalName(), attr.getPrefix());
        }
        attribName.add(qname);
    }
    return attribName.iterator();
}

24. SOAPElementImpl#getAllAttributesAsQNames()

Project: axis2-java
Source File: SOAPElementImpl.java
View license
public Iterator getAllAttributesAsQNames() {
    final Iterator attribIter = omTarget.getAllAttributes();
    Collection attributesAsQNames = new ArrayList();
    Attr attr;
    QName qname;
    while (attribIter.hasNext()) {
        attr = (Attr) attribIter.next();
        //Check : attr.getLocalName() | attr.getName()
        qname = new QName(attr.getNamespaceURI(), attr.getName(), attr.getPrefix());
        attributesAsQNames.add(qname);
    }
    return attributesAsQNames.iterator();
}

25. SOAPFaultImpl#getChildren()

Project: axis2-java
Source File: SOAPFaultImpl.java
View license
private Iterator getChildren(Iterator childIter) {
    Collection childElements = new ArrayList();
    while (childIter.hasNext()) {
        org.w3c.dom.Node domNode = (org.w3c.dom.Node) childIter.next();
        org.w3c.dom.Node saajNode = toSAAJNode(domNode);
        if (!(saajNode instanceof SOAPFaultElement)) {
            // silently replace node, as per saaj 1.2 spec
            SOAPFaultElement bodyEle = new SOAPFaultElementImpl<OMElement>((OMElement) domNode);
            domNode.setUserData(SAAJ_NODE, bodyEle, null);
            childElements.add(bodyEle);
        } else {
            childElements.add(saajNode);
        }
    }
    return childElements.iterator();
}

26. SOAPHeaderImpl#getChildren()

Project: axis2-java
Source File: SOAPHeaderImpl.java
View license
private Iterator getChildren(Iterator childIter) {
    Collection childElements = new ArrayList();
    while (childIter.hasNext()) {
        org.w3c.dom.Node domNode = (org.w3c.dom.Node) childIter.next();
        org.w3c.dom.Node saajNode = toSAAJNode(domNode);
        if (saajNode instanceof javax.xml.soap.Text) {
            childElements.add(saajNode);
        } else if (!(saajNode instanceof SOAPHeaderElement)) {
            // silently replace node, as per saaj 1.2 spec
            SOAPHeaderElement headerEle = new SOAPHeaderElementImpl((SOAPHeaderBlock) domNode);
            domNode.setUserData(SAAJ_NODE, headerEle, null);
            childElements.add(headerEle);
        } else {
            childElements.add(saajNode);
        }
    }
    return childElements.iterator();
}

27. ExampleActivity#sendErrorWithMetaData()

View license
public void sendErrorWithMetaData(View view) {
    Map<String, String> nested = new HashMap<String, String>();
    nested.put("normalkey", "normalvalue");
    nested.put("password", "s3cr3t");
    Collection list = new ArrayList();
    list.add(nested);
    MetaData metaData = new MetaData();
    metaData.addToTab("user", "payingCustomer", true);
    metaData.addToTab("user", "password", "p4ssw0rd");
    metaData.addToTab("user", "credentials", nested);
    metaData.addToTab("user", "more", list);
    Bugsnag.notify(new RuntimeException("Non-fatal error with metaData"), Severity.ERROR, metaData);
    Toast.makeText(this, "Sent error with metaData", LENGTH_SHORT).show();
}

28. LazySeqAgronaTest#batchSinceLastReadIterator()

View license
@Test
public void batchSinceLastReadIterator() throws InterruptedException {
    Iterator<Collection<Integer>> it = of(1, 2, 3, 4, 5, 6).chunkLastReadIterator();
    Thread.sleep(10);
    Collection one = it.next();
    Collection two = it.next();
    assertThat(one.size(), greaterThan(0));
    assertThat(two.size(), greaterThan(0));
}

29. LazySequentialSeqAgronaTest#batchSinceLastReadIterator()

View license
@Test
public void batchSinceLastReadIterator() throws InterruptedException {
    Iterator<Collection<Integer>> it = of(1, 2, 3, 4, 5, 6).chunkLastReadIterator();
    Thread.sleep(10);
    Collection one = it.next();
    Collection two = it.next();
    assertThat(one.size(), greaterThan(0));
    assertThat(two.size(), greaterThan(0));
}

30. LazySequentialSeqObjectPoolsTest#batchSinceLastReadIterator()

View license
@Test
public void batchSinceLastReadIterator() throws InterruptedException {
    Iterator<Collection<Integer>> it = of(1, 2, 3, 4, 5, 6).chunkLastReadIterator();
    Thread.sleep(10);
    Collection one = it.next();
    Collection two = it.next();
    assertThat(one.size(), greaterThan(0));
    assertThat(two.size(), greaterThan(0));
}

31. LazySequentialSeqTest#batchSinceLastReadIterator()

View license
@Test
public void batchSinceLastReadIterator() throws InterruptedException {
    Iterator<Collection<Integer>> it = of(1, 2, 3, 4, 5, 6).chunkLastReadIterator();
    Thread.sleep(10);
    Collection one = it.next();
    Collection two = it.next();
    assertThat(one.size(), greaterThan(0));
    assertThat(two.size(), greaterThan(0));
}

32. CollectionMapper#read()

Project: effektif
Source File: CollectionMapper.java
View license
@Override
public Collection read(Object jsonValue, JsonReader jsonReader) {
    if (!Collection.class.isAssignableFrom(jsonValue.getClass())) {
        throw new InvalidValueException(String.format("Invalid Collection value %s (%s)", jsonValue, jsonValue.getClass().getName()));
    }
    Collection list = null;
    try {
        list = collectionType.newInstance();
    } catch (Exception e) {
        throw new RuntimeException("Couldn't instantiate collection: " + e.getMessage(), e);
    }
    Collection jsonCollection = (Collection) jsonValue;
    Iterator jsonIterator = jsonCollection.iterator();
    while (jsonIterator.hasNext()) {
        Object jsonElement = jsonIterator.next();
        Object objectElementValue = jsonElement != null ? elementMapper.read(jsonElement, jsonReader) : null;
        list.add(objectElementValue);
    }
    return list;
}

33. PersistentResource#addToCollection()

Project: elide
Source File: PersistentResource.java
View license
/**
     * Adds a new element to a collection and tests update permission.
     * @param collection the collection
     * @param collectionName the collection name
     * @param toAdd the to add
     * @return True if added to collection false otherwise (i.e. element already in collection)
     */
protected boolean addToCollection(Collection collection, String collectionName, PersistentResource toAdd) {
    final Collection singleton = Collections.singleton(toAdd.getObject());
    final Collection original = copyCollection(collection);
    checkFieldAwareDeferPermissions(UpdatePermission.class, collectionName, CollectionUtils.union(CollectionUtils.emptyIfNull(collection), singleton), original);
    if (collection == null) {
        collection = Collections.singleton(toAdd.getObject());
        Object value = getValueUnchecked(collectionName);
        if ((value == null && toAdd.getObject() != null) || (value != null && !value.equals(toAdd.getObject()))) {
            this.setValueChecked(collectionName, collection);
            return true;
        }
    } else {
        if (!collection.contains(toAdd.getObject())) {
            collection.add(toAdd.getObject());
            auditField(new ChangeSpec(this, collectionName, original, collection));
            return true;
        }
    }
    return false;
}

34. NestedJarFile#entries()

Project: geronimo
Source File: NestedJarFile.java
View license
public Enumeration entries() {
    if (isClosed) {
        throw new IllegalStateException("NestedJarFile is closed");
    }
    Collection baseEntries = Collections.list(baseJar.entries());
    Collection entries = new LinkedList();
    for (Iterator iterator = baseEntries.iterator(); iterator.hasNext(); ) {
        JarEntry baseEntry = (JarEntry) iterator.next();
        String path = baseEntry.getName();
        if (path.startsWith(basePath)) {
            entries.add(new NestedJarEntry(path.substring(basePath.length()), baseEntry, getManifestSafe()));
        }
    }
    return Collections.enumeration(entries);
}

35. RailsAssetsService#initialize()

Project: gocd
Source File: RailsAssetsService.java
View license
public void initialize() throws IOException {
    if (!systemEnvironment.useCompressedJs()) {
        return;
    }
    String assetsDirPath = servletContext.getRealPath(servletContext.getInitParameter("rails.root") + "/public/assets/");
    File assetsDir = new File(assetsDirPath);
    if (!assetsDir.exists()) {
        throw new RuntimeException(String.format("Assets directory does not exist %s", assetsDirPath));
    }
    Collection files = FileUtils.listFiles(assetsDir, new RegexFileFilter(MANIFEST_FILE_PATTERN), null);
    if (files.isEmpty()) {
        throw new RuntimeException(String.format("Manifest json file was not found at %s", assetsDirPath));
    }
    File manifestFile = (File) files.iterator().next();
    LOG.info(String.format("Found rails assets manifest file named %s ", manifestFile.getName()));
    String manifest = FileUtil.readContentFromFile(manifestFile);
    Gson gson = new Gson();
    railsAssetsManifest = gson.fromJson(manifest, RailsAssetsManifest.class);
    LOG.info(String.format("Successfully read rails assets manifest file located at %s", manifestFile.getAbsolutePath()));
}

36. Program#errorCheck()

Project: JAADAS
Source File: Program.java
View license
/**
   * @ast method 
   * @aspect ErrorCheck
   * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/ErrorCheck.jrag:238
   */
public boolean errorCheck() {
    Collection collection = new LinkedList();
    errorCheck(collection);
    if (collection.isEmpty())
        return false;
    System.out.println("Errors:");
    for (Iterator iter = collection.iterator(); iter.hasNext(); ) {
        String s = (String) iter.next();
        System.out.println(s);
    }
    return true;
}

37. MockMimeMessage#getAllHeaders()

Project: james-jsieve
Source File: MockMimeMessage.java
View license
public Enumeration getAllHeaders() throws MessagingException {
    final Collection results = new ArrayList();
    final Collection entries = m_contentHeaders.entrySet();
    for (Object entry1 : entries) {
        Map.Entry entry = (Map.Entry) entry1;
        String name = entry.getKey().toString();
        Object value = entry.getValue();
        if (value == null) {
        // ignore
        } else if (value instanceof Collection) {
            Collection values = (Collection) value;
            for (Object value1 : values) {
                String stringValue = (String) value1;
                results.add(new Header(name, stringValue));
            }
        } else {
            results.add(new Header(name, value.toString()));
        }
    }
    return Collections.enumeration(results);
}

38. CollectionChangeFakeAppender#calculateChanges()

View license
@Override
public PropertyChange calculateChanges(NodePair pair, Property property) {
    Collection leftCol = (Collection) pair.getLeftPropertyValue(property);
    Collection rightCol = (Collection) pair.getRightPropertyValue(property);
    if (!Objects.equals(leftCol, rightCol)) {
        logger.warn("Collections: " + property + "\n" + "are not equals but can't be compared. " + "Raw Collection properties are not supported. Expected Set, List or any of their subclasses. " + "JaVers uses different algorithms for comparing Sets and Lists and needs to know (statically) which one to apply.");
    }
    return null;
}

39. ComponentTest#assertJDependPackage()

Project: jdepend
Source File: ComponentTest.java
View license
private void assertJDependPackage() {
    JavaPackage p = jdepend.getPackage("jdepend");
    assertEquals("jdepend", p.getName());
    assertEquals(36, p.getConcreteClassCount());
    assertEquals(7, p.getAbstractClassCount());
    assertEquals(0, p.afferentCoupling());
    assertEquals(5, p.efferentCoupling());
    assertEquals(format(0.16f), format(p.abstractness()));
    assertEquals("1", format(p.instability()));
    assertEquals(format(0.16f), format(p.distance()));
    assertEquals(1, p.getVolatility());
    Collection efferents = p.getEfferents();
    assertEquals(5, efferents.size());
    assertTrue(efferents.contains(new JavaPackage("java")));
    assertTrue(efferents.contains(new JavaPackage("javax")));
    assertTrue(efferents.contains(new JavaPackage("junit")));
    Collection afferents = p.getAfferents();
    assertEquals(0, afferents.size());
}

40. MXBeanTest#compositeDataEqual()

Project: jdk7u-jdk
Source File: MXBeanTest.java
View license
// This is needed to work around a bug (5095277)
// in CompositeDataSupport.equals
private static boolean compositeDataEqual(CompositeData cd1, CompositeData cd2, NamedMXBeans namedMXBeans) {
    if (cd1 == cd2)
        return true;
    if (!cd1.getCompositeType().equals(cd2.getCompositeType()))
        return false;
    Collection v1 = cd1.values();
    Collection v2 = cd2.values();
    if (v1.size() != v2.size())
        // should not happen
        return false;
    for (Iterator i1 = v1.iterator(), i2 = v2.iterator(); i1.hasNext(); ) {
        if (!equal(i1.next(), i2.next(), namedMXBeans))
            return false;
    }
    return true;
}

41. DisruptorFactory#loadOnEventConsumers()

Project: jdonframework
Source File: DisruptorFactory.java
View license
protected Collection loadOnEventConsumers(String topic) {
    Collection ehs = new ArrayList();
    Collection consumerMethods = (Collection) containerWrapper.lookup(ConsumerLoader.TOPICNAME2 + topic);
    if (consumerMethods == null)
        return ehs;
    for (Object o : consumerMethods) {
        ConsumerMethodHolder consumerMethodHolder = (ConsumerMethodHolder) o;
        DomainEventDispatchHandler domainEventDispatchHandler = new DomainEventDispatchHandler(consumerMethodHolder, containerWrapper);
        ehs.add(domainEventDispatchHandler);
    }
    return ehs;
}

42. SimpleConfigurationTest#testGetBoolean7()

Project: jPOS
Source File: SimpleConfigurationTest.java
View license
@Test
public void testGetBoolean7() throws Throwable {
    Properties props = new Properties();
    SimpleConfiguration simpleConfiguration = new SimpleConfiguration(props);
    props.clear();
    Collection arrayList = new ArrayList();
    arrayList.add("testString");
    props.put("testString", "testString");
    String name = (String) props.put("testString", arrayList);
    boolean result = simpleConfiguration.getBoolean(name);
    assertFalse("result", result);
}

43. MXBeanTest#compositeDataEqual()

Project: openjdk
Source File: MXBeanTest.java
View license
// This is needed to work around a bug (5095277)
// in CompositeDataSupport.equals
private static boolean compositeDataEqual(CompositeData cd1, CompositeData cd2, NamedMXBeans namedMXBeans) {
    if (cd1 == cd2)
        return true;
    if (!cd1.getCompositeType().equals(cd2.getCompositeType()))
        return false;
    Collection v1 = cd1.values();
    Collection v2 = cd2.values();
    if (v1.size() != v2.size())
        // should not happen
        return false;
    for (Iterator i1 = v1.iterator(), i2 = v2.iterator(); i1.hasNext(); ) {
        if (!equal(i1.next(), i2.next(), namedMXBeans))
            return false;
    }
    return true;
}

44. OLuceneNearOperator#parseParams()

Project: orientdb
Source File: OLuceneNearOperator.java
View license
private Object[] parseParams(OIdentifiable iRecord, OSQLFilterCondition iCondition) {
    ODocument oDocument = (ODocument) iRecord;
    Collection left = (Collection) iCondition.getLeft();
    Collection right = (Collection) iCondition.getRight();
    Object[] params = new Object[(left.size() * 2) - 2];
    int i = 0;
    for (Object obj : left) {
        if (obj instanceof OSQLFilterItemField) {
            String fName = ((OSQLFilterItemField) obj).getFieldChain().getItemName(0);
            params[i] = oDocument.field(fName);
            i++;
        }
    }
    for (Object obj : right) {
        if (obj instanceof Number) {
            params[i] = ((Double) OType.convert(obj, Double.class)).doubleValue();
            ;
            i++;
        }
    }
    return params;
}

45. ZipFileParser#parse()

Project: sakai
Source File: ZipFileParser.java
View license
public ImportDataSource parse(InputStream fileData, String unArchiveLocation) {
    this.localArchiveLocation = unzipArchive(fileData, unArchiveLocation);
    this.pathToData = unArchiveLocation + File.separator + localArchiveLocation;
    awakeFromUnzip(pathToData);
    List categories = new ArrayList();
    Collection items = new ArrayList();
    categories.addAll(getCategoriesFromArchive(pathToData));
    items.addAll(getImportableItemsFromArchive(pathToData));
    ZipImportDataSource dataSource = new ZipImportDataSource();
    dataSource.setItemCategories(categories);
    dataSource.setItems(items);
    return dataSource;
}

46. LBCommonCartridgeFileParser#getImportableItemsFromArchive()

View license
protected Collection getImportableItemsFromArchive(String pathToData) {
    Collection items = new ArrayList();
    LBCCResource file = new LBCCResource();
    String fileName = "";
    file.setFileName(pathToData);
    file.setDescription("");
    file.setContentType("lessonbuilder-cc-file");
    String title = XPathHelper.getNodeValue("/manifest/metadata/lom/general/title", this.archiveManifest);
    file.setTitle(title);
    file.setLegacyGroup("");
    items.add(file);
    return items;
}

47. SakaiArchiveFileParser#parse()

Project: sakai
Source File: SakaiArchiveFileParser.java
View license
public ImportDataSource parse(InputStream fileData, String unArchiveLocation) {
    this.localArchiveLocation = unzipArchive(fileData, unArchiveLocation);
    this.pathToData = unArchiveLocation + "/" + localArchiveLocation;
    awakeFromUnzip(pathToData);
    List categories = new ArrayList();
    Collection items = new ArrayList();
    categories.addAll(getCategoriesFromArchive(pathToData));
    items.addAll(getImportableItemsFromArchive(pathToData));
    SakaiArchiveDataSource dataSource = new SakaiArchiveDataSource(fileData, localArchiveLocation, pathToData);
    dataSource.setItemCategories(categories);
    dataSource.setItems(items);
    return dataSource;
}

48. BaseContentService#getGroupsWithReadAccess()

Project: sakai
Source File: BaseContentService.java
View license
/******************************************************************************************************************************************************************************************************************************************************
	 * Group awareness implementation
	 *****************************************************************************************************************************************************************************************************************************************************/
/**
	 * Access a collection (Group) of groups to which this user has access and whose members have "content.read" permission in the collection. 
	 * In effect, this method returns a collection that identifies groups that are defined for the collection (locally or inherited) that 
	 * this user can access. If access to the collection is determined by group-membership, the return is limited to groups that have 
	 * access to the specified collection. If access is not defined by groups (i.e. it is "site" access), the return includes all groups
	 * defined in the site for which this user has read permission.
	 * 
	 * @param collectionId
	 *        The id for the collection.
	 */
public Collection getGroupsWithReadAccess(String collectionId) {
    Collection rv = new ArrayList();
    String refString = getReference(collectionId);
    Reference ref = m_entityManager.newReference(refString);
    Collection groups = getGroupsAllowFunction(AUTH_RESOURCE_READ, ref.getReference());
    if (groups != null && !groups.isEmpty()) {
        rv.addAll(groups);
    }
    return rv;
}

49. BaseContentService#getGroupsWithAddPermission()

Project: sakai
Source File: BaseContentService.java
View license
/**
	 * Access a collection (Group) of groups to which this user has access and whose members have "content.new" permission in the collection. 
	 * In effect, this method returns a collection that identifies groups that are defined for the collection (locally or inherited) in which 
	 * this user has permission to add content entities. If access to the collection is determined by group-membership, the return is limited 
	 * to groups that have "add" permission in the specified collection. If access is not defined by groups (i.e. it is "site" access), the return 
	 * includes all groups defined in the site for which this user has add permission in this collection.
	 * 
	 * @param collectionId
	 *        The id for the collection.
	 */
public Collection getGroupsWithAddPermission(String collectionId) {
    Collection rv = new ArrayList();
    String refString = getReference(collectionId);
    Reference ref = m_entityManager.newReference(refString);
    Collection groups = getGroupsAllowFunction(AUTH_RESOURCE_ADD, ref.getReference());
    if (groups != null && !groups.isEmpty()) {
        rv.addAll(groups);
    }
    return rv;
}

50. DefaultPermissionsManagerImpl#hasPermission()

View license
private boolean hasPermission(String role, String permission) {
    Collection realmList = new ArrayList();
    realmList.add(getContextSiteId());
    AuthzGroup authzGroup = null;
    try {
        authzGroup = authzGroupService.getAuthzGroup("!site.helper");
    } catch (Exception e) {
        LOG.info("No site helper template found");
    }
    if (authzGroup != null) {
        realmList.add(authzGroup.getId());
    }
    Set allowedFunctions = authzGroupService.getAllowedFunctions(role, realmList);
    return allowedFunctions.contains(permission);
}

51. CourseManagerTest#testRemoveTaFromCourse()

Project: sakai
Source File: CourseManagerTest.java
View license
public void testRemoveTaFromCourse() throws Exception {
    Course course = courseManager.createCourse("site", "course title", false, false, false);
    User ta1 = userManager.createUser("userUid", "foo", "bar", "baz");
    CourseSection section1 = sectionManager.addSection(course.getUuid(), "a section", "a category", null, null, null, null, false, false, false, false, false, false, false);
    CourseSection section2 = sectionManager.addSection(course.getUuid(), "another section", "another category", null, null, null, null, false, false, false, false, false, false, false);
    // Enroll the user in the course
    courseManager.addTA(ta1, course);
    // Enroll the user as a student in both sections
    sectionManager.addSectionMembership(ta1.getUserUid(), Role.TA, section1.getUuid());
    sectionManager.addSectionMembership(ta1.getUserUid(), Role.TA, section2.getUuid());
    // Make sure the user is a member of two sections
    Collection memberships1 = sectionManager.getSectionTeachingAssistants(section1.getUuid());
    Collection memberships2 = sectionManager.getSectionTeachingAssistants(section2.getUuid());
    Assert.assertTrue(memberships1.size() == 1);
    Assert.assertTrue(memberships2.size() == 1);
}

52. TestPageRecorder#testGetChanges()

Project: tapestry4
Source File: TestPageRecorder.java
View license
public void testGetChanges() {
    IRequestCycle cycle = newCycle();
    ErrorLog log = newLog();
    MockControl sourcec = newControl(PropertyPersistenceStrategySource.class);
    PropertyPersistenceStrategySource source = (PropertyPersistenceStrategySource) sourcec.getMock();
    Collection expected = new ArrayList();
    source.getAllStoredChanges("Foo");
    sourcec.setReturnValue(expected);
    replayControls();
    PageRecorderImpl pr = new PageRecorderImpl("Foo", cycle, source, log);
    Collection actual = pr.getChanges();
    assertSame(expected, actual);
    verifyControls();
}

53. FileSystemGroupStore#findEntitiesForGroup()

Project: uPortal
Source File: FileSystemGroupStore.java
View license
public java.util.Iterator findEntitiesForGroup(IEntityGroup group) throws GroupsException {
    if (log.isDebugEnabled())
        log.debug(DEBUG_CLASS_NAME + ".findEntitiesForGroup(): retrieving entities for group " + group);
    Collection entities = null;
    File f = getFile(group);
    if (f.isDirectory()) {
        entities = Collections.EMPTY_LIST;
    } else {
        entities = getEntitiesFromFile(f);
    }
    return entities.iterator();
}

54. FileSystemGroupStore#fileContains()

Project: uPortal
Source File: FileSystemGroupStore.java
View license
private boolean fileContains(File file, IGroupMember member) throws GroupsException {
    Collection ids = null;
    try {
        ids = member.isGroup() ? getGroupIdsFromFile(file) : getEntityIdsFromFile(file);
    } catch (Exception ex) {
        throw new GroupsException("Error retrieving ids from file", ex);
    }
    return ids.contains(member.getKey());
}

55. ReferenceCompositeGroupService#findParentGroups()

View license
/**
 * Returns groups that contain the <code>IGroupMember</code>.  Delegates to the
 * component services, but only after checking that they might actually contain
 * a membership for this member.
 * @param gm IGroupMember
 */
public Iterator findParentGroups(IGroupMember gm) throws GroupsException {
    Collection allGroups = new ArrayList();
    for (IIndividualGroupService service : (Collection<IIndividualGroupService>) getComponentServices().values()) {
        if (!gm.isGroup() || service.isEditable() || getComponentService(((IEntityGroup) gm).getServiceName()) == service) {
            {
                for (Iterator groups = service.findParentGroups(gm); groups.hasNext(); ) {
                    allGroups.add((IEntityGroup) groups.next());
                }
            }
        }
    }
    return allGroups.iterator();
}

56. ReferenceIndividualGroupService#findParentGroups()

View license
/**
 * Returns and caches the containing groups for the <code>IGroupMember</code>
 * @param gm IGroupMember
 */
@Override
public Iterator findParentGroups(IGroupMember gm) throws GroupsException {
    log.debug("Finding containing groups for member {}", gm.getKey());
    Collection groups = new ArrayList(10);
    IEntityGroup group = null;
    for (Iterator it = getGroupStore().findParentGroups(gm); it.hasNext(); ) {
        group = (IEntityGroup) it.next();
        group.setLocalGroupService(this);
        groups.add(group);
        if (cacheInUse()) {
            try {
                if (getGroupFromCache(group.getEntityIdentifier().getKey()) == null) {
                    cacheAdd(group);
                }
            } catch (CachingException ce) {
                throw new GroupsException("Problem finding containing groups", ce);
            }
        }
    }
    return groups.iterator();
}

57. ReferenceIndividualGroupService#findMembers()

View license
/**
 * Returns and members for the <code>IEntityGroup</code>.
 * @param eg IEntityGroup
 */
public Iterator findMembers(IEntityGroup eg) throws GroupsException {
    Collection members = new ArrayList(10);
    Iterator it = null;
    for (it = findMemberGroups(eg); it.hasNext(); ) {
        members.add(it.next());
    }
    for (it = findMemberEntities(eg); it.hasNext(); ) {
        members.add(it.next());
    }
    return members.iterator();
}

58. TestSpliter#main()

Project: android-lite-orm
Source File: TestSpliter.java
View license
public static void main(String[] args) throws Exception {
    Collection coll = new LinkedList();
    for (int i = 0; i < 9; i++) {
        coll.add("a " + i);
    }
    CollSpliter.split(coll, 3, new CollSpliter.Spliter() {

        @Override
        public int oneSplit(ArrayList list) throws Exception {
            System.out.println("-------  " + list.size());
            for (Object o : list) {
                System.out.println(o);
            }
            return 0;
        }
    });
}

59. IvyCacheTask#getArtifacts()

Project: ant-ivy
Source File: IvyCacheTask.java
View license
protected List getArtifacts() throws BuildException, ParseException, IOException {
    Collection artifacts = getAllArtifacts();
    List ret = new ArrayList();
    for (Iterator iter = artifacts.iterator(); iter.hasNext(); ) {
        Artifact artifact = (Artifact) iter.next();
        if (getArtifactFilter().accept(artifact)) {
            ret.add(artifact);
        }
    }
    return ret;
}

60. FilterHelper#filter()

Project: ant-ivy
Source File: FilterHelper.java
View license
/**
     * we could have used commons-collections facility for this...
     * if we accepted to add dependencies on third party jars
     * @param col
     * @param filter
     * @return
     */
public static Collection filter(Collection col, Filter filter) {
    if (filter == null) {
        return col;
    }
    Collection ret = new ArrayList(col);
    for (Iterator iter = ret.iterator(); iter.hasNext(); ) {
        Object element = (Object) iter.next();
        if (!filter.accept(element)) {
            iter.remove();
        }
    }
    return ret;
}

61. Ivy#sync()

Project: ant-ivy
Source File: Ivy.java
View license
private void sync(Collection target, Collection existing) {
    Collection toRemove = new HashSet();
    for (Iterator iter = existing.iterator(); iter.hasNext(); ) {
        File file = (File) iter.next();
        toRemove.add(file.getAbsoluteFile());
    }
    for (Iterator iter = target.iterator(); iter.hasNext(); ) {
        File file = (File) iter.next();
        toRemove.remove(file.getAbsoluteFile());
    }
    for (Iterator iter = toRemove.iterator(); iter.hasNext(); ) {
        File file = (File) iter.next();
        if (file.exists()) {
            Message.verbose("\t\tdeleting " + file);
            FileUtil.forceDelete(file);
        }
    }
}

62. Ivy#listOrganisations()

Project: ant-ivy
Source File: Ivy.java
View license
public String[] listOrganisations() {
    Collection orgs = new HashSet();
    for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext(); ) {
        DependencyResolver resolver = (DependencyResolver) iter.next();
        OrganisationEntry[] entries = resolver.listOrganisations();
        if (entries != null) {
            for (int i = 0; i < entries.length; i++) {
                if (entries[i] != null) {
                    orgs.add(entries[i].getOrganisation());
                }
            }
        }
    }
    return (String[]) orgs.toArray(new String[orgs.size()]);
}

63. IvyNode#getResolvedRevisions()

Project: ant-ivy
Source File: IvyNode.java
View license
public Collection getResolvedRevisions(ModuleId mid, String rootModuleConf) {
    Collection resolved = (Collection) _selectedDeps.get(new ModuleIdConf(mid, rootModuleConf));
    if (resolved == null) {
        return new HashSet();
    } else {
        Collection resolvedRevs = new HashSet();
        for (Iterator iter = resolved.iterator(); iter.hasNext(); ) {
            IvyNode node = (IvyNode) iter.next();
            resolvedRevs.add(node.getId());
            resolvedRevs.add(node.getResolvedId());
        }
        return resolvedRevs;
    }
}

64. IvyNode#getAllEvictingNodes()

Project: ant-ivy
Source File: IvyNode.java
View license
/**
     * Returns null if this node has only be evicted transitively, or the the colletion of selected nodes
     * if it has been evicted by other selected nodes
     * @return
     */
public Collection getAllEvictingNodes() {
    Collection allEvictingNodes = null;
    for (Iterator iter = _evicted.values().iterator(); iter.hasNext(); ) {
        EvictionData ed = (EvictionData) iter.next();
        Collection selected = ed.getSelected();
        if (selected != null) {
            if (allEvictingNodes == null) {
                allEvictingNodes = new HashSet();
            }
            allEvictingNodes.addAll(selected);
        }
    }
    return allEvictingNodes;
}

65. IvyNode#getDependencies()

Project: ant-ivy
Source File: IvyNode.java
View license
public Collection getDependencies(String[] confs) {
    if (_md == null) {
        throw new IllegalStateException("impossible to get dependencies when data has not been loaded");
    }
    if (Arrays.asList(confs).contains("*")) {
        confs = _md.getConfigurationsNames();
    }
    Collection deps = new HashSet();
    for (int i = 0; i < confs.length; i++) {
        deps.addAll(getDependencies(confs[i], false));
    }
    return deps;
}

66. IvyNode#getEvictionDataInRoot()

Project: ant-ivy
Source File: IvyNode.java
View license
/**
     * Returns the eviction data for this node if it has been previously evicted in the most far parent
     * of the given node, null otherwise (if it hasn't been evicted in root) for the 
     * given rootModuleConf.
     * Note that this method only works if conflict resolution has already be done in all the ancestors.
     * 
     * @param rootModuleConf
     * @param parent
     * @return
     */
public EvictionData getEvictionDataInRoot(String rootModuleConf, IvyNode parent) {
    IvyNode root = parent.getRoot();
    Collection selectedNodes = root.getResolvedNodes(getModuleId(), rootModuleConf);
    for (Iterator iter = selectedNodes.iterator(); iter.hasNext(); ) {
        IvyNode node = (IvyNode) iter.next();
        if (node.getResolvedId().equals(getResolvedId())) {
            // the node is part of the selected ones for the root: no eviction data to return
            return null;
        }
    }
    // we didn't find this mrid in the selected ones for the root: it has been previously evicted
    return new EvictionData(rootModuleConf, parent, root.getConflictManager(getModuleId()), selectedNodes);
}

67. BasicResolver#listModules()

Project: ant-ivy
Source File: BasicResolver.java
View license
public ModuleEntry[] listModules(OrganisationEntry org) {
    Map tokenValues = new HashMap();
    tokenValues.put(IvyPatternHelper.ORGANISATION_KEY, org.getOrganisation());
    Collection names = findNames(tokenValues, IvyPatternHelper.MODULE_KEY);
    ModuleEntry[] ret = new ModuleEntry[names.size()];
    int i = 0;
    for (Iterator iter = names.iterator(); iter.hasNext(); i++) {
        String name = (String) iter.next();
        ret[i] = new ModuleEntry(org, name);
    }
    return ret;
}

68. BasicResolver#listRevisions()

Project: ant-ivy
Source File: BasicResolver.java
View license
public RevisionEntry[] listRevisions(ModuleEntry mod) {
    Map tokenValues = new HashMap();
    tokenValues.put(IvyPatternHelper.ORGANISATION_KEY, mod.getOrganisation());
    tokenValues.put(IvyPatternHelper.MODULE_KEY, mod.getModule());
    Collection names = findNames(tokenValues, IvyPatternHelper.REVISION_KEY);
    RevisionEntry[] ret = new RevisionEntry[names.size()];
    int i = 0;
    for (Iterator iter = names.iterator(); iter.hasNext(); i++) {
        String name = (String) iter.next();
        ret[i] = new RevisionEntry(mod, name);
    }
    return ret;
}

69. IvyRepResolver#listModules()

Project: ant-ivy
Source File: IvyRepResolver.java
View license
// overwrite parent to use only ivy patterns (and not artifact ones, cause ibiblio is too slow to answer)
public ModuleEntry[] listModules(OrganisationEntry org) {
    ensureIvyConfigured(getIvy());
    Map tokenValues = new HashMap();
    tokenValues.put(IvyPatternHelper.ORGANISATION_KEY, org.getOrganisation());
    Collection names = findIvyNames(tokenValues, IvyPatternHelper.MODULE_KEY);
    ModuleEntry[] ret = new ModuleEntry[names.size()];
    int i = 0;
    for (Iterator iter = names.iterator(); iter.hasNext(); i++) {
        String name = (String) iter.next();
        ret[i] = new ModuleEntry(org, name);
    }
    return ret;
}

70. MultiRevDependencyDescriptor#getRevisions()

View license
/**
     * @return all revisions
     */
public String[] getRevisions() {
    Set revisions = new HashSet();
    /* Collection<Collection<DependencyDescriptor>> */
    Collection projectDependencyDescriptors = dependenciesByContainer.values();
    Iterator it = projectDependencyDescriptors.iterator();
    while (it.hasNext()) {
        Collection /* <DependencyDescriptor> */
        projectCollection = (Collection) it.next();
        Iterator descriptorIter = projectCollection.iterator();
        while (descriptorIter.hasNext()) {
            DependencyDescriptor descriptor = (DependencyDescriptor) descriptorIter.next();
            revisions.add(descriptor.getDependencyRevisionId().getRevision());
        }
    }
    return (String[]) revisions.toArray(new String[revisions.size()]);
}

71. MultiRevDependencyDescriptor#getRevisions()

View license
/**
     * This returns the current revisions for a project <br>
     * 
     * @param project
     *            project
     * @return revision
     */
public String[] getRevisions(IvyClasspathContainerImpl container) {
    /* Collection<DependencyDescriptor> */
    Collection containerDependencyDescriptors = (Collection) dependenciesByContainer.get(container);
    if (containerDependencyDescriptors == null) {
        return new String[0];
    }
    Set revisions = new HashSet();
    Iterator iter = containerDependencyDescriptors.iterator();
    while (iter.hasNext()) {
        DependencyDescriptor descriptor = (DependencyDescriptor) iter.next();
        revisions.add(descriptor.getDependencyRevisionId().getRevision());
    }
    return (String[]) revisions.toArray(new String[revisions.size()]);
}

72. SyncIvyFilesJob#getIvyClasspathContainers()

Project: ant-ivyde
Source File: SyncIvyFilesJob.java
View license
private IvyClasspathContainerImpl[] getIvyClasspathContainers() {
    Collection /* <IvyClasspathContainer> */
    containers = new HashSet();
    for (int i = 0; i < multiRevisionDependencies.length; i++) {
        MultiRevDependencyDescriptor multiRevision = multiRevisionDependencies[i];
        if (multiRevision.hasNewRevision()) {
            containers.addAll(Arrays.asList(multiRevision.getIvyClasspathContainers()));
        }
    }
    return (IvyClasspathContainerImpl[]) containers.toArray(new IvyClasspathContainerImpl[containers.size()]);
}

73. IvyNodeElementFilterAdapter#filter()

View license
public IvyNodeElement[] filter(IvyNodeElement[] unfiltered) {
    if (!enabled)
        return unfiltered;
    Collection filtered = new HashSet();
    for (int i = 0; i < unfiltered.length; i++) {
        if (accept(unfiltered[i]))
            filtered.add(unfiltered[i]);
    }
    return (IvyNodeElement[]) filtered.toArray(new IvyNodeElement[filtered.size()]);
}

74. PackageStateTest#testListPackages()

Project: apache-aries
Source File: PackageStateTest.java
View license
@Test
public void testListPackages() throws IOException {
    Bundle bundle = Mockito.mock(Bundle.class);
    Bundle impBundle = Mockito.mock(Bundle.class);
    Mockito.when(context.getBundles()).thenReturn(new Bundle[] { bundle });
    ExportedPackage exported = Mockito.mock(ExportedPackage.class);
    Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
    Mockito.when(exported.getImportingBundles()).thenReturn(new Bundle[] { impBundle });
    Mockito.when(exported.getName()).thenReturn("test");
    Mockito.when(exported.getExportingBundle()).thenReturn(bundle);
    Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(4));
    Mockito.when(impBundle.getBundleId()).thenReturn(Long.valueOf(5));
    Mockito.when(admin.getExportedPackages(bundle)).thenReturn(new ExportedPackage[] { exported });
    TabularData table = mbean.listPackages();
    Assert.assertEquals(PackageStateMBean.PACKAGES_TYPE, table.getTabularType());
    Collection values = table.values();
    Assert.assertEquals(1, values.size());
    CompositeData data = (CompositeData) values.iterator().next();
    Long[] exportingBundles = (Long[]) data.get(PackageStateMBean.EXPORTING_BUNDLES);
    Assert.assertArrayEquals(new Long[] { Long.valueOf(4) }, exportingBundles);
    String name = (String) data.get(PackageStateMBean.NAME);
    Assert.assertEquals("test", name);
    String version = (String) data.get(PackageStateMBean.VERSION);
    Assert.assertEquals("1.0.0", version);
}

75. KeySequenceDirect#getNextID()

Project: apache-aries
Source File: KeySequenceDirect.java
View license
public static synchronized Integer getNextID(Connection conn, String keyName, boolean inSession, boolean inGlobalTxn) throws Exception {
    Integer nextID = null;
    // allocate a new block if necessary
    if (keyMap.containsKey(keyName) == false)
        allocNewBlock(conn, keyName, inSession, inGlobalTxn);
    Collection block = (Collection) keyMap.get(keyName);
    Iterator ids = block.iterator();
    if (ids.hasNext() == false)
        ids = allocNewBlock(conn, keyName, inSession, inGlobalTxn).iterator();
    // get and return a new unique key
    nextID = (Integer) ids.next();
    if (Log.doTrace())
        Log.trace("KeySequenceDirect:getNextID inSession(" + inSession + ") - return new PK ID for Entity type: " + keyName + " ID=" + nextID);
    return nextID;
}

76. PackageStateTest#testListPackages()

Project: aries
Source File: PackageStateTest.java
View license
@Test
public void testListPackages() throws IOException {
    Bundle bundle = Mockito.mock(Bundle.class);
    Bundle impBundle = Mockito.mock(Bundle.class);
    Mockito.when(context.getBundles()).thenReturn(new Bundle[] { bundle });
    ExportedPackage exported = Mockito.mock(ExportedPackage.class);
    Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
    Mockito.when(exported.getImportingBundles()).thenReturn(new Bundle[] { impBundle });
    Mockito.when(exported.getName()).thenReturn("test");
    Mockito.when(exported.getExportingBundle()).thenReturn(bundle);
    Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(4));
    Mockito.when(impBundle.getBundleId()).thenReturn(Long.valueOf(5));
    Mockito.when(admin.getExportedPackages(bundle)).thenReturn(new ExportedPackage[] { exported });
    TabularData table = mbean.listPackages();
    Assert.assertEquals(PackageStateMBean.PACKAGES_TYPE, table.getTabularType());
    Collection values = table.values();
    Assert.assertEquals(1, values.size());
    CompositeData data = (CompositeData) values.iterator().next();
    Long[] exportingBundles = (Long[]) data.get(PackageStateMBean.EXPORTING_BUNDLES);
    Assert.assertArrayEquals(new Long[] { Long.valueOf(4) }, exportingBundles);
    String name = (String) data.get(PackageStateMBean.NAME);
    Assert.assertEquals("test", name);
    String version = (String) data.get(PackageStateMBean.VERSION);
    Assert.assertEquals("1.0.0", version);
}

77. KeySequenceDirect#getNextID()

Project: aries
Source File: KeySequenceDirect.java
View license
public static synchronized Integer getNextID(Connection conn, String keyName, boolean inSession, boolean inGlobalTxn) throws Exception {
    Integer nextID = null;
    // allocate a new block if necessary
    if (keyMap.containsKey(keyName) == false)
        allocNewBlock(conn, keyName, inSession, inGlobalTxn);
    Collection block = (Collection) keyMap.get(keyName);
    Iterator ids = block.iterator();
    if (ids.hasNext() == false)
        ids = allocNewBlock(conn, keyName, inSession, inGlobalTxn).iterator();
    // get and return a new unique key
    nextID = (Integer) ids.next();
    if (Log.doTrace())
        Log.trace("KeySequenceDirect:getNextID inSession(" + inSession + ") - return new PK ID for Entity type: " + keyName + " ID=" + nextID);
    return nextID;
}

78. HTTPLocationBasedDispatcher#getOperationFromHTTPLocation()

View license
/**
     * Given the requestPath that the request came to his method returns the corresponding axisOperation
     *
     * @param requestPath - Part of the request url which is the part after the service name
     * @param httpLocationTable - The httpLocationTable stored in the relavant binding
     * @return AxisOperation - The corresponding AxisOperation
     */
private AxisOperation getOperationFromHTTPLocation(String requestPath, Map httpLocationTable) {
    Collection httpLocations = httpLocationTable.keySet();
    Iterator iter = httpLocations.iterator();
    while (iter.hasNext()) {
        String location = (String) iter.next();
        int index = requestPath.indexOf(location);
        if (index == 0) {
            return (AxisOperation) httpLocationTable.get(location);
        }
    }
    return null;
}

79. ValueObjectUtil#typeCastCollection()

Project: bboss
Source File: ValueObjectUtil.java
View license
/**
	 * @param values
	 * @param targetContainer
	 * @param objectType
	 */
public static Object typeCastCollection(Object values, Class targetContainerType, Class elementType, String dateformat) {
    if (values == null)
        return null;
    Collection targetContainer = createCollection(targetContainerType);
    if (values.getClass().isArray()) {
        for (int i = 0; i < Array.getLength(values); i++) {
            Object v = Array.get(values, i);
            targetContainer.add(ValueObjectUtil.typeCast(v, elementType, dateformat));
        }
    } else {
        targetContainer.add(ValueObjectUtil.typeCast(values, elementType, dateformat));
    }
    return targetContainer;
}

80. X509CRLSelector#getIssuerNames()

Project: bc-java
Source File: X509CRLSelector.java
View license
/**
     * Returns a copy of the issuerNames criterion. The issuer distinguished
     * name in the <code>X509CRL</code> must match at least one of the
     * specified distinguished names. If the value returned is <code>null</code>,
     * any issuer distinguished name will do.<br />
     * <br />
     * If the value returned is not <code>null</code>, it is a
     * <code>Collection</code> of names. Each name is a <code>String</code>
     * or a byte array representing a distinguished name (in RFC 2253 or ASN.1
     * DER encoded form, respectively). Note that the <code>Collection</code>
     * returned may contain duplicate names.<br />
     * <br />
     * If a name is specified as a byte array, it should contain a single DER
     * encoded distinguished name, as defined in X.501. The ASN.1 notation for
     * this structure is given in the documentation for
     * {@link #setIssuerNames setIssuerNames(Collection names)}.<br />
     * <br />
     * Note that a deep copy is performed on the <code>Collection</code> to
     * protect against subsequent modifications.
     * 
     * @return a <code>Collection</code> of names (or <code>null</code>)
     * @see #setIssuerNames
     */
public Collection getIssuerNames() {
    if (issuerNames == null) {
        return null;
    }
    Collection set = new HashSet();
    Iterator iter = issuerNames.iterator();
    Object item;
    while (iter.hasNext()) {
        item = iter.next();
        if (item instanceof String) {
            set.add(new String((String) item));
        } else if (item instanceof byte[]) {
            set.add(((byte[]) item).clone());
        }
    }
    return set;
}

81. NewSMIMESignedTest#testDoubleNlCanonical()

Project: bc-java
Source File: NewSMIMESignedTest.java
View license
public void testDoubleNlCanonical() throws Exception {
    MimeMessage message = loadMessage("3nnn_smime.eml");
    SMIMESigned s = new SMIMESigned((MimeMultipart) message.getContent());
    Collection c = s.getSignerInfos().getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = s.getCertificates().getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
        // in this case the sig is invalid, but it's the lack of an exception from the content digest we're looking for
        Assert.assertFalse(signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certHolder)));
    }
}

82. NewSMIMESignedTest#verifySigners()

Project: bc-java
Source File: NewSMIMESignedTest.java
View license
private void verifySigners(Store certs, SignerInformationStore signers) throws Exception {
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certs.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
        assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certHolder)));
    }
}

83. SMIMEMiscTest#verifySigners()

Project: bc-java
Source File: SMIMEMiscTest.java
View license
private void verifySigners(Store certs, SignerInformationStore signers) throws Exception {
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certs.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
        assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)));
    }
}

84. DANEEntryStore#toCertificateStore()

Project: bc-java
Source File: DANEEntryStore.java
View license
/**
     * Return a Store of X509CertificateHolder objects representing all the certificates associated with
     * entries in the store.
     *
     * @return a Store of X509CertificateHolder.
     */
public Store toCertificateStore() {
    Collection col = this.getMatches(null);
    List certColl = new ArrayList(col.size());
    for (Iterator it = col.iterator(); it.hasNext(); ) {
        DANEEntry entry = (DANEEntry) it.next();
        certColl.add(entry.getCertificate());
    }
    return new CollectionStore(certColl);
}

85. CMSSignedData#verifyCounterSignature()

Project: bc-java
Source File: CMSSignedData.java
View license
private boolean verifyCounterSignature(SignerInformation counterSigner, SignerInformationVerifierProvider verifierProvider) throws OperatorCreationException, CMSException {
    SignerInformationVerifier counterVerifier = verifierProvider.get(counterSigner.getSID());
    if (!counterSigner.verify(counterVerifier)) {
        return false;
    }
    Collection counterSigners = counterSigner.getCounterSignatures().getSigners();
    for (Iterator cIt = counterSigners.iterator(); cIt.hasNext(); ) {
        if (!verifyCounterSignature((SignerInformation) cIt.next(), verifierProvider)) {
            return false;
        }
    }
    return true;
}

86. BcSignedDataTest#verifyRSASignatures()

Project: bc-java
Source File: BcSignedDataTest.java
View license
private void verifyRSASignatures(CMSSignedData s, byte[] contentDigest) throws Exception {
    Store certStore = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certStore.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
        assertEquals(true, signer.verify(new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(cert)));
        if (contentDigest != null) {
            assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest()));
        }
    }
}

87. BcSignedDataTest#checkSignerStoreReplacement()

Project: bc-java
Source File: BcSignedDataTest.java
View license
//
// signerInformation store replacement test.
//
private void checkSignerStoreReplacement(CMSSignedData orig, SignerInformationStore signers) throws Exception {
    CMSSignedData s = CMSSignedData.replaceSigners(orig, signers);
    Store certs = s.getCertificates();
    signers = s.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certs.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
        assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert)));
    }
}

88. BcSignedDataTest#verifySignatures()

Project: bc-java
Source File: BcSignedDataTest.java
View license
private void verifySignatures(CMSSignedDataParser sp) throws Exception {
    Store certs = sp.getCertificates();
    SignerInformationStore signers = sp.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certs.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
        assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert)));
    }
}

89. MiscDataStreamTest#verifySignatures()

Project: bc-java
Source File: MiscDataStreamTest.java
View license
private void verifySignatures(CMSSignedDataParser sp, byte[] contentDigest) throws Exception {
    Store certStore = sp.getCertificates();
    SignerInformationStore signers = sp.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certStore.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
        assertEquals(true, signer.verify(new JcaSignerInfoVerifierBuilder(digCalcProv).setProvider(BC).build(cert)));
        if (contentDigest != null) {
            assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest()));
        }
    }
}

90. NewAuthenticatedDataTest#checkData()

View license
private void checkData(byte[] data, SecretKey kek, CMSAuthenticatedData ad) throws CMSException {
    RecipientInformationStore recipients = ad.getRecipientInfos();
    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();
    if (it.hasNext()) {
        RecipientInformation recipient = (RecipientInformation) it.next();
        byte[] recData = recipient.getContent(new JceKEKAuthenticatedRecipient(kek).setProvider(BC));
        assertTrue(Arrays.equals(data, recData));
        assertTrue(Arrays.equals(ad.getMac(), recipient.getMac()));
        assertTrue(Arrays.equals(ad.getContentDigest(), recipient.getContentDigest()));
    } else {
        fail("no recipient found");
    }
}

91. NewEnvelopedDataStreamTest#verifyData()

View license
private void verifyData(ByteArrayOutputStream encodedStream, String expectedOid, byte[] expectedData) throws Exception {
    CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(encodedStream.toByteArray());
    RecipientInformationStore recipients = ep.getRecipientInfos();
    assertEquals(ep.getEncryptionAlgOID(), expectedOid);
    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        RecipientInformation recipient = (RecipientInformation) it.next();
        assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId());
        CMSTypedStream recData = recipient.getContentStream(new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC));
        assertEquals(true, Arrays.equals(expectedData, CMSTestUtil.streamToByteArray(recData.getContentStream())));
    }
}

92. NewSignedDataTest#verifyRSASignatures()

Project: bc-java
Source File: NewSignedDataTest.java
View license
private void verifyRSASignatures(CMSSignedData s, byte[] contentDigest) throws Exception {
    Store certStore = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certStore.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
        assertEquals(true, signer.verify(new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(cert)));
        if (contentDigest != null) {
            assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest()));
        }
    }
}

93. NewSignedDataTest#testGostNoAttributesEncapsulated()

Project: bc-java
Source File: NewSignedDataTest.java
View license
public void testGostNoAttributesEncapsulated() throws Exception {
    CMSSignedData data = new CMSSignedData(rawGost);
    Store certStore = data.getCertificates();
    SignerInformationStore signers = data.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certStore.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
        assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)));
    }
}

94. NewSignedDataTest#checkSignerStoreReplacement()

Project: bc-java
Source File: NewSignedDataTest.java
View license
//
// signerInformation store replacement test.
//
private void checkSignerStoreReplacement(CMSSignedData orig, SignerInformationStore signers) throws Exception {
    CMSSignedData s = CMSSignedData.replaceSigners(orig, signers);
    Store certs = s.getCertificates();
    signers = s.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certs.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
        assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert)));
    }
}

95. NewSignedDataTest#testMixed()

Project: bc-java
Source File: NewSignedDataTest.java
View license
public void testMixed() throws Exception {
    DERApplicationSpecific derApplicationSpecific = (DERApplicationSpecific) ASN1Primitive.fromByteArray(mixedSignedData);
    CMSSignedData s = new CMSSignedData(new ByteArrayInputStream(derApplicationSpecific.getContents()));
    Store certs = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certs.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
        assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert)));
    }
}

96. NewSignedDataTest#verifySignatures()

Project: bc-java
Source File: NewSignedDataTest.java
View license
private void verifySignatures(CMSSignedDataParser sp) throws Exception {
    Store certs = sp.getCertificates();
    SignerInformationStore signers = sp.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certs.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
        assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert)));
    }
}

97. Rfc4134Test#verifyEnvelopedData()

Project: bc-java
Source File: Rfc4134Test.java
View license
private void verifyEnvelopedData(CMSEnvelopedData envelopedData, String symAlgorithmOID) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, CMSException {
    byte[] privKeyData = getRfc4134Data("BobPrivRSAEncrypt.pri");
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKeyData);
    KeyFactory keyFact = KeyFactory.getInstance("RSA", BC);
    PrivateKey privKey = keyFact.generatePrivate(keySpec);
    RecipientInformationStore recipients = envelopedData.getRecipientInfos();
    assertEquals(envelopedData.getEncryptionAlgOID(), symAlgorithmOID);
    Collection c = recipients.getRecipients();
    assertTrue(c.size() >= 1 && c.size() <= 2);
    Iterator it = c.iterator();
    verifyRecipient((RecipientInformation) it.next(), privKey);
    if (c.size() == 2) {
        RecipientInformation recInfo = (RecipientInformation) it.next();
        assertEquals(PKCSObjectIdentifiers.id_alg_CMSRC2wrap.getId(), recInfo.getKeyEncryptionAlgOID());
    }
}

98. Rfc4134Test#verifyEnvelopedData()

Project: bc-java
Source File: Rfc4134Test.java
View license
private void verifyEnvelopedData(CMSEnvelopedDataParser envelopedParser, String symAlgorithmOID) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, CMSException {
    byte[] privKeyData = getRfc4134Data("BobPrivRSAEncrypt.pri");
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKeyData);
    KeyFactory keyFact = KeyFactory.getInstance("RSA", BC);
    PrivateKey privKey = keyFact.generatePrivate(keySpec);
    RecipientInformationStore recipients = envelopedParser.getRecipientInfos();
    assertEquals(envelopedParser.getEncryptionAlgOID(), symAlgorithmOID);
    Collection c = recipients.getRecipients();
    assertTrue(c.size() >= 1 && c.size() <= 2);
    Iterator it = c.iterator();
    verifyRecipient((RecipientInformation) it.next(), privKey);
    if (c.size() == 2) {
        RecipientInformation recInfo = (RecipientInformation) it.next();
        assertEquals(PKCSObjectIdentifiers.id_alg_CMSRC2wrap.getId(), recInfo.getKeyEncryptionAlgOID());
    }
}

99. Rfc4134Test#verifySignatures()

Project: bc-java
Source File: Rfc4134Test.java
View license
private void verifySignatures(CMSSignedData s, byte[] contentDigest) throws Exception {
    Store certStore = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certStore.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
        verifySigner(signer, cert);
        if (contentDigest != null) {
            assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest()));
        }
    }
}

100. X509CRLSelector#getIssuerNames()

Project: bc-java
Source File: X509CRLSelector.java
View license
/**
     * Returns a copy of the issuerNames criterion. The issuer distinguished
     * name in the <code>X509CRL</code> must match at least one of the
     * specified distinguished names. If the value returned is <code>null</code>,
     * any issuer distinguished name will do.<br />
     * <br />
     * If the value returned is not <code>null</code>, it is a
     * <code>Collection</code> of names. Each name is a <code>String</code>
     * or a byte array representing a distinguished name (in RFC 2253 or ASN.1
     * DER encoded form, respectively). Note that the <code>Collection</code>
     * returned may contain duplicate names.<br />
     * <br />
     * If a name is specified as a byte array, it should contain a single DER
     * encoded distinguished name, as defined in X.501. The ASN.1 notation for
     * this structure is given in the documentation for
     * {@link #setIssuerNames setIssuerNames(Collection names)}.<br />
     * <br />
     * Note that a deep copy is performed on the <code>Collection</code> to
     * protect against subsequent modifications.
     * 
     * @return a <code>Collection</code> of names (or <code>null</code>)
     * @see #setIssuerNames
     */
public Collection getIssuerNames() {
    if (issuerNames == null) {
        return null;
    }
    Collection set = new HashSet();
    Iterator iter = issuerNames.iterator();
    Object item;
    while (iter.hasNext()) {
        item = iter.next();
        if (item instanceof String) {
            set.add(new String((String) item));
        } else if (item instanceof byte[]) {
            set.add(((byte[]) item).clone());
        }
    }
    return set;
}