List of usage examples for java.util Set containsAll
boolean containsAll(Collection<?> c);
From source file:edu.unc.lib.dl.services.DigitalObjectManagerMoveTest.java
@Test public void oneSourceLockFailTest() throws Exception { makeDatastream("/fedora/mdContents1.xml", MD_CONTENTS.getName(), source1PID); PairedMatcher sourceRelsExtMatcher = new PairedMatcher(); InputStream relsExtStream = this.getClass().getResourceAsStream("/fedora/containerRELSEXT1.xml"); MIMETypedStream mts = mock(MIMETypedStream.class); when(mts.getHeader()).thenReturn(dsHeaders); when(mts.getStream()).thenReturn(IOUtils.toByteArray(relsExtStream)); PairedAnswer sourceRelsExtAnswer = new PairedAnswer(mts, sourceRelsExtMatcher); // Throw locking exception on first attempt to rewrite source RELS-EXT doThrow(new OptimisticLockException("")).doNothing().when(managementClient).modifyDatastream(eq(source1PID), eq(RELS_EXT.getName()), anyString(), anyString(), argThat(sourceRelsExtMatcher)); doThrow(new OptimisticLockException("")).doNothing().when(managementClient).modifyDatastream(eq(destPID), eq(RELS_EXT.getName()), anyString(), anyString(), any(Document.class)); doThrow(new OptimisticLockException("")).doNothing().when(managementClient).modifyDatastream(eq(source1PID), eq(MD_CONTENTS.getName()), anyString(), anyString(), any(Document.class)); when(accessClient.getDatastreamDissemination(eq(source1PID), eq(RELS_EXT.getName()), anyString())) .thenAnswer(sourceRelsExtAnswer); List<PID> moving = Arrays.asList(new PID("uuid:child1"), new PID("uuid:child5")); when(tripleStoreQueryService.fetchContainer(any(PID.class))).thenReturn(source1PID); digitalMan.move(moving, destPID, "user", ""); verify(accessClient, times(3)).getDatastreamDissemination(eq(source1PID), eq(RELS_EXT.getName()), anyString());//from w w w . jav a2s.c o m ArgumentCaptor<Document> sourceRelsExtUpdateCaptor = ArgumentCaptor.forClass(Document.class); verify(managementClient, times(3)).modifyDatastream(eq(source1PID), eq(RELS_EXT.getName()), anyString(), anyString(), sourceRelsExtUpdateCaptor.capture()); List<Document> sourceRelsAnswers = sourceRelsExtUpdateCaptor.getAllValues(); // Verify that the initial source RELS-EXT update is repeated after failure Document sourceRelsExt = sourceRelsAnswers.get(0); Set<PID> removed = JDOMQueryUtil.getRelationSet(sourceRelsExt.getRootElement(), removedChild); assertEquals("Child tombstones should still be present", 2, removed.size()); sourceRelsExt = sourceRelsAnswers.get(1); removed = JDOMQueryUtil.getRelationSet(sourceRelsExt.getRootElement(), removedChild); assertEquals("Child tombstones should still be present on second try", 2, removed.size()); // Check that tombstones were cleaned up by the end of the operation Document cleanRelsExt = sourceRelsAnswers.get(2); Set<PID> children = JDOMQueryUtil.getRelationSet(cleanRelsExt.getRootElement(), contains); assertEquals("Incorrect number of children in source container after cleanup", 10, children.size()); removed = JDOMQueryUtil.getRelationSet(cleanRelsExt.getRootElement(), removedChild); assertEquals("Child tombstones not cleaned up", 0, removed.size()); // Verify that the destination had the moved children added to it ArgumentCaptor<Document> destRelsExtUpdateCaptor = ArgumentCaptor.forClass(Document.class); verify(managementClient, times(2)).modifyDatastream(eq(destPID), eq(RELS_EXT.getName()), anyString(), anyString(), destRelsExtUpdateCaptor.capture()); Document destRelsExt = destRelsExtUpdateCaptor.getValue(); children = JDOMQueryUtil.getRelationSet(destRelsExt.getRootElement(), contains); assertEquals("Incorrect number of children in destination container after moved", 9, children.size()); assertTrue("Moved children were not present in destination", children.containsAll(moving)); verify(managementClient, times(2)).modifyDatastream(eq(source1PID), eq(MD_CONTENTS.getName()), anyString(), anyString(), any(Document.class)); }
From source file:org.flite.cach3.aop.ReadThroughMultiCacheTest.java
@Test public void testInitialKey2Result() { final String ns = RandomStringUtils.randomAlphanumeric(6); final Map<String, Object> expectedString2Object = new HashMap<String, Object>(); final Map<String, Object> key2Result = new HashMap<String, Object>(); final Set<Object> missObjects = new HashSet<Object>(); final int length = 15; for (int ix = 0; ix < length; ix++) { final String object = RandomStringUtils.randomAlphanumeric(2 + ix); final String key = cut.buildCacheKey(object, ns, null); expectedString2Object.put(key, object); // There are 3 possible outcomes when fetching by key from memcached: // 0) You hit, and the key & result are in the map // 1) You hit, but the result is null, which counts as a miss. // 2) You miss, and the key doesn't even get into the result map. final int option = RandomUtils.nextInt(3); if (option == 0) { key2Result.put(key, key + RandomStringUtils.randomNumeric(5)); }// w w w.j ava2 s.c o m if (option == 1) { key2Result.put(key, null); missObjects.add(object); } if (option == 2) { missObjects.add(object); } } try { coord.setInitialKey2Result(null); fail("Expected Exception."); } catch (RuntimeException ex) { } coord.getKey2Obj().putAll(expectedString2Object); coord.setInitialKey2Result(key2Result); assertTrue(coord.getMissObjects().containsAll(missObjects)); assertTrue(missObjects.containsAll(coord.getMissObjects())); }
From source file:net.nelz.simplesm.aop.ReadThroughMultiCacheTest.java
@Test public void testInitialKey2Result() { final AnnotationData annotation = new AnnotationData(); annotation.setNamespace(RandomStringUtils.randomAlphanumeric(6)); final Map<String, Object> expectedString2Object = new HashMap<String, Object>(); final Map<String, Object> key2Result = new HashMap<String, Object>(); final Set<Object> missObjects = new HashSet<Object>(); final int length = 15; for (int ix = 0; ix < length; ix++) { final String object = RandomStringUtils.randomAlphanumeric(2 + ix); final String key = cut.buildCacheKey(object, annotation); expectedString2Object.put(key, object); // There are 3 possible outcomes when fetching by key from memcached: // 0) You hit, and the key & result are in the map // 1) You hit, but the result is null, which counts as a miss. // 2) You miss, and the key doesn't even get into the result map. final int option = RandomUtils.nextInt(3); if (option == 0) { key2Result.put(key, key + RandomStringUtils.randomNumeric(5)); }/*from w ww . j av a 2s .com*/ if (option == 1) { key2Result.put(key, null); missObjects.add(object); } if (option == 2) { missObjects.add(object); } } try { coord.setInitialKey2Result(null); fail("Expected Exception."); } catch (RuntimeException ex) { } coord.getKey2Obj().putAll(expectedString2Object); coord.setInitialKey2Result(key2Result); assertTrue(coord.getMissObjects().containsAll(missObjects)); assertTrue(missObjects.containsAll(coord.getMissObjects())); }
From source file:org.apache.kylin.cube.model.validation.rule.AggregationGroupRule.java
private void inner(CubeDesc cube, ValidateContext context) { if (cube.getAggregationGroups() == null || cube.getAggregationGroups().size() == 0) { context.addResult(ResultLevel.ERROR, "Cube should have at least one Aggregation group."); return;//w w w . j ava2 s .c o m } int index = 0; for (AggregationGroup agg : cube.getAggregationGroups()) { if (agg.getIncludes() == null) { context.addResult(ResultLevel.ERROR, "Aggregation group " + index + " 'includes' field not set"); continue; } if (agg.getSelectRule() == null) { context.addResult(ResultLevel.ERROR, "Aggregation group " + index + " 'select rule' field not set"); continue; } Set<String> includeDims = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); if (agg.getIncludes() != null) { for (String include : agg.getIncludes()) { includeDims.add(include); } } Set<String> mandatoryDims = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); if (agg.getSelectRule().mandatoryDims != null) { for (String m : agg.getSelectRule().mandatoryDims) { mandatoryDims.add(m); } } Set<String> hierarchyDims = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); if (agg.getSelectRule().hierarchyDims != null) { for (String[] ss : agg.getSelectRule().hierarchyDims) { for (String s : ss) { hierarchyDims.add(s); } } } Set<String> jointDims = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); if (agg.getSelectRule().jointDims != null) { for (String[] ss : agg.getSelectRule().jointDims) { for (String s : ss) { jointDims.add(s); } } } if (!includeDims.containsAll(mandatoryDims) || !includeDims.containsAll(hierarchyDims) || !includeDims.containsAll(jointDims)) { List<String> notIncluded = Lists.newArrayList(); final Iterable<String> all = Iterables .unmodifiableIterable(Iterables.concat(mandatoryDims, hierarchyDims, jointDims)); for (String dim : all) { if (includeDims.contains(dim) == false) { notIncluded.add(dim); } } context.addResult(ResultLevel.ERROR, "Aggregation group " + index + " 'includes' dimensions not include all the dimensions:" + notIncluded.toString()); continue; } if (CollectionUtils.containsAny(mandatoryDims, hierarchyDims)) { Set<String> intersection = new HashSet<>(mandatoryDims); intersection.retainAll(hierarchyDims); context.addResult(ResultLevel.ERROR, "Aggregation group " + index + " mandatory dimension has overlap with hierarchy dimension: " + intersection.toString()); continue; } if (CollectionUtils.containsAny(mandatoryDims, jointDims)) { Set<String> intersection = new HashSet<>(mandatoryDims); intersection.retainAll(jointDims); context.addResult(ResultLevel.ERROR, "Aggregation group " + index + " mandatory dimension has overlap with joint dimension: " + intersection.toString()); continue; } int jointDimNum = 0; if (agg.getSelectRule().jointDims != null) { for (String[] joints : agg.getSelectRule().jointDims) { Set<String> oneJoint = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); for (String s : joints) { oneJoint.add(s); } if (oneJoint.size() < 2) { context.addResult(ResultLevel.ERROR, "Aggregation group " + index + " require at least 2 dimensions in a joint: " + oneJoint.toString()); continue; } jointDimNum += oneJoint.size(); int overlapHierarchies = 0; if (agg.getSelectRule().hierarchyDims != null) { for (String[] oneHierarchy : agg.getSelectRule().hierarchyDims) { Set<String> share = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); share.addAll(CollectionUtils.intersection(oneJoint, Arrays.asList(oneHierarchy))); if (!share.isEmpty()) { overlapHierarchies++; } if (share.size() > 1) { context.addResult(ResultLevel.ERROR, "Aggregation group " + index + " joint dimensions has overlap with more than 1 dimensions in same hierarchy: " + share.toString()); continue; } } if (overlapHierarchies > 1) { context.addResult(ResultLevel.ERROR, "Aggregation group " + index + " joint dimensions has overlap with more than 1 hierarchies"); continue; } } } if (jointDimNum != jointDims.size()) { Set<String> existing = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); Set<String> overlap = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); for (String[] joints : agg.getSelectRule().jointDims) { Set<String> oneJoint = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); for (String s : joints) { oneJoint.add(s); } if (CollectionUtils.containsAny(existing, oneJoint)) { overlap.addAll(CollectionUtils.intersection(existing, oneJoint)); } existing.addAll(oneJoint); } context.addResult(ResultLevel.ERROR, "Aggregation group " + index + " a dimension exists in more than one joint: " + overlap.toString()); continue; } } long combination = 0; try { combination = agg.calculateCuboidCombination(); } catch (Exception ex) { combination = getMaxCombinations(cube) + 1; } finally { if (combination > getMaxCombinations(cube)) { String msg = "Aggregation group " + index + " has too many combinations, current combination is " + combination + ", max allowed combination is " + getMaxCombinations(cube) + "; use 'mandatory'/'hierarchy'/'joint' to optimize; or update 'kylin.cube.aggrgroup.max-combination' to a bigger value."; context.addResult(ResultLevel.ERROR, msg); continue; } } index++; } }
From source file:com.aurel.track.admin.customize.category.filter.execute.loadItems.LoadTreeFilterItems.java
/** * Gets the item types for projects allowed to read * @param selectedAndDescendantProjects/*from ww w .j a v a 2 s .c o m*/ * @param selectedItemTypesSet * @param projectToIssueTypesWithReadRight * @param childToParentProjectIDMap * @param raciProjectIDs no direct right but may have raci roles used later * @return */ static Map<Set<Integer>, Set<Integer>> getItemTypesToProjectsMap(Integer[] selectedAndDescendantProjects, Set<Integer> selectedItemTypesSet, Map<Integer, Set<Integer>> projectToIssueTypesWithReadRight, Map<Integer, Integer> childToParentProjectIDMap, Set<Integer> raciProjectIDs) { Map<Set<Integer>, Set<Integer>> itemTypesToProjectsMap = new HashMap<Set<Integer>, Set<Integer>>(); for (Integer projectKey : selectedAndDescendantProjects) { String projectLabel = null; if (LOGGER.isDebugEnabled()) { projectLabel = LookupContainer.getNotLocalizedLabelBeanLabel(SystemFields.INTEGER_PROJECT, projectKey); } Set<Integer> itemTypeLimitations = AccessBeans.getItemTypeLimitations(projectKey, selectedItemTypesSet, projectToIssueTypesWithReadRight, childToParentProjectIDMap); if (itemTypeLimitations == null) { raciProjectIDs.add(projectKey); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "No right for project " + projectLabel + " (" + projectKey + "). Add to RACI projects"); } } else { if (itemTypeLimitations.contains(null)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Project " + projectLabel + " (" + projectKey + ") has no item type limitation by role"); } } else { if (selectedItemTypesSet.isEmpty()) { raciProjectIDs.add(projectKey); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "No items types selected in filter but there are item type limitations by role in project " + projectLabel + " (" + projectKey + "). Add to RACI projects"); } } else { if (itemTypeLimitations.containsAll(selectedItemTypesSet)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("All selected items types in filter are allowed by role in project " + projectLabel + " (" + projectKey + ")"); } } else { raciProjectIDs.add(projectKey); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Some selected items types in filter are not allowed by role in project " + projectLabel + " (" + projectKey + "). Add to RACI projects"); } } } } Set<Integer> projectIDs = itemTypesToProjectsMap.get(itemTypeLimitations); if (projectIDs == null) { projectIDs = new HashSet<Integer>(); itemTypesToProjectsMap.put(itemTypeLimitations, projectIDs); } projectIDs.add(projectKey); } } return itemTypesToProjectsMap; }
From source file:org.codice.ddf.spatial.ogc.csw.catalog.source.CswSource.java
/** * Searches every query response for previously unknown content types * * @param response A Query Response/*from w w w.ja v a 2 s. com*/ */ private void addContentTypes(SourceResponse response) { if (response == null || response.getResults() == null) { return; } if (contentTypeMappingUpdated) { LOGGER.debug("{}: The content type mapping has been updated. Removing all old content types.", cswSourceConfiguration.getId()); contentTypes.clear(); } for (Result result : response.getResults()) { Metacard metacard = result.getMetacard(); if (metacard != null) { addContentType(metacard.getContentTypeName(), metacard.getContentTypeVersion(), metacard.getContentTypeNamespace()); } } Configuration[] managedConfigs = getManagedConfigs(); if (managedConfigs != null) { for (Configuration managedConfig : managedConfigs) { Dictionary<String, Object> properties = managedConfig.getProperties(); Set<String> current = new HashSet<String>( Arrays.asList((String[]) properties.get(CONTENTTYPES_PROPERTY))); if (contentTypeMappingUpdated || (current != null && !current.containsAll(contentTypes.keySet()))) { LOGGER.debug("{}: Adding new content types {} for content type mapping: {}.", cswSourceConfiguration.getId(), contentTypes.toString(), cswSourceConfiguration.getContentTypeMapping()); properties.put(CONTENTTYPES_PROPERTY, contentTypes.keySet().toArray(new String[0])); properties.put(CONTENT_TYPE_MAPPING_PROPERTY, cswSourceConfiguration.getContentTypeMapping()); try { LOGGER.debug("{}: Updating CSW Federated Source configuration with {}.", cswSourceConfiguration.getId(), properties.toString()); managedConfig.update(properties); } catch (IOException e) { LOGGER.warn("{}: Failed to update managedConfiguration with new contentTypes, Error: {}", cswSourceConfiguration.getId(), e); } } } } }
From source file:com.google.code.ssm.aop.ReadThroughMultiCacheTest.java
@Test public void testInitialKey2Result() { final AnnotationData annotation = new AnnotationData(); annotation.setNamespace(RandomStringUtils.randomAlphanumeric(6)); final Map<String, Object> expectedString2Object = new HashMap<String, Object>(); final Map<String, Object> key2Result = new HashMap<String, Object>(); final Set<Object> missObjects = new HashSet<Object>(); final int length = 15; for (int ix = 0; ix < length; ix++) { final String object = RandomStringUtils.randomAlphanumeric(2 + ix); final String key = cut.getCacheBase().getCacheKeyBuilder().getCacheKey(object, annotation.getNamespace()); expectedString2Object.put(key, object); // There are 3 possible outcomes when fetching by key from memcached: // 0) You hit, and the key & result are in the map // 1) You hit, but the result is null, which counts as a miss. // 2) You miss, and the key doesn't even get into the result map. final int option = RandomUtils.nextInt(3); if (option == 0) { key2Result.put(key, key + RandomStringUtils.randomNumeric(5)); }//www .j a va2 s . c o m if (option == 1) { key2Result.put(key, null); missObjects.add(object); } if (option == 2) { missObjects.add(object); } } try { coord.setInitialKey2Result(null); fail("Expected Exception."); } catch (RuntimeException ex) { } coord.getKey2Obj().putAll(expectedString2Object); coord.setInitialKey2Result(key2Result); assertTrue(coord.getMissedObjects().containsAll(missObjects)); assertTrue(missObjects.containsAll(coord.getMissedObjects())); }
From source file:de.iteratec.iteraplan.presentation.UserContextInitializationServiceImpl.java
/** * Stores the user's login name and the user's roles to the session. The stored information is * used in {@link de.iteratec.iteraplan.presentation.dialogs.Start.InitCommand} to create the * {@link UserContext} object.//from w w w . j av a2s. c om * * Retrieves all information about the logged-in user from the iteraplan database, creates the * {@link UserContext} filled with the respective values of the logged-in user and stores the * context in the global memory. Also checks, if the user's password has expired. If the user * context already exists, nothing is done. * * @return An error message key or null if everything was successful. */ private String createAndStoreUserContext(HttpServletRequest req, Authentication authentication) { HttpSession session = req.getSession(); String userLogin = StringUtils.trim(authentication.getName()); session.setAttribute(LOGGED_IN_USER_LOGIN, userLogin); // Make sure that the MASTER data source is used upon login. The user's context stored in the // thread local of the UserContext is not null, if the user has already logged into iteraplan // previously and the server has not been restarted since. Note that though the session has // been invalidated on logout (see Spring Security configuration), but the UserContext is still // there. // Thus the reference to the data source that the user connects to must be explicitly set to // the MASTER data source. Otherwise the data source stored in the context is used, but the // according database does usually not contain all the data necessary for a successful login // (e.g. the role for the demo access to iteraplan). if (UserContext.getCurrentUserContext() != null) { LOGGER.info("Point the user to the MASTER data source."); UserContext.getCurrentUserContext().setDataSource(Constants.MASTER_DATA_SOURCE); } final Set<String> userRoles = getUserRoles(authentication); session.setAttribute(LOGGED_IN_USER_ROLES, userRoles); User user = userService.getUserByLoginIfExists(userLogin); final Set<Role> roles = loadRoles(userRoles); Locale locale = RequestContextUtils.getLocale(req); // Create and store user context. UserContext userContext = new UserContext(userLogin, roles, locale, user); UserContext.setCurrentUserContext(userContext); session.setAttribute(SessionConstants.USER_CONTEXT, userContext); LOGGER.debug("User context created and stored in user's session."); LOGIN_LOGGER.info(userContext.toCSVString()); if (user == null) { user = userService.createUser(userLogin); // Create and store user context. // the new user can only be created after the user context is set (above) // as the update of an entity triggers the LastModificationInterceptor, which // expects an already set user context userContext = new UserContext(userLogin, roles, locale, user); UserContext.detachCurrentUserContext(); UserContext.setCurrentUserContext(userContext); session.setAttribute(SessionConstants.USER_CONTEXT, userContext); } readLdapData(authentication.getPrincipal(), user); if (roles != null && !roles.isEmpty() && !(roles.containsAll(user.getRoles()) && user.getRoles().containsAll(roles))) { user.clearRoles(); for (Role role : roles) { user.addRoleTwoWay(role); } userService.saveOrUpdate(user); } final String errorMessageKey = createDataSource(userContext); if (errorMessageKey != null) { return errorMessageKey; } LOGGER.info("User has logged in."); // notify ElasticeamService (bean), that the metamodel and model for the 'new' datasource needs to be loaded elasticService.initOrReload(); //Create elasticMiContext ElasticMiContext elasticMiContext = elasticMiContextAndStakeholderManagerInitializationService .initializeMiContextAndStakeholderManager(userLogin, userContext.getDataSource()); session.setAttribute(SessionConstants.ELASTIC_MI_CONTEXT, elasticMiContext); return null; }
From source file:com.aurel.track.accessControl.AccessBeans.java
/** * Add restrictions/* ww w . j a v a 2 s .com*/ * * @param resultMap * @param roles * @param restrictedFieldsToRoles * @param restriction */ static void addRestrictions(Map<Integer, Integer> resultMap, Set<Integer> roles, Map<Integer, Set<Integer>> restrictedFieldsToRoles, Integer restriction) { for (Integer fieldID : restrictedFieldsToRoles.keySet()) { Set<Integer> restrictedRoles = restrictedFieldsToRoles.get(fieldID); if (restrictedRoles != null && restrictedRoles.containsAll(roles)) { // field is restricted in all roles resultMap.put(fieldID, restriction); } } }