Example usage for com.google.common.collect Sets symmetricDifference

List of usage examples for com.google.common.collect Sets symmetricDifference

Introduction

In this page you can find the example usage for com.google.common.collect Sets symmetricDifference.

Prototype

public static <E> SetView<E> symmetricDifference(final Set<? extends E> set1, final Set<? extends E> set2) 

Source Link

Document

Returns an unmodifiable view of the symmetric difference of two sets.

Usage

From source file:com.facebook.swift.codec.metadata.ThriftCatalog.java

/**
 * Add the @ToThrift and @FromThrift coercions in the specified class to this catalog.  All
 * coercions must be symmetrical, so ever @ToThrift method must have a corresponding @FromThrift
 * method./*from   w w  w . j av a2s. co m*/
 */
public void addDefaultCoercions(Class<?> coercionsClass) {
    Preconditions.checkNotNull(coercionsClass, "coercionsClass is null");
    Map<ThriftType, Method> toThriftCoercions = new HashMap<>();
    Map<ThriftType, Method> fromThriftCoercions = new HashMap<>();
    for (Method method : coercionsClass.getDeclaredMethods()) {
        if (method.isAnnotationPresent(ToThrift.class)) {
            verifyCoercionMethod(method);
            ThriftType thriftType = getThriftType(method.getGenericReturnType());
            ThriftType coercedType = thriftType.coerceTo(method.getGenericParameterTypes()[0]);

            Method oldValue = toThriftCoercions.put(coercedType, method);
            Preconditions.checkArgument(oldValue == null,
                    "Coercion class two @ToThrift methods (%s and %s) for type %s", coercionsClass.getName(),
                    method, oldValue, coercedType);
        } else if (method.isAnnotationPresent(FromThrift.class)) {
            verifyCoercionMethod(method);
            ThriftType thriftType = getThriftType(method.getGenericParameterTypes()[0]);
            ThriftType coercedType = thriftType.coerceTo(method.getGenericReturnType());

            Method oldValue = fromThriftCoercions.put(coercedType, method);
            Preconditions.checkArgument(oldValue == null,
                    "Coercion class two @FromThrift methods (%s and %s) for type %s", coercionsClass.getName(),
                    method, oldValue, coercedType);
        }
    }

    // assure coercions are symmetric
    Set<ThriftType> difference = Sets.symmetricDifference(toThriftCoercions.keySet(),
            fromThriftCoercions.keySet());
    Preconditions.checkArgument(difference.isEmpty(),
            "Coercion class %s does not have matched @ToThrift and @FromThrift methods for types %s",
            coercionsClass.getName(), difference);

    // add the coercions
    Map<Type, TypeCoercion> coercions = new HashMap<>();
    for (Map.Entry<ThriftType, Method> entry : toThriftCoercions.entrySet()) {
        ThriftType type = entry.getKey();
        Method toThriftMethod = entry.getValue();
        Method fromThriftMethod = fromThriftCoercions.get(type);
        // this should never happen due to the difference check above, but be careful
        Preconditions.checkState(fromThriftMethod != null,
                "Coercion class %s does not have matched @ToThrift and @FromThrift methods for type %s",
                coercionsClass.getName(), type);
        TypeCoercion coercion = new TypeCoercion(type, toThriftMethod, fromThriftMethod);
        coercions.put(type.getJavaType(), coercion);
    }
    this.coercions.putAll(coercions);
}

From source file:org.caleydo.view.enroute.correlation.wilcoxon.WilcoxonUtil.java

private static boolean containsSet(Set<Set<Object>> pool, Set<Object> set) {
    for (Set<Object> s : pool) {
        if (Sets.symmetricDifference(s, set).isEmpty()) {
            return true;
        }//from  w  w  w.ja va 2s.  c om
    }
    return false;
}

From source file:com.olacabs.fabric.compute.sources.kafka.impl.KafkaReaderLeaderElector.java

