List of usage examples for java.util Set removeAll
boolean removeAll(Collection<?> c);
From source file:com.tesora.dve.tools.DVEAnalyzerCLI.java
private static <T extends TableTemplateType> Set<T> getIntersection(final Set<T> a, final Set<T> b, final Comparator<? super T> comparator) { final Set<T> intersection = new TreeSet<T>(comparator); intersection.addAll(a);/*from www .jav a 2s .c o m*/ final Set<T> difference = getDifference(intersection, b, comparator); intersection.removeAll(difference); return intersection; }
From source file:gaffer.store.Store.java
protected boolean validateTwoSetsContainSameElements(final Set<String> firstSet, final Set<String> secondSet, final String type) { final Set<String> firstSetCopy = Sets.newHashSet(firstSet); final Set<String> secondSetCopy = Sets.newHashSet(secondSet); firstSetCopy.removeAll(secondSetCopy); secondSetCopy.removeAll(firstSet);/*from ww w . j a v a 2 s .co m*/ boolean valid = true; if (!firstSetCopy.isEmpty()) { valid = false; LOGGER.warn("the data schema contains the following " + type + " which are not in the store schema: {" + StringUtils.join(firstSetCopy, ", ") + " }"); } if (!secondSetCopy.isEmpty()) { valid = false; LOGGER.warn("the store schema contains the following " + type + " which are not in the data schema: {" + StringUtils.join(secondSetCopy, ", ") + " }"); } return valid; }
From source file:com.addthis.ahocorasick.TestAhoCorasick.java
private void randomOneIteration(int iter) { Random random = new Random(); Set<String> elements = new LinkedHashSet<>(); AhoCorasick tree = AhoCorasick.builder().build(); for (int i = 0; i < 10; i++) { int length = random.nextInt(MAX_LENGTH - MIN_LENGTH) + MIN_LENGTH; String candidate = RandomStringUtils.random(length, 'a', 'b', 'c'); elements.add(candidate);/*from w ww.j ava2s. c om*/ tree.add(candidate); } tree.prepare(); StringBuilder builder = new StringBuilder(); for (String element : elements) { builder.append(element); } String input = builder.toString(); List<OutputResult> results = tree.completeSearch(input, true, false); Set<String> output = new HashSet<>(); for (OutputResult outputResult : results) { output.add(outputResult.getOutput().toString()); } if (elements.size() > output.size()) { Set<String> extra = new LinkedHashSet<>(elements); extra.removeAll(output); fail("At iteration " + iter + " did not find the elements: " + extra + " out of the input set: " + elements); } else if (elements.size() < output.size()) { output.removeAll(elements); fail("At iteration " + iter + " + found extra elements: " + output); } }
From source file:io.cloudslang.lang.compiler.validator.PreCompileValidatorImpl.java
private void validateResultsAreReachable(Set<String> reachableResultNames, List<String> resultNames, List<RuntimeException> errors) { Set<String> unreachableResultNames = new HashSet<>(resultNames); unreachableResultNames.removeAll(reachableResultNames); if (!unreachableResultNames.isEmpty()) { errors.add(/* w ww . j a v a 2 s . c o m*/ new RuntimeException("The following results are not wired: " + unreachableResultNames + ".")); } }
From source file:com.microsoft.tfs.core.clients.workitem.internal.metadata.ConstantSet.java
private Set<Integer> query(final DBConnection connection, // the DB connection to use final Set<Integer> rootIds, // these IDs form the starting set final boolean addLeaf, // leaf node values should be added to this // constant set final boolean addNonLeaf, // non-leaf node values should be added to // this constant set final boolean needChildren) // we need to return children ids that are // non-leaf nodes { final Set<Integer> childIds = getChildIDs(connection, rootIds); final Set<Integer> selfContainedIds = new HashSet<Integer>(rootIds); selfContainedIds.retainAll(childIds); childIds.removeAll(selfContainedIds); final Set<Integer> idsToAdd = new HashSet<Integer>(); Set<Integer> nonLeafChildIds = new HashSet<Integer>(); if (addLeaf) { final Set<Integer> leafIds = new HashSet<Integer>(childIds); leafIds.removeAll(distinctConstantSetIds); leafIds.addAll(selfContainedIds); idsToAdd.addAll(leafIds);/*from w ww.j a va2s .co m*/ } if (addNonLeaf | needChildren) { nonLeafChildIds = new HashSet<Integer>(childIds); nonLeafChildIds.retainAll(distinctConstantSetIds); if (addNonLeaf) { idsToAdd.addAll(nonLeafChildIds); } } if (idsToAdd.size() > 0) { final StringBuffer sb = new StringBuffer( "select ConstID, String, DisplayName from Constants where ConstID in ("); //$NON-NLS-1$ for (final Iterator<Integer> it = idsToAdd.iterator(); it.hasNext();) { final Integer i = it.next(); sb.append(i); if (it.hasNext()) { sb.append(","); //$NON-NLS-1$ } } sb.append(")"); //$NON-NLS-1$ connection.createStatement(sb.toString()).executeQuery(new ResultHandler() { @Override public void handleRow(final ResultSet rset) throws SQLException { final int constId = rset.getInt(1); final String string = rset.getString(2); final String displayName = rset.getString(3); values.add(displayName != null ? displayName : string); constIds.add(new Integer(constId)); } }); } if (needChildren) { return nonLeafChildIds; } else { return Collections.emptySet(); } }
From source file:com.foilen.smalltools.spring.messagesource.UsageMonitoringMessageSource.java
private void init() { // Check the base folder File basenameFile = new File(basename); logger.info("Base name is {}", basename); File directory = basenameFile.getParentFile(); logger.info("Base directory is {}", directory.getAbsoluteFile()); if (!directory.exists()) { throw new SmallToolsException("Directory: " + directory.getAbsolutePath() + " does not exists"); }/*from w w w. j a va 2s . co m*/ tmpUsed = new File(directory.getAbsolutePath() + File.separatorChar + "_messages_usage.txt"); // Check the files in it String startswith = basenameFile.getName() + "_"; String endswith = ".properties"; for (File file : directory.listFiles( (FilenameFilter) (dir, name) -> name.startsWith(startswith) && name.endsWith(endswith))) { // Create the locale logger.info("Found messages file {}", directory.getAbsoluteFile()); String filename = file.getName(); String localePart = filename.substring(startswith.length(), filename.length() - endswith.length()); Locale locale = new Locale(localePart); logger.info("Locale is {} -> {}", localePart, locale); filePerLocale.put(locale, file); // Load the file Properties properties = new Properties(); try (FileInputStream inputStream = new FileInputStream(file)) { properties.load(new InputStreamReader(inputStream, CharsetTools.UTF_8)); } catch (IOException e) { logger.error("Problem reading the property file {}", file.getAbsoluteFile(), e); throw new SmallToolsException("Problem reading the file", e); } // Check codes and save values Map<String, String> messages = new HashMap<>(); messagesPerLocale.put(locale, messages); for (Object key : properties.keySet()) { String name = (String) key; String value = properties.getProperty(name); allCodesInFiles.add(name); messages.put(name, value); } } // Add missing codes in all the maps (copy one that has it) for (Locale locale : filePerLocale.keySet()) { Set<String> missingCodes = new HashSet<>(); Map<String, String> messagesForCurrentLocale = messagesPerLocale.get(locale); // Get the ones missing missingCodes.addAll(allCodesInFiles); missingCodes.removeAll(messagesForCurrentLocale.keySet()); for (String missingCode : missingCodes) { logger.info("Locale {} was missing code {}", locale, missingCode); String codeValue = findAnyValue(missingCode); messagesForCurrentLocale.put(missingCode, codeValue); } } // Load the already known codes if (tmpUsed.exists()) { for (String line : FileTools.readFileLinesIteration(tmpUsed.getAbsolutePath())) { knownUsedCodes.add(line); } } smoothTrigger = new SmoothTrigger(() -> { synchronized (lock) { logger.info("Begin saving locale files"); // Go through each locale for (Entry<Locale, File> entry : filePerLocale.entrySet()) { Map<String, String> messages = messagesPerLocale.get(entry.getKey()); try (PrintWriter printWriter = new PrintWriter(entry.getValue(), CharsetTools.UTF_8.toString())) { // Save the known used (sorted) at the top for (String code : knownUsedCodes.stream().sorted(String.CASE_INSENSITIVE_ORDER) .collect(Collectors.toList())) { printWriter.println(code + "=" + messages.get(code)); } printWriter.println(); // Save the others (sorted) at the bottom Set<String> unknownCodes = new HashSet<>(); unknownCodes.addAll(messages.keySet()); unknownCodes.removeAll(knownUsedCodes); if (!unknownCodes.isEmpty()) { printWriter.println("# Unknown"); printWriter.println(); for (String code : unknownCodes.stream().sorted(String.CASE_INSENSITIVE_ORDER) .collect(Collectors.toList())) { printWriter.println(code + "=" + messages.get(code)); } printWriter.println(); } } catch (Exception e) { logger.error("Could not write the file", e); } } // Save the known FileTools.writeFile(Joiner.on('\n').join( knownUsedCodes.stream().sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.toList())), tmpUsed); logger.info("Done saving locale files"); } }) // .setDelayAfterLastTriggerMs(5000) // .setMaxDelayAfterFirstRequestMs(10000) // .setFirstPassThrough(true) // .start(); smoothTrigger.request(); }
From source file:com.redhat.rhn.frontend.xmlrpc.user.external.UserExternalHandler.java
private void removeImpliedRoles(Set<Role> roles) { if (roles.contains(RoleFactory.ORG_ADMIN)) { roles.removeAll(UserFactory.IMPLIEDROLES); }//from w w w .j av a 2 s .c o m }
From source file:org.cateproject.features.FeatureStoreSpringJDBC.java
/** {@inheritDoc} */ @Override/*from www . j a va 2 s.co m*/ @Transactional public void update(Feature fp) { if (fp == null) { throw new IllegalArgumentException("Feature cannot be null nor empty"); } Feature fpExist = read(fp.getUid()); // Update core Flip POINT String fStrategy = null; String fExpression = null; if (fp.getFlippingStrategy() != null) { fStrategy = fp.getFlippingStrategy().getClass().getCanonicalName(); fExpression = ParameterUtils.fromMap(fp.getFlippingStrategy().getInitParams()); } String enable = "0"; if (fp.isEnable()) { enable = "1"; } getJdbcTemplate().update(SQL_UPDATE, enable, fp.getDescription(), fStrategy, fExpression, fp.getGroup(), fp.getUid()); // To be deleted : not in second but in first Set<String> toBeDeleted = new HashSet<String>(); toBeDeleted.addAll(fpExist.getPermissions()); toBeDeleted.removeAll(fp.getPermissions()); for (String roleToBeDelete : toBeDeleted) { removeRoleFromFeature(fpExist.getUid(), roleToBeDelete); } // To be created : in second but not in first Set<String> toBeAdded = new HashSet<String>(); toBeAdded.addAll(fp.getPermissions()); toBeAdded.removeAll(fpExist.getPermissions()); for (String addee : toBeAdded) { grantRoleOnFeature(fpExist.getUid(), addee); } // enable/disable if (fp.isEnable() != fpExist.isEnable()) { if (fp.isEnable()) { enable(fp.getUid()); } else { disable(fp.getUid()); } } }
From source file:com.aurel.track.admin.customize.category.filter.execute.loadItems.LoadItemLinksUtil.java
/** * Get the linked items: either linked though parent or children hierarchy or through plugin links * It is very important to remove those linked/parent/child issues which are * already contained in the result set to avoid adding them once again * @param linkTypeFilterSuperset/*www .java 2 s . c o m*/ * @param archived * @param deleted * @param itemTypesList * @param baseWorkItemBeanList */ public static int[] getLinkedWorkItemIDs(String linkTypeFilterSuperset, Integer archived, Integer deleted, List<Integer> itemTypesList, List<TWorkItemBean> baseWorkItemBeanList) { if (linkTypeFilterSuperset == null || "".equals(linkTypeFilterSuperset) || baseWorkItemBeanList == null || baseWorkItemBeanList.isEmpty()) { return null; } else { List<Integer> baseWorkItemIDsList = GeneralUtils.createIntegerListFromBeanList(baseWorkItemBeanList); int[] baseWorkItemIDsArr = GeneralUtils.createIntArrFromIntegerList(baseWorkItemIDsList); Integer[] parts = MergeUtil.getParts(linkTypeFilterSuperset); Integer linkType = parts[0]; Integer direction = parts[1]; Set<Integer> linkedWorkItemIDsSet = null; if (ILinkType.PARENT_CHILD == linkType.intValue()) { if (PARENT_CHILD_EXPRESSION.ALL_PARENTS == direction) { linkedWorkItemIDsSet = getParentHierarchy(baseWorkItemBeanList, archived, deleted); } else { linkedWorkItemIDsSet = ItemBL.getChildHierarchy(baseWorkItemIDsArr, direction, archived, deleted, itemTypesList); } } else { Map<Integer, SortedSet<Integer>> linkedWorkItemIDsMap = getLinkedWorkItemIDsMap(baseWorkItemIDsList, linkType, direction, archived, deleted); linkedWorkItemIDsSet = getFlatItems(linkedWorkItemIDsMap); } //remove those linked/parent/child issues which are //already contained in the result set to avoid adding them once again if (linkedWorkItemIDsSet != null) { linkedWorkItemIDsSet.removeAll(GeneralUtils.createSetFromIntArr(baseWorkItemIDsArr)); } return GeneralUtils.createIntArrFromSet(linkedWorkItemIDsSet); } }
From source file:org.syncope.core.rest.data.UserDataBinder.java
/** * Update user, given UserMod.//from ww w. jav a2 s. c o m * * @param user to be updated * @param userMod bean containing update request * @return updated user + propagation by resource * @throws SyncopeClientCompositeErrorException if anything goes wrong * @see PropagationByResource */ public PropagationByResource update(final SyncopeUser user, final UserMod userMod) throws SyncopeClientCompositeErrorException { PropagationByResource propByRes = new PropagationByResource(); SyncopeClientCompositeErrorException scce = new SyncopeClientCompositeErrorException( HttpStatus.BAD_REQUEST); // when requesting to add user to new resources, either directly or // through role subscription, password is mandatory (issue 147) // first, let's take current resources into account Set<String> currentResources = user.getResourceNames(); // password if (userMod.getPassword() != null) { int passwordHistorySize = 0; try { Policy policy = policyDAO.getGlobalPasswordPolicy(); PasswordPolicySpec passwordPolicy = policy.getSpecification(); passwordHistorySize = passwordPolicy.getHistoryLength(); } catch (Throwable ignore) { // ignore exceptions } user.setPassword(userMod.getPassword(), getCipherAlgoritm(), passwordHistorySize); user.setChangePwdDate(new Date()); propByRes.addAll(PropagationOperation.UPDATE, user.getResourceNames()); } // username if (userMod.getUsername() != null && !userMod.getUsername().equals(user.getUsername())) { String oldUsername = user.getUsername(); user.setUsername(userMod.getUsername()); propByRes.addAll(PropagationOperation.UPDATE, user.getResourceNames()); for (ExternalResource resource : user.getResources()) { for (SchemaMapping mapping : resource.getMappings()) { if (mapping.isAccountid() && mapping.getIntMappingType() == IntMappingType.Username) { propByRes.addOldAccountId(resource.getName(), oldUsername); } } } } // attributes, derived attributes, virtual attributes and resources propByRes.merge(fill(user, userMod, AttributableUtil.USER, scce)); // store the role ids of membership required to be added Set<Long> membershipToBeAddedRoleIds = new HashSet<Long>(); for (MembershipMod membToBeAdded : userMod.getMembershipsToBeAdded()) { membershipToBeAddedRoleIds.add(membToBeAdded.getRole()); } // memberships to be removed Membership membership = null; for (Long membershipId : userMod.getMembershipsToBeRemoved()) { LOG.debug("Membership to be removed: {}", membershipId); membership = membershipDAO.find(membershipId); if (membership == null) { LOG.debug("Invalid membership id specified to be removed: {}", membershipId); } else { for (ExternalResource resource : membership.getSyncopeRole().getResources()) { if (!membershipToBeAddedRoleIds.contains(membership.getSyncopeRole().getId())) { propByRes.add(PropagationOperation.DELETE, resource.getName()); } } // In order to make the removeMembership() below to work, // we need to be sure to take exactly the same membership // of the user object currently in memory (which has potentially // some modifications compared to the one stored in the DB membership = user.getMembership(membership.getSyncopeRole().getId()); if (membershipToBeAddedRoleIds.contains(membership.getSyncopeRole().getId())) { Set<Long> attributeIds = new HashSet<Long>(membership.getAttributes().size()); for (AbstractAttr attribute : membership.getAttributes()) { attributeIds.add(attribute.getId()); } for (Long attributeId : attributeIds) { attributeDAO.delete(attributeId, MAttr.class); } attributeIds.clear(); // remove derived attributes for (AbstractDerAttr derAttr : membership.getDerivedAttributes()) { attributeIds.add(derAttr.getId()); } for (Long derAttrId : attributeIds) { derAttrDAO.delete(derAttrId, MDerAttr.class); } attributeIds.clear(); // remove virtual attributes for (AbstractVirAttr virAttr : membership.getVirtualAttributes()) { attributeIds.add(virAttr.getId()); } for (Long virAttrId : attributeIds) { virAttrDAO.delete(virAttrId, MVirAttr.class); } attributeIds.clear(); } else { user.removeMembership(membership); membershipDAO.delete(membershipId); } } } // memberships to be added for (MembershipMod membershipMod : userMod.getMembershipsToBeAdded()) { LOG.debug("Membership to be added: role({})", membershipMod.getRole()); SyncopeRole role = roleDAO.find(membershipMod.getRole()); if (role == null) { LOG.debug("Ignoring invalid role {}", membershipMod.getRole()); } else { membership = user.getMembership(role.getId()); if (membership == null) { membership = new Membership(); membership.setSyncopeRole(role); membership.setSyncopeUser(user); user.addMembership(membership); propByRes.addAll(PropagationOperation.UPDATE, role.getResourceNames()); } propByRes.merge(fill(membership, membershipMod, AttributableUtil.MEMBERSHIP, scce)); } } // now, let's see if there are new resource subscriptions without // providing password Set<String> updatedResources = user.getResourceNames(); updatedResources.removeAll(currentResources); if (!updatedResources.isEmpty() && StringUtils.isBlank(userMod.getPassword())) { SyncopeClientException sce = new SyncopeClientException( SyncopeClientExceptionType.RequiredValuesMissing); sce.addElement("password cannot be empty " + "when subscribing to new resources"); scce.addException(sce); throw scce; } return propByRes; }