List of usage examples for java.util List containsAll
boolean containsAll(Collection<?> c);
From source file:org.apache.brooklyn.rest.resources.BundleAndTypeResourcesTest.java
@Test public void testOsgiBundleWithBomNotInBrooklynNamespace() throws Exception { TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_PATH); final String symbolicName = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_SYMBOLIC_NAME_FULL; final String version = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_VERSION; final String bundleUrl = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_URL; final String entityType = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_ENTITY; final String iconPath = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_ICON_PATH; BundleMaker bm = new BundleMaker(manager); File f = Os.newTempFile("osgi", "jar"); Files.copyFile(ResourceUtils.create(this).getResourceFromUrl(bundleUrl), f); String bom = Joiner.on("\n").join("brooklyn.catalog:", " bundle: " + symbolicName, " version: " + version, " id: " + symbolicName, " itemType: entity", " name: My Catalog App", " description: My description", " icon_url: classpath:" + iconPath, " item:", " type: " + entityType); f = bm.copyAdding(f,/*w w w.j a v a2 s .c o m*/ MutableMap.of(new ZipEntry("catalog.bom"), (InputStream) new ByteArrayInputStream(bom.getBytes()))); Response response = client().path("/catalog/bundles").header(HttpHeaders.CONTENT_TYPE, "application/x-zip") .post(Streams.readFully(new FileInputStream(f))); assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); TypeDetail entityItem = client().path("/catalog/types/" + symbolicName + "/" + version) .get(TypeDetail.class); Assert.assertNotNull(entityItem.getPlan().getData()); Assert.assertTrue(entityItem.getPlan().getData().toString().contains(entityType)); assertEquals(entityItem.getSymbolicName(), symbolicName); assertEquals(entityItem.getVersion(), version); // and internally let's check we have libraries RegisteredType item = getManagementContext().getTypeRegistry().get(symbolicName, version); Assert.assertNotNull(item); Collection<OsgiBundleWithUrl> libs = item.getLibraries(); assertEquals(libs.size(), 1); OsgiBundleWithUrl lib = Iterables.getOnlyElement(libs); Assert.assertNull(lib.getUrl()); assertEquals(lib.getSymbolicName(), symbolicName); assertEquals(lib.getSuppliedVersionString(), version); // now let's check other things on the item assertEquals(entityItem.getDescription(), "My description"); URI expectedIconUrl = URI.create( getEndpointAddress() + "/catalog/types/" + symbolicName + "/" + entityItem.getVersion() + "/icon") .normalize(); assertEquals(entityItem.getIconUrl(), expectedIconUrl.getPath()); assertEquals(item.getIconUrl(), "classpath:" + iconPath); if (checkTraits(false)) { // an InterfacesTag should be created for every catalog item @SuppressWarnings("unchecked") Map<String, List<String>> traitsMapTag = Iterables .getOnlyElement(Iterables.filter(entityItem.getTags(), Map.class)); List<String> actualInterfaces = traitsMapTag.get("traits"); List<String> expectedInterfaces = ImmutableList.of(Entity.class.getName(), BrooklynObject.class.getName(), Identifiable.class.getName(), Configurable.class.getName()); assertTrue(actualInterfaces.containsAll(expectedInterfaces), "actual=" + actualInterfaces); } byte[] iconData = client().path("/catalog/types/" + symbolicName + "/" + version + "/icon") .get(byte[].class); assertEquals(iconData.length, 43); // Check that the catalog item is useable (i.e. can deploy the entity) String appYaml = Joiner.on("\n").join("services:", "- type: " + symbolicName + ":" + version, " name: myEntityName"); Response appResponse = client().path("/applications").header(HttpHeaders.CONTENT_TYPE, "application/x-yaml") .post(appYaml); assertEquals(appResponse.getStatus(), Response.Status.CREATED.getStatusCode()); Entity entity = Iterables.tryFind(getManagementContext().getEntityManager().getEntities(), EntityPredicates.displayNameEqualTo("myEntityName")).get(); assertEquals(entity.getEntityType().getName(), entityType); }
From source file:com.linkedin.d2.balancer.simple.SimpleLoadBalancerTest.java
/** * This tests the getPartitionInfo() when keys are null (actually a test for KeyMapper.getAllPartitionMultipleHosts()). *//* w w w.j av a2 s .co m*/ @Test public void testGetAllPartitionMultipleHostsOrdering() throws Exception { String serviceName = "articles"; String clusterName = "cluster"; String path = "path"; String strategyName = "degrader"; //setup partition Map<URI, Map<Integer, PartitionData>> partitionDescriptions = new HashMap<URI, Map<Integer, PartitionData>>(); final URI server1 = new URI("http://foo1.com"); Map<Integer, PartitionData> server1Data = new HashMap<Integer, PartitionData>(); server1Data.put(1, new PartitionData(1.0)); server1Data.put(2, new PartitionData(1.0)); server1Data.put(3, new PartitionData(1.0)); partitionDescriptions.put(server1, server1Data); final URI server2 = new URI("http://foo2.com"); Map<Integer, PartitionData> server2Data = new HashMap<Integer, PartitionData>(); server2Data.put(1, new PartitionData(1.0)); server2Data.put(2, new PartitionData(1.0)); //server2Data.put(3, new PartitionData(1.0)); partitionDescriptions.put(server2, server2Data); final URI server3 = new URI("http://foo3.com"); Map<Integer, PartitionData> server3Data = new HashMap<Integer, PartitionData>(); server3Data.put(1, new PartitionData(1.0)); server3Data.put(2, new PartitionData(1.0)); //server3Data.put(3, new PartitionData(1.0)); partitionDescriptions.put(server3, server3Data); //setup strategy which involves tweaking the hash ring to get partitionId -> URI host List<LoadBalancerState.SchemeStrategyPair> orderedStrategies = new ArrayList<LoadBalancerState.SchemeStrategyPair>(); LoadBalancerStrategy strategy = new TestLoadBalancerStrategy(partitionDescriptions); orderedStrategies.add(new LoadBalancerState.SchemeStrategyPair("http", strategy)); //setup the partition accessor which is used to get partitionId -> keys PartitionAccessor accessor = new TestPartitionAccessor(); URI serviceURI = new URI("d2://" + serviceName); SimpleLoadBalancer balancer = new SimpleLoadBalancer(new PartitionedLoadBalancerTestState(clusterName, serviceName, path, strategyName, partitionDescriptions, orderedStrategies, accessor)); HostToKeyMapper<URI> result = balancer.getPartitionInformation(serviceURI, null, 3, 123); Assert.assertEquals(result.getPartitionInfoMap().size(), 4); Assert.assertEquals(4, result.getPartitionCount()); // partition 0 should be empty Assert.assertTrue(result.getPartitionInfoMap().get(0).getHosts().isEmpty()); // partition 1 should have server1, server2 and server3. List<URI> ordering1 = result.getPartitionInfoMap().get(1).getHosts(); List<URI> allServers = new ArrayList<>(); allServers.add(server1); allServers.add(server2); allServers.add(server3); Assert.assertTrue(ordering1.size() == 3); Assert.assertTrue(ordering1.containsAll(allServers)); // partition 2 should be the same as partition 1 List<URI> ordering2 = result.getPartitionInfoMap().get(2).getHosts(); Assert.assertEquals(ordering1, ordering2); // partition 3 should only contain server1 List<URI> ordering3 = result.getPartitionInfoMap().get(3).getHosts(); Assert.assertEquals(ordering3.get(0), server1); // partition 0 and partition 3 should not have enough hosts: lacking 3 and 2 respectively. Assert.assertTrue(result.getPartitionsWithoutEnoughHosts().containsKey(3)); Assert.assertTrue(result.getPartitionsWithoutEnoughHosts().containsKey(0)); Assert.assertEquals((int) result.getPartitionsWithoutEnoughHosts().get(3), 2); Assert.assertEquals((int) result.getPartitionsWithoutEnoughHosts().get(0), 3); }
From source file:org.apache.cloudstack.storage.datastore.util.SolidFireUtil.java
private static SolidFireUtil.SolidFireVag getCompatibleVag(SolidFireConnection sfConnection, List<HostVO> hosts) { List<SolidFireUtil.SolidFireVag> sfVags = SolidFireUtil.getAllSolidFireVags(sfConnection); if (sfVags != null) { List<String> hostIqns = new ArrayList<String>(); // where the method we're in is called, hosts should not be null for (HostVO host : hosts) { // where the method we're in is called, host.getStorageUrl() should not be null (it actually should start with "iqn") hostIqns.add(host.getStorageUrl().toLowerCase()); }/*from w w w . j a va2 s . co m*/ for (SolidFireUtil.SolidFireVag sfVag : sfVags) { List<String> lstInitiators = getStringArrayAsLowerCaseStringList(sfVag.getInitiators()); // lstInitiators should not be returned from getStringArrayAsLowerCaseStringList as null if (lstInitiators.containsAll(hostIqns)) { return sfVag; } } } throw new CloudRuntimeException("Unable to locate the appropriate SolidFire Volume Access Group"); }
From source file:org.apache.any23.extractor.microdata.MicrodataParser.java
/** * Given a document and a list of <b>itemprop</b> names this method will return * such <b>itemprops</b>./* ww w . j a va 2 s.c o m*/ * * @param node a {@link org.w3c.dom.Node} to which the refs belong * @param refs list of references. * @return list of retrieved <b>itemprop</b>s. * @throws MicrodataParserException if a loop is detected or a property name is missing. */ public ItemProp[] deferProperties(Node node, String... refs) throws MicrodataParserException { dereferenceRecursionCounter++; final List<ItemProp> result = new ArrayList<>(); try { for (String ref : refs) { if (loopDetectorSet.contains(ref)) { throw new MicrodataParserException( String.format("Loop detected with depth %d while dereferencing itemProp '%s' .", dereferenceRecursionCounter - 1, ref), null); } loopDetectorSet.add(ref); Element element = (Element) node; if (element == null) { manageError(new MicrodataParserException(String.format("Unknown itemProp id '%s'", ref), null)); continue; } List<ItemProp> propList = getItemProps(element, false); if (!result.containsAll(propList)) { result.addAll(propList); } } } catch (MicrodataParserException mpe) { if (dereferenceRecursionCounter == 1) manageError(mpe); else throw mpe; // Recursion end, this the the top call. } finally { dereferenceRecursionCounter--; if (dereferenceRecursionCounter == 0) { // Recursion end, this the the top call. loopDetectorSet.clear(); } } return result.toArray(new ItemProp[result.size()]); }
From source file:org.apache.hadoop.hive.ql.parse.CommonSubtreeDetect.java
private void removeCommonPart(HashSet<List<Object>> commonList) { HashSet<List<Object>> commonl = new HashSet<List<Object>>(); Iterator<List<Object>> listIter = commonList.iterator(); while (listIter.hasNext()) { List<Object> l = listIter.next(); Iterator<List<Object>> tmpIter = commonList.iterator(); while (tmpIter.hasNext()) { List<Object> tmpl = tmpIter.next(); if (!l.equals(tmpl) && l.containsAll(tmpl)) { commonl.add(tmpl);/*w w w. j a va2 s . c o m*/ } } //remove list that don't include operator boolean visitedOp = false; for (int i = 0; i < l.size(); i++) { if (l.get(i) instanceof Operator<?>) { visitedOp = true; break; } } if (visitedOp == false) { listIter.remove(); continue; } } //merge common sub optree for (List<Object> list : commonl) { commonList.remove(list); } }
From source file:de.skubware.opentraining.activity.create_workout.ExerciseTypeListFragment.java
/** * Filters the list of exercises for muscles and equipment. */// w ww .ja v a 2 s.co m private void filterExercisesForMusclesAndEquipment() { IDataProvider dataProvider = new DataProvider(getActivity()); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); List<Muscle> acceptedMuscles = new ArrayList<Muscle>(); for (Muscle m : dataProvider.getMuscles()) { if (sharedPrefs.getBoolean(m.toString(), true)) { acceptedMuscles.add(m); } } List<SportsEquipment> acceptedEquipment = new ArrayList<SportsEquipment>(); for (SportsEquipment e : dataProvider.getEquipment()) { if (sharedPrefs.getBoolean(e.toString(), true)) { acceptedEquipment.add(e); } } mExerciseList = dataProvider.getExercises(); for (ExerciseType ex : dataProvider.getExercises()) { boolean accepted = false; for (Muscle m : acceptedMuscles) { if (ex.getActivatedMuscles().contains(m)) accepted = true; } if (ex.getActivatedMuscles().isEmpty()) accepted = true; if (!accepted) { // Log.d(TAG, "Exercise: " + ex.toString() + " will not be shown. Muscles do not fit."); mExerciseList.remove(ex); continue; } if (!acceptedEquipment.containsAll(ex.getRequiredEquipment())) { // Log.d(TAG, "Exercise: " + ex.toString() + " will not be shown. Equipment does not fit"); mExerciseList.remove(ex); continue; } } setListAdapter(new ExerciseTypeListAdapter(getActivity(), android.R.layout.simple_list_item_single_choice, android.R.id.text1, mExerciseList)); }
From source file:org.sparkcommerce.admin.server.service.handler.SkuCustomPersistenceHandler.java
/** * Ensures that the given list of {@link ProductOptionValue} IDs is unique for the given {@link Product} * @param product//from w w w. j av a 2s . co m * @param productOptionValueIds * @param currentSku - for update operations, this is the current Sku that is being updated; should be excluded from * attempting validation * @return <b>null</b> if successfully validation, the error entity otherwise */ protected Entity validateUniqueProductOptionValueCombination(Product product, List<Property> productOptionProperties, Sku currentSku) { //do not attempt POV validation if no PO properties were passed in if (CollectionUtils.isNotEmpty(productOptionProperties)) { List<Long> productOptionValueIds = new ArrayList<Long>(); for (Property property : productOptionProperties) { productOptionValueIds.add(Long.parseLong(property.getValue())); } boolean validated = true; for (Sku sku : product.getAdditionalSkus()) { if (currentSku == null || !sku.getId().equals(currentSku.getId())) { List<Long> testList = new ArrayList<Long>(); for (ProductOptionValue optionValue : sku.getProductOptionValues()) { testList.add(optionValue.getId()); } if (CollectionUtils.isNotEmpty(testList) && productOptionValueIds.containsAll(testList) && productOptionValueIds.size() == testList.size()) { validated = false; break; } } } if (!validated) { Entity errorEntity = new Entity(); for (Property productOptionProperty : productOptionProperties) { errorEntity.addValidationError(productOptionProperty.getName(), "uniqueSkuError"); } return errorEntity; } } return null; }
From source file:org.opendaylight.vpnservice.itm.impl.ItmUtils.java
public static VtepConfigSchema validateForUpdateVtepSchema(String schemaName, List<BigInteger> lstDpnsForAdd, List<BigInteger> lstDpnsForDelete, IITMProvider itmProvider) { Preconditions.checkArgument(StringUtils.isNotBlank(schemaName)); if ((lstDpnsForAdd == null || lstDpnsForAdd.isEmpty()) && (lstDpnsForDelete == null || lstDpnsForDelete.isEmpty())) { Preconditions.checkArgument(false, new StringBuilder("DPN ID list for add | delete is null or empty in schema ").append(schemaName) .toString());//from w w w . j av a2 s . c om } VtepConfigSchema schema = itmProvider.getVtepConfigSchema(schemaName); if (schema == null) { Preconditions.checkArgument(false, new StringBuilder("Specified VTEP Schema [").append(schemaName) .append("] doesn't exists!").toString()); } List<BigInteger> existingDpnIds = getDpnIdList(schema.getDpnIds()); if (isNotEmpty(lstDpnsForAdd)) { if (isNotEmpty(existingDpnIds)) { List<BigInteger> lstAlreadyExistingDpns = new ArrayList<>(existingDpnIds); lstAlreadyExistingDpns.retainAll(lstDpnsForAdd); Preconditions.checkArgument(lstAlreadyExistingDpns.isEmpty(), new StringBuilder("DPN ID's ").append(lstAlreadyExistingDpns) .append(" already exists in VTEP schema [").append(schemaName).append("]") .toString()); } if (schema.getTunnelType().equals(TunnelTypeGre.class)) { validateForSingleGreTep(schema.getSchemaName(), lstDpnsForAdd, itmProvider.getAllVtepConfigSchemas()); } } if (isNotEmpty(lstDpnsForDelete)) { if (existingDpnIds == null || existingDpnIds.isEmpty()) { StringBuilder builder = new StringBuilder("DPN ID's ").append(lstDpnsForDelete) .append(" specified for delete from VTEP schema [").append(schemaName) .append("] are not configured in the schema."); Preconditions.checkArgument(false, builder.toString()); } else if (!existingDpnIds.containsAll(lstDpnsForDelete)) { List<BigInteger> lstConflictingDpns = new ArrayList<>(lstDpnsForDelete); lstConflictingDpns.removeAll(existingDpnIds); StringBuilder builder = new StringBuilder("DPN ID's ").append(lstConflictingDpns) .append(" specified for delete from VTEP schema [").append(schemaName) .append("] are not configured in the schema."); Preconditions.checkArgument(false, builder.toString()); } } return schema; }
From source file:org.apache.hadoop.hbase.backup.TestHFileArchiving.java
private void assertArchiveFiles(FileSystem fs, List<String> storeFiles, long timeout) throws IOException { long end = System.currentTimeMillis() + timeout; Path archiveDir = HFileArchiveUtil.getArchivePath(UTIL.getConfiguration()); List<String> archivedFiles = new ArrayList<String>(); // We have to ensure that the DeleteTableHandler is finished. HBaseAdmin.deleteXXX() can return before all files // are archived. We should fix HBASE-5487 and fix synchronous operations from admin. while (System.currentTimeMillis() < end) { archivedFiles = getAllFileNames(fs, archiveDir); if (archivedFiles.size() >= storeFiles.size()) { break; }/*from w ww . j a v a2s. c om*/ } Collections.sort(storeFiles); Collections.sort(archivedFiles); LOG.debug("Store files:"); for (int i = 0; i < storeFiles.size(); i++) { LOG.debug(i + " - " + storeFiles.get(i)); } LOG.debug("Archive files:"); for (int i = 0; i < archivedFiles.size(); i++) { LOG.debug(i + " - " + archivedFiles.get(i)); } assertTrue("Archived files are missing some of the store files!", archivedFiles.containsAll(storeFiles)); }
From source file:org.dataconservancy.dcs.util.DigestNotificationStreamTest.java
@Test public void chainedHashTest() throws Exception { final List<String> visited = new ArrayList<String>(); InputStream filtered = new ByteArrayInputStream(CONTENT.getBytes()); filtered = new DigestNotificationStream(filtered, MessageDigest.getInstance("MD5"), new DigestListener() { public void notify(byte[] digestValue) throws IOException { assertEquals(CONTENT_MD5_HEX, toHex(digestValue)); visited.add("MD5"); }// w w w.j av a 2s . c o m }); filtered = new DigestNotificationStream(filtered, MessageDigest.getInstance("SHA1"), new DigestListener() { public void notify(byte[] digestValue) throws IOException { assertEquals(CONTENT_SHA1_HEX, toHex(digestValue)); visited.add("SHA1"); } }); filtered = new DigestNotificationStream(filtered, MessageDigest.getInstance("SHA-256"), new DigestListener() { public void notify(byte[] digestValue) throws IOException { assertEquals(CONTENT_SHA256_HEX, toHex(digestValue)); visited.add("SHA-256"); } }); assertEquals(CONTENT, IOUtils.toString(filtered)); assertEquals(3, visited.size()); assertTrue(visited.containsAll(Arrays.asList("MD5", "SHA1", "SHA-256"))); }