private void peerCountChange(boolean force) {
    final String memberPath = memberPathPrefix();
    List<String> members = null;
    try {/* www.j  a va2 s  . c  om*/
        members = curatorFramework.getChildren().forPath(memberPath);
        LOGGER.debug("Members: " + members);
        if (Sets.symmetricDifference(knownMembers, Sets.newHashSet(members)).isEmpty() && !force) {
            LOGGER.debug("No membership changes detected");
            return;
        } //.intersection(knownMembers, Sets.newHashSet(members))
    } catch (Exception e) {
        if (e instanceof KeeperException.NodeExistsException) {
            LOGGER.info("Looks like this topology/topic combination is being used for the first time");
        } else {
            LOGGER.error("Error checking for node on ZK: ", e);
        }
    }
    if (null == members) {
        LOGGER.error("No members found .. how did i come here? ZK issue?");
        return;
    }
    if (null == leaderSelector || !leaderSelector.hasLeadership()) {
        LOGGER.debug("I'm not the leader coordinator");
        return;
    }
    knownMembers = Sets.newHashSet(members);
    final List<String> finalMembers = members;
    AtomicInteger counter = new AtomicInteger(0);
    readers.keySet().forEach(partition -> {
        String selectedReader = finalMembers.get(counter.getAndIncrement() % finalMembers.size());
        LOGGER.info("[{}:{}:{}] Selected reader: {}", topology, topic, partition, selectedReader);
        final String communicatorPath = communicatorPath(partition);
        try {
            if (null == curatorFramework.checkExists().creatingParentContainersIfNeeded()
                    .forPath(communicatorPath)) {
                curatorFramework.create().creatingParentContainersIfNeeded().forPath(communicatorPath);
                LOGGER.info("[{}:{}:{}] Created communicator", topology, topic, partition);
            }
            curatorFramework.setData().forPath(communicatorPath, selectedReader.getBytes());
            LOGGER.error("Set reader at {} to {}", communicatorPath, selectedReader);
        } catch (Exception e) {
            LOGGER.error("Error setting reader value at {} to {}", communicatorPath, selectedReader, e);
        }
    });
}

From source file:com.opengamma.financial.analytics.PropertyPreservingFunction.java

/**
 * Creates the intersection of two valueProperties.
 * Note: this behaves as ValueProperties.compose except for the clause
 *  "Any properties defined in this set but not in the other remain untouched."
 * @param a some properties/*w w w. j  a v a  2s.c  om*/
 * @param b some properties
 * @return the intersection of a and b
 */
private ValueProperties composeStrict(final ValueProperties a, final ValueProperties b) {
    final ValueProperties none = ValueProperties.none();
    if (none.equals(a) || none.equals(b)) {
        //NOTE: none has null properties
        return none;
    }
    //NOTE: infinite properties behave as empty

    final ValueProperties compose = a.compose(b);
    final Set<String> mismatchedProperties = Sets.symmetricDifference(a.getProperties(), b.getProperties());
    return without(compose, mismatchedProperties);
}

From source file:org.fenixedu.academic.domain.accessControl.academicAdministration.AcademicOperationType.java

@Override
public Optional<AcademicAccessRule> grant(Group whoCanAccess, Set<AcademicAccessTarget> whatCanAffect) {
    if (whoCanAccess.equals(NobodyGroup.get())) {
        return Optional.empty();
    }//from   w w w .java  2  s  . c o  m
    Optional<AcademicAccessRule> match = AcademicAccessRule.accessRules()
            .filter(r -> r.getOperation().equals(this) && r.getWhoCanAccess().equals(whoCanAccess)
                    && Sets.symmetricDifference(r.getWhatCanAffect(), whatCanAffect).isEmpty())
            .findAny();
    return Optional.of(match.orElseGet(() -> new AcademicAccessRule(this, whoCanAccess, whatCanAffect)));
}

From source file:org.yakindu.sct.ui.editor.validation.DefaultValidationIssueStore.java

