List of usage examples for com.google.common.collect Sets symmetricDifference
public static <E> SetView<E> symmetricDifference(final Set<? extends E> set1, final Set<? extends E> set2)
From source file:org.mifosplatform.portfolio.group.service.GroupWritePlatformServiceJpaRepositoryImpl.java
@Transactional @Override//from w w w.j ava 2 s .co m public CommandProcessingResult updateGroup(final Long grouptId, final JsonCommand command) { GroupLevel groupLevel = null; try { this.context.authenticatedUser(); final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(9); this.fromApiJsonDeserializer.validateForUpdate(command.json()); final Group groupForUpdate = this.groupRepository.findOne(grouptId); if (groupForUpdate == null || groupForUpdate.isDeleted()) { throw new GroupNotFoundException(grouptId); } final Long officeId = groupForUpdate.getOfficeId(); final String nameParamName = "name"; if (command.isChangeInStringParameterNamed(nameParamName, groupForUpdate.getName())) { final String newValue = command.stringValueOfParameterNamed(nameParamName); actualChanges.put(nameParamName, newValue); groupForUpdate.setName(StringUtils.defaultIfEmpty(newValue, null)); } final String externalIdParamName = "externalId"; if (command.isChangeInStringParameterNamed(externalIdParamName, groupForUpdate.getExternalId())) { final String newValue = command.stringValueOfParameterNamed(externalIdParamName); actualChanges.put(externalIdParamName, newValue); groupForUpdate.setExternalId(StringUtils.defaultIfEmpty(newValue, null)); } final Staff presentStaff = groupForUpdate.getStaff(); Long presentStaffId = null; if (presentStaff != null) { presentStaffId = presentStaff.getId(); } final String staffIdParamName = "staffId"; if (command.isChangeInLongParameterNamed(staffIdParamName, presentStaffId)) { final Long newValue = command.longValueOfParameterNamed(staffIdParamName); actualChanges.put(staffIdParamName, newValue); Staff newStaff = null; if (newValue != null) { newStaff = this.staffRepository.findByOffice(newValue, officeId); if (newStaff == null) { throw new StaffNotFoundException(newValue); } } groupForUpdate.setStaff(newStaff); } groupLevel = this.groupLevelRepository.findOne(groupForUpdate.getGroupLevel().getId()); /* * Ignoring parentId param, if group for update is super parent. * TODO Need to check: Ignoring is correct or need throw unsupported * param */ if (!groupLevel.isSuperParent()) { final String parentIdParamName = "parentId"; Long parentId = null; final Group presentParentGroup = groupForUpdate.getParent(); if (presentParentGroup != null) { parentId = presentParentGroup.getId(); } if (command.isChangeInLongParameterNamed(parentIdParamName, parentId)) { final Long newValue = command.longValueOfParameterNamed(parentIdParamName); actualChanges.put(parentIdParamName, newValue); Group newParentGroup = null; if (newValue != null) { newParentGroup = this.groupRepository.findOne(newValue); if (newParentGroup == null || newParentGroup.isDeleted()) { throw new StaffNotFoundException(newValue); } if (!newParentGroup.isOfficeIdentifiedBy(officeId)) { final String errorMessage = "Group and parent group must have the same office"; throw new InvalidOfficeException("group", "attach.to.parent.group", errorMessage); } /* * If Group is not super parent then validate group * level's parent level is same as group parent's level * this check makes sure new group is added at immediate * next level in hierarchy */ if (!groupForUpdate.getGroupLevel() .isIdentifiedByParentId(newParentGroup.getGroupLevel().getId())) { final String errorMessage = "Parent group's level is not equal to child level's parent level "; throw new InvalidGroupLevelException("add", "invalid.level", errorMessage); } } groupForUpdate.setParent(newParentGroup); // Parent has changed, re-generate 'Hierarchy' as parent is changed groupForUpdate.generateHierarchy(); } } final Set<Client> clientMembers = assembleSetOfClients(officeId, command); final String clientMembersParamName = "clientMembers"; if (!clientMembers.equals(groupForUpdate.getClientMembers())) { Set<Client> diffClients = Sets.symmetricDifference(clientMembers, groupForUpdate.getClientMembers()); final String[] diffClientsIds = getClientIds(diffClients); actualChanges.put(clientMembersParamName, diffClientsIds); groupForUpdate.setClientMembers(clientMembers); } this.groupRepository.saveAndFlush(groupForUpdate); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withOfficeId(groupForUpdate.getId()) // .withGroupId(groupForUpdate.getOfficeId()) // .withEntityId(groupForUpdate.getId()) // .with(actualChanges) // .build(); } catch (final DataIntegrityViolationException dve) { handleGroupDataIntegrityIssues(command, dve, groupLevel); return new CommandProcessingResult(Long.valueOf(-1)); } }
From source file:org.apache.accumulo.core.clientImpl.bulk.BulkImport.java
private SortedMap<KeyExtent, Files> computeMappingFromPlan(FileSystem fs, TableId tableId, Path srcPath) throws IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException { Map<String, List<Destination>> fileDestinations = plan.getDestinations().stream() .collect(groupingBy(Destination::getFileName)); List<FileStatus> statuses = filterInvalid( fs.listStatus(srcPath, p -> !p.getName().equals(Constants.BULK_LOAD_MAPPING))); Map<String, Long> fileLens = getFileLenMap(statuses); if (!fileDestinations.keySet().equals(fileLens.keySet())) { throw new IllegalArgumentException( "Load plan files differ from directory files, symmetric difference : " + Sets.symmetricDifference(fileDestinations.keySet(), fileLens.keySet())); }/* w ww .j a v a2 s . c o m*/ KeyExtentCache extentCache = new ConcurrentKeyExtentCache(tableId, context); // Pre-populate cache by looking up all end rows in sorted order. Doing this in sorted order // leverages read ahead. fileDestinations.values().stream().flatMap(List::stream) .filter(dest -> dest.getRangeType() == RangeType.FILE) .flatMap(dest -> Stream.of(dest.getStartRow(), dest.getEndRow())).filter(row -> row != null) .map(Text::new).sorted().distinct().forEach(row -> { try { extentCache.lookup(row); } catch (Exception e) { throw new RuntimeException(e); } }); SortedMap<KeyExtent, Files> mapping = new TreeMap<>(); for (Entry<String, List<Destination>> entry : fileDestinations.entrySet()) { String fileName = entry.getKey(); List<Destination> destinations = entry.getValue(); Set<KeyExtent> extents = mapDesitnationsToExtents(tableId, extentCache, destinations); long estSize = (long) (fileLens.get(fileName) / (double) extents.size()); for (KeyExtent keyExtent : extents) { mapping.computeIfAbsent(keyExtent, k -> new Files()).add(new FileInfo(fileName, estSize, 0)); } } return mergeOverlapping(mapping); }
From source file:org.apache.accumulo.core.clientImpl.BulkImport.java
private SortedMap<KeyExtent, Files> computeMappingFromPlan(FileSystem fs, ID tableId, Path srcPath) throws IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException { Map<String, List<Destination>> fileDestinations = plan.getDestinations().stream() .collect(groupingBy(Destination::getFileName)); List<FileStatus> statuses = filterInvalid( fs.listStatus(srcPath, p -> !p.getName().equals(Constants.BULK_LOAD_MAPPING))); Map<String, Long> fileLens = getFileLenMap(statuses); if (!fileDestinations.keySet().equals(fileLens.keySet())) { throw new IllegalArgumentException( "Load plan files differ from directory files, symmetric difference : " + Sets.symmetricDifference(fileDestinations.keySet(), fileLens.keySet())); }/*from w w w .j a va2s . c o m*/ KeyExtentCache extentCache = new ConcurrentKeyExtentCache(tableId, context); // Pre-populate cache by looking up all end rows in sorted order. Doing this in sorted order // leverages read ahead. fileDestinations.values().stream().flatMap(List::stream) .filter(dest -> dest.getRangeType() == RangeType.FILE) .flatMap(dest -> Stream.of(dest.getStartRow(), dest.getEndRow())).filter(row -> row != null) .map(Text::new).sorted().distinct().forEach(row -> { try { extentCache.lookup(row); } catch (Exception e) { throw new RuntimeException(e); } }); SortedMap<KeyExtent, Files> mapping = new TreeMap<>(); for (Entry<String, List<Destination>> entry : fileDestinations.entrySet()) { String fileName = entry.getKey(); List<Destination> destinations = entry.getValue(); Set<KeyExtent> extents = mapDesitnationsToExtents(tableId, extentCache, destinations); long estSize = (long) (fileLens.get(fileName) / (double) extents.size()); for (KeyExtent keyExtent : extents) { mapping.computeIfAbsent(keyExtent, k -> new Files()).add(new FileInfo(fileName, estSize, 0)); } } return mergeOverlapping(mapping); }
From source file:voldemort.ServerTestUtils.java
/** * Returns a list of zones with their proximity list being in increasing * order//w w w . ja v a 2 s . co m * * @param numberOfZones The number of zones to return * @return List of zones */ public static List<Zone> getZonesFromZoneIds(int[] zoneIds) { List<Zone> zones = Lists.newArrayList(); Set<Integer> zoneIdsSet = new HashSet<Integer>(); for (int i : zoneIds) { zoneIdsSet.add(i); } Set<Integer> removeSet = new HashSet<Integer>(); for (int i = 0; i < zoneIds.length; i++) { removeSet.add(zoneIds[i]); zones.add(new Zone(zoneIds[i], Lists.newLinkedList(Sets.symmetricDifference(zoneIdsSet, removeSet)))); removeSet.clear(); } return zones; }
From source file:org.eclipse.sirius.diagram.ui.tools.internal.palette.PaletteManagerImpl.java
/** * Update the palette for a diagram that has layer(s), at least a default * one.// w w w . j av a2s . c o m * * @param dDiagram * The {@link DDiagram} representing by the editor which contains * the palette to update. * @param description * The {@link DiagramDescription} of the {@link DDiagram}. It * should not be a proxy. * @param session * The {@session} containing the {@link DDiagram}. */ private void updatePaletteForDiagramWithLayer(DiagramDescription description, Session session, DDiagram dDiagram) { // Copy of all layers of selected viewpoints HashSet<Layer> layersInActivatedViewpoints = new HashSet<Layer>(new DiagramComponentizationManager() .getAllLayers(session.getSelectedViewpoints(false), description)); // Copy of diagram activated layers (in all Viewpoints: activated or // not) HashSet<Layer> activatedLayers = new HashSet<Layer>(dDiagram.getActivatedLayers()); // Get the list of activated layers (of selected viewpoints) final List<Layer> activatedLayersOfSelectedViewpoints = Lists .newArrayList(Sets.intersection(layersInActivatedViewpoints, activatedLayers)); // Get the list of deactivated layers (deactivated layers of selected // viewpoints and all layers of deselected viewpoints) final List<Layer> deactivatedLayersAndAllLayersOfDeselectedViewpoints = Lists .newArrayList(Sets.symmetricDifference(layersInActivatedViewpoints, activatedLayers)); // Update the filters for (final ToolSection section : new DiagramComponentizationManager() .getRootPaletteSections(session.getSelectedViewpoints(false), description)) { updateFilters(session, new DiagramComponentizationManager() .getAllToolEntries(session.getSelectedViewpoints(false), section)); } for (final ToolSection section : new DiagramComponentizationManager() .getRootPaletteSections(session.getSelectedViewpoints(false), description)) { Option<SectionPaletteDrawer> paletteEntry = getPaletteEntry(paletteRoot, MessageTranslator.INSTANCE.getMessage(section, new IdentifiedElementQuery(section).getLabel()), SectionPaletteDrawer.class); if (!paletteEntry.some()) { final PaletteContainer container = PaletteManagerImpl.createPaletteDrawner(section); updateContainer(session, dDiagram, container, new DiagramComponentizationManager() .getAllToolEntries(session.getSelectedViewpoints(false), section)); paletteRoot.add(container); } else { updateContainer(session, dDiagram, paletteEntry.get(), new DiagramComponentizationManager() .getAllToolEntries(session.getSelectedViewpoints(false), section)); } } for (final Layer layer : Lists.newArrayList(deactivatedLayersAndAllLayersOfDeselectedViewpoints)) { setLayerVisibility(layer, false); } for (final Layer layer : Lists.newArrayList(activatedLayersOfSelectedViewpoints)) { setLayerVisibility(layer, true); } }
From source file:org.mifosplatform.portfolio.group.domain.Group.java
public List<String> updateClientMembersIfDifferent(final Set<Client> clientMembersSet) { List<String> differences = new ArrayList<String>(); if (!clientMembersSet.equals(this.clientMembers)) { final Set<Client> diffClients = Sets.symmetricDifference(clientMembersSet, this.clientMembers); final String[] diffClientsIds = getClientIds(diffClients); if (diffClientsIds != null) { differences = Arrays.asList(diffClientsIds); }// w ww.j av a 2s .c o m this.clientMembers = clientMembersSet; } return differences; }
From source file:org.onosproject.store.app.DistributedApplicationStore.java
@Override public void setPermissions(ApplicationId appId, Set<Permission> permissions) { AtomicBoolean permissionsChanged = new AtomicBoolean(false); Versioned<InternalApplicationHolder> appHolder = apps.computeIf(appId, v -> v != null && !Sets.symmetricDifference(v.permissions(), permissions).isEmpty(), (k, v) -> { permissionsChanged.set(true); return new InternalApplicationHolder(v.app(), v.state(), ImmutableSet.copyOf(permissions)); });/* ww w . j a va 2 s. c o m*/ if (permissionsChanged.get()) { notifyDelegate(new ApplicationEvent(APP_PERMISSIONS_CHANGED, appHolder.value().app())); } }
From source file:com.facebook.buck.distributed.build_client.BuildPhase.java
@Nonnull private Set<String> checkForRuleKeyMismatches(DistLocalBuildMode distLocalBuildMode, ListenableFuture<List<Pair<BuildRule, RuleKey>>> ruleKeyPairsFutureFuture) throws ExecutionException, InterruptedException { Set<String> mismatchingBuildTargets = new HashSet<>(); if (!distLocalBuildMode.equals(DistLocalBuildMode.RULE_KEY_DIVERGENCE_CHECK)) { return mismatchingBuildTargets; }/*from www. ja v a 2 s . com*/ List<Pair<BuildRule, RuleKey>> localRuleKeyPairs = ruleKeyPairsFutureFuture.get(); List<RuleKeyCalculatedEvent> remoteRuleKeys = buildRuleEventManager.getRuleKeyCalculatedEvents(); Map<String, String> localRulesToKeys = new HashMap<>(); for (Pair<BuildRule, RuleKey> localRuleKeyPair : localRuleKeyPairs) { localRulesToKeys.put(localRuleKeyPair.getFirst().getFullyQualifiedName(), localRuleKeyPair.getSecond().getHashCode().toString()); } Set<String> remoteBuildTargets = new HashSet<>(); for (RuleKeyCalculatedEvent remoteRuleAndKey : remoteRuleKeys) { String remoteBuildTarget = remoteRuleAndKey.getBuildTarget(); remoteBuildTargets.add(remoteBuildTarget); if (localRulesToKeys.containsKey(remoteBuildTarget) && !localRulesToKeys.get(remoteBuildTarget).equals(remoteRuleAndKey.getDefaultRuleKey())) { LOG.warn("Rule key for [%s] mismatched locally and remotely. Local [%s]. Remote [%s]", remoteBuildTarget, localRulesToKeys.containsKey(remoteBuildTarget), remoteRuleAndKey.getDefaultRuleKey()); mismatchingBuildTargets.add(remoteBuildTarget); } } SetView<String> buildTargetsOnlyBuildInOneLocation = Sets.symmetricDifference(localRulesToKeys.keySet(), remoteBuildTargets); for (String buildTarget : buildTargetsOnlyBuildInOneLocation) { LOG.warn("Rule [%s] was only built in one location", buildTarget); mismatchingBuildTargets.add(buildTarget); } return mismatchingBuildTargets; }
From source file:de.bund.bfr.knime.openkrise.views.tracingview.TracingChange.java
private static <T> Set<T> symDiff(Set<T> before, Set<T> after) { return new LinkedHashSet<>(Sets.symmetricDifference(before, after)); }
From source file:brooklyn.entity.nosql.cassandra.CassandraDatacenterImpl.java
@Override public void update() { synchronized (mutex) { // Update our seeds, as necessary seedTracker.refreshSeeds();/*from ww w . j av a 2s. com*/ // Choose the first available cluster member to set host and port (and compute one-up) Optional<Entity> upNode = Iterables.tryFind(getMembers(), EntityPredicates.attributeEqualTo(SERVICE_UP, Boolean.TRUE)); if (upNode.isPresent()) { setAttribute(HOSTNAME, upNode.get().getAttribute(Attributes.HOSTNAME)); setAttribute(THRIFT_PORT, upNode.get().getAttribute(CassandraNode.THRIFT_PORT)); List<String> currentNodes = getAttribute(CASSANDRA_CLUSTER_NODES); Set<String> oldNodes = (currentNodes != null) ? ImmutableSet.copyOf(currentNodes) : ImmutableSet.<String>of(); Set<String> newNodes = MutableSet.<String>of(); for (Entity member : getMembers()) { if (member instanceof CassandraNode && Boolean.TRUE.equals(member.getAttribute(SERVICE_UP))) { String hostname = member.getAttribute(Attributes.HOSTNAME); Integer thriftPort = member.getAttribute(CassandraNode.THRIFT_PORT); if (hostname != null && thriftPort != null) { newNodes.add(HostAndPort.fromParts(hostname, thriftPort).toString()); } } } if (Sets.symmetricDifference(oldNodes, newNodes).size() > 0) { setAttribute(CASSANDRA_CLUSTER_NODES, MutableList.copyOf(newNodes)); } } else { setAttribute(HOSTNAME, null); setAttribute(THRIFT_PORT, null); setAttribute(CASSANDRA_CLUSTER_NODES, Collections.<String>emptyList()); } ServiceNotUpLogic.updateNotUpIndicatorRequiringNonEmptyList(this, CASSANDRA_CLUSTER_NODES); } }