@Override
public void processIssues(List<Issue> issues, IProgressMonitor monitor) {

    final Multimap<String, SCTIssue> newVisibleIssues = ArrayListMultimap.create();
    for (Issue issue : issues) {
        if (issue instanceof SCTIssue) {
            String semanticURI = ((SCTIssue) issue).getSemanticURI();
            newVisibleIssues.put(semanticURI, (SCTIssue) issue);
        }/*from w w w  .  ja v a  2  s  .  c o  m*/
    }

    final Multimap<String, SCTIssue> oldVisibleIssues = ArrayListMultimap.create();
    synchronized (visibleIssues) {
        oldVisibleIssues.putAll(visibleIssues);
        // normal and expensive checks will not be executed by the live
        // validation, so persistent markers have to be copied
        Iterable<SCTIssue> persistentIssues = Iterables.filter(visibleIssues.values(),
                new Predicate<SCTIssue>() {
                    public boolean apply(SCTIssue input) {
                        CheckType type = input.getType();
                        Severity severity = input.getSeverity();
                        return CheckType.NORMAL == type || CheckType.EXPENSIVE == type
                                || Severity.INFO == severity;
                    }
                });
        for (SCTIssue sctIssue : persistentIssues) {
            newVisibleIssues.put(sctIssue.getSemanticURI(), sctIssue);
        }
        visibleIssues.clear();
        visibleIssues.putAll(newVisibleIssues);
    }

    SetView<String> changes = Sets.symmetricDifference(oldVisibleIssues.keySet(), newVisibleIssues.keySet());
    for (String string : changes) {
        notifyListeners(string);
    }

    SetView<String> intersection = Sets.intersection(oldVisibleIssues.keySet(), newVisibleIssues.keySet());
    for (String string : intersection) {
        if (changedSeverity(string, oldVisibleIssues, newVisibleIssues)
                || changedErrorCount(string, oldVisibleIssues, newVisibleIssues)) {
            notifyListeners(string);
        }
    }

}

From source file:org.cinchapi.concourse.server.storage.BufferedStore.java

@Override
public Set<Long> search(String key, String query) {
    // FIXME: should this be implemented using a context instead?
    return Sets.symmetricDifference(buffer.search(key, query), destination.search(key, query));
}

From source file:io.airlift.drift.codec.metadata.ThriftCatalog.java

/**
 * Add the @ToThrift and @FromThrift coercions in the specified class to this catalog.
 * All coercions must be symmetrical, so every @ToThrift method must have a
 * corresponding @FromThrift method./*ww  w .  j a  va2 s .c o m*/
 */
public void addDefaultCoercions(Class<?> coercionsClass) {
    requireNonNull(coercionsClass, "coercionsClass is null");
    Map<ThriftType, Method> toThriftCoercions = new HashMap<>();
    Map<ThriftType, Method> fromThriftCoercions = new HashMap<>();
    for (Method method : coercionsClass.getDeclaredMethods()) {
        if (method.isAnnotationPresent(ToThrift.class)) {
            verifyCoercionMethod(method);
            ThriftType thriftType = getThriftType(method.getGenericReturnType());
            ThriftType coercedType = thriftType.coerceTo(method.getGenericParameterTypes()[0]);

            Method oldValue = toThriftCoercions.put(coercedType, method);
            checkArgument(oldValue == null, "Coercion class two @ToThrift methods (%s and %s) for type %s",
                    coercionsClass.getName(), method, oldValue, coercedType);
        } else if (method.isAnnotationPresent(FromThrift.class)) {
            verifyCoercionMethod(method);
            ThriftType thriftType = getThriftType(method.getGenericParameterTypes()[0]);
            ThriftType coercedType = thriftType.coerceTo(method.getGenericReturnType());

            Method oldValue = fromThriftCoercions.put(coercedType, method);
            checkArgument(oldValue == null, "Coercion class two @FromThrift methods (%s and %s) for type %s",
                    coercionsClass.getName(), method, oldValue, coercedType);
        }
    }

    // assure coercions are symmetric
    Set<ThriftType> difference = Sets.symmetricDifference(toThriftCoercions.keySet(),
            fromThriftCoercions.keySet());
    checkArgument(difference.isEmpty(),
            "Coercion class %s does not have matched @ToThrift and @FromThrift methods for types %s",
            coercionsClass.getName(), difference);

    // add the coercions
    Map<Type, TypeCoercion> coercions = new HashMap<>();
    for (Map.Entry<ThriftType, Method> entry : toThriftCoercions.entrySet()) {
        ThriftType type = entry.getKey();
        Method toThriftMethod = entry.getValue();
        Method fromThriftMethod = fromThriftCoercions.get(type);
        // this should never happen due to the difference check above, but be careful
        checkState(fromThriftMethod != null,
                "Coercion class %s does not have matched @ToThrift and @FromThrift methods for type %s",
                coercionsClass.getName(), type);
        TypeCoercion coercion = new TypeCoercion(type, toThriftMethod, fromThriftMethod);
        coercions.put(type.getJavaType(), coercion);
    }
    this.coercions.putAll(coercions);
}

From source file:vars.annotation.ui.AnnotationFrame.java

protected JXObservationTable getTable() {
    if (table == null) {
        table = new JXObservationTable();
        table.setFocusable(false); // The row editor panel should get focus NOT the table
        ((JXObservationTableColumnModel) table.getColumnModel())
                .setImageView(VARSProperties.getShowRecordedDateInTable());

        // Map Mask+UP-ARROW Key Stroke
        String upTable = "up-table";
        Action upAction = new AbstractAction() {

            public void actionPerformed(final ActionEvent e) {
                final int numRows = table.getRowCount();
                final int currentRow = table.getSelectionModel().getLeadSelectionIndex();
                final int nextRow = (currentRow - 1 < 0) ? numRows - 1 : currentRow - 1;
                table.getSelectionModel().setSelectionInterval(nextRow, nextRow);
                table.scrollToVisible(nextRow, 0);
            }/*w  w  w  . j  a va2  s.  c om*/
        };

        table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_UP, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
                upTable);
        table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP,
                Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), upTable);
        table.getActionMap().put(upTable, upAction);

        // Map Mask+DOWN-ARROW Key Stroke
        String downTable = "down-table";
        Action downAction = new AbstractAction() {

            public void actionPerformed(final ActionEvent e) {
                final int numRows = table.getRowCount();
                final int currentRow = table.getSelectionModel().getLeadSelectionIndex();
                final int nextRow = (currentRow + 1 >= numRows) ? 0 : currentRow + 1;
                table.getSelectionModel().setSelectionInterval(nextRow, nextRow);
                table.scrollToVisible(nextRow, 0);
            }

        };
        table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
                downTable);
        table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN,
                Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), downTable);
        table.getActionMap().put(downTable, downAction);

        /*
         * Watch the selected rows and notify the world when the selected rows
         * are changed
         */
        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    int[] rows = table.getSelectedRows();
                    final List<Observation> selectedObservations = new Vector<Observation>(rows.length);
                    for (int i = 0; i < rows.length; i++) {
                        selectedObservations.add(table.getObservationAt(rows[i]));
                    }
                    // TODO add check to see if the selected observations are different thant
                    // the previously selected observations BEFORE sending this
                    Collection<Observation> oldObservations = (Collection<Observation>) Lookup
                            .getSelectedObservationsDispatcher().getValueObject();
                    Set<Observation> oldSelectedObservations = new HashSet<Observation>(oldObservations);
                    if (!Sets.symmetricDifference(new HashSet<Observation>(selectedObservations),
                            oldSelectedObservations).isEmpty()) {
                        EventBus.publish(new ObservationsSelectedEvent(table, selectedObservations));
                    }
                }
            }
        });

        Lookup.getObservationTableDispatcher().setValueObject(table);

    }

    return table;
}

From source file:org.apache.hadoop.hdfs.server.namenode.FSImageTestUtil.java

/**
 * Assert that a set of properties files all contain the same data.
 * We cannot simply check the md5sums here, since Properties files
 * contain timestamps -- thus, two properties files from the same
 * saveNamespace operation may actually differ in md5sum.
 * @param propFiles the files to compare
 * @throws IOException if the files cannot be opened or read
 * @throws AssertionError if the files differ
 *//*w  ww. ja  v  a  2  s  . c  om*/
public static void assertPropertiesFilesSame(File[] propFiles) throws IOException {
    Set<Map.Entry<Object, Object>> prevProps = null;

    for (File f : propFiles) {
        Properties props;
        FileInputStream is = new FileInputStream(f);
        try {
            props = new Properties();
            props.load(is);
        } finally {
            IOUtils.closeStream(is);
        }
        if (prevProps == null) {
            prevProps = props.entrySet();
        } else {
            Set<Entry<Object, Object>> diff = Sets.symmetricDifference(prevProps, props.entrySet());
            if (!diff.isEmpty()) {
                fail("Properties file " + f + " differs from " + propFiles[0]);
            }
        }
    }
}