Java Code Examples for java.util.Collection#equals()

The following examples show how to use java.util.Collection#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MBJavaApi.java    From container with Apache License 2.0 6 votes vote down vote up
private WSDLEndpoint getAdaptationPlanEndpoint(final Collection<String> sourceNodeIDs,
                                               final Collection<String> sourceRelationIDs,
                                               final Collection<String> targetNodeIDs,
                                               final Collection<String> targetRelationIDs) {
    for (final WSDLEndpoint endpoint : endpointService.getWSDLEndpoints()) {
        final Collection<String> sourceNodesMetadata =
            toStringCollection(endpoint.getMetadata().get("SOURCENODES"), ",");
        final Collection<String> sourceRelationsMetadata =
            toStringCollection(endpoint.getMetadata().get("SOURCERELATIONS"), ",");
        final Collection<String> targetNodesMetadata =
            toStringCollection(endpoint.getMetadata().get("TARGETNODES"), ",");
        final Collection<String> targetRelationsMetadata =
            toStringCollection(endpoint.getMetadata().get("TARGETRELATIONS"), ",");

        if (sourceNodeIDs.equals(sourceNodesMetadata) && sourceRelationIDs.equals(sourceRelationsMetadata)
            && targetNodeIDs.equals(targetNodesMetadata) && targetRelationIDs.equals(targetRelationsMetadata)) {
            return endpoint;
        }
    }

    return null;
}
 
Example 2
Source File: FunctionTagComparator.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/** 
 * Returns whether the tag lists for the given functions contain 
 * the same items; order is unimportant.
 * 
 * @param obj1 the first {@link FunctionDB} object
 * @param obj2 the second {@link FunctionDB} object
 * @return true if the tags lists contain the same elements.
 */
@Override
public boolean isSame(Object obj1, Object obj2) {
	FunctionDB f1 = (FunctionDB) obj1;
	FunctionDB f2 = (FunctionDB) obj2;

	if (f1 == null && f2 == null) {
		// Both null - neither is a function so just return true
		return true;
	}
	if (f1 == null || f2 == null) {
		// Someone is not a function, return false
		return false;
	}

	// Get the tag lists and check if they're the same.
	Collection<FunctionTag> f1Tags = f1.getTags();
	Collection<FunctionTag> f2Tags = f2.getTags();
	return f1Tags.equals(f2Tags);
}
 
Example 3
Source File: StandardConnection.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void setRelationships(final Collection<Relationship> newRelationships) {
    final Collection<Relationship> currentRelationships = relationships.get();
    if (currentRelationships.equals(newRelationships)) {
        return;
    }

    if (getSource().isRunning()) {
        throw new IllegalStateException("Cannot update the relationships for Connection because the source of the Connection is running");
    }

    try {
        this.relationships.set(new ArrayList<>(newRelationships));
        getSource().updateConnection(this);
    } catch (final RuntimeException e) {
        this.relationships.set(currentRelationships);
        throw e;
    }
}
 
Example 4
Source File: ProximityUpdater.java    From binnavi with Apache License 2.0 6 votes vote down vote up
@Override
public void selectionChanged() {
  if (!m_graph.getSettings().getProximitySettings().getProximityBrowsing()
      || m_graph.getSettings().getProximitySettings().getProximityBrowsingFrozen()) {
    return;
  }

  final Collection<NodeType> selectedNodes =
      SelectedVisibleFilter.filter(m_graph.getSelectedNodes());

  if (selectedNodes.equals(m_lastSelectedNodes)) {
    // this avoids a proximity browsing update when node selection has not changed
    // occurs if selected nodes a dragged by the mouse in order to move them around
    return;
  }

  m_lastSelectedNodes = selectedNodes;

  // Without this check all nodes are hidden when all nodes are unselected.
  if (!selectedNodes.isEmpty()) {
    final List<NodeType> allNodes = GraphHelpers.getNodes(m_graph);
    allNodes.removeAll(selectedNodes);
    showNodes(selectedNodes, allNodes);
  }
}
 
Example 5
Source File: CollectionInequality.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public String testInequality(Collection<?> s1, Collection<?> s2, InequalityTester t, String location)
{
	if (s1.size() != s2.size())
	{
		return "@CI=" + location + ": Inequality in Set Size: " + s1 + " " + s2;
	}
	if (s1.equals(s2))
	{
		return null;
	}
	Collection<Object> l1 = new ArrayList<>(s1);
	Collection<Object> l2 = new ArrayList<>(s2);
	l1.removeAll(l2);
	if (l1.isEmpty())
	{
		return null;
	}
	l2.removeAll(new ArrayList<Object>(s1));
	return "@CI=" + location + ": " + s1.getClass() + " Inequality between: " + l1 + " " + l2;
}
 
Example 6
Source File: AbstractLombokParsingTestCase.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Collection<PsiMethod> filterMethods(PsiMethod[] beforeMethods, PsiMethod compareMethod) {
  Collection<PsiMethod> result = new ArrayList<>();
  for (PsiMethod psiMethod : beforeMethods) {
    final PsiParameterList compareMethodParameterList = compareMethod.getParameterList();
    final PsiParameterList psiMethodParameterList = psiMethod.getParameterList();
    if (compareMethod.getName().equals(psiMethod.getName()) &&
      compareMethodParameterList.getParametersCount() == psiMethodParameterList.getParametersCount()) {
      final Collection<String> typesOfCompareMethod = mapToTypeString(compareMethodParameterList);
      final Collection<String> typesOfPsiMethod = mapToTypeString(psiMethodParameterList);
      if (typesOfCompareMethod.equals(typesOfPsiMethod)) {
        result.add(psiMethod);
      }
    }
  }
  return result;
}
 
Example 7
Source File: BaseTest.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
protected static <T> void assertCollectionEquals(Collection<T> expecteds,
		Collection<T> actuals) {
	if (!expecteds.equals(actuals)) {
		Logger.sys.info("EXPECTED");
		prettyPrint(expecteds);
		Logger.sys.info("ACTUAL"); 
		prettyPrint(actuals);
		Assert.assertTrue(false);
	}
}
 
Example 8
Source File: OverriddenValueInspector.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private void checkAssignment(AbstractElement object, String feature) {
	if (assignedFeatures.containsKey(feature)) {
		Collection<AbstractElement> sources = Lists.newArrayList(assignedFeatures.get(feature));
		assignedFeatures.replaceValues(feature, Collections.<AbstractElement> emptyList());
		if (sources != null && sources.equals(Collections.singletonList(object))) {
			if (getNestingLevel() == 0 && fragmentStack.isEmpty()) {
				if (object instanceof RuleCall) {
					acceptWarning("The fragment will possibly override the assigned value of feature '" + feature
							+ "' it is used inside of a loop.", object, null);
				} else {
					acceptWarning("The assigned value of feature '" + feature
							+ "' will possibly override itself because it is used inside of a loop.", object, null);
				}
			}
		}
		else {
			if (sources != null) {
				if (getNestingLevel() == 0 && fragmentStack.isEmpty()) {
					for (AbstractElement source : sources) {
						acceptWarning("The possibly assigned value of feature '" + feature
								+ "' may be overridden by subsequent assignments.", source, null);
					}
				}
			}
			if (getNestingLevel() == 0 && fragmentStack.isEmpty()) {
				if (object instanceof RuleCall) {
					acceptWarning("The fragment will potentially override the possibly assigned value of feature '"
							+ feature + "'.", object, null);
				} else {
					acceptWarning("This assignment will override the possibly assigned value of feature '"
							+ feature + "'.", object, null);
				}
			}
		}
	}
	else {
		assignedFeatures.put(feature, object);
	}
}
 
Example 9
Source File: CollectionUtil.java    From objectlabkit with Apache License 2.0 5 votes vote down vote up
public static boolean sameContent(final Collection<?> c1, final Collection<?> c2) {
    if (c1 == c2 || isEmpty(c2) && isEmpty(c1)) {
        return true;
    }
    boolean same = false;
    if (c1 != null && c2 != null) {
        same = c1.size() == c2.size();
        if (same) {
            same = c1.equals(c2);
        }
    }
    return same;
}
 
Example 10
Source File: IncompatibleEqualsNegativeCases.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@NoWarning("EC")
public boolean testCollection(Collection<String> c, HashSet<String> s, TreeSet<String> s2, Set<String> s3,  Object o) {
    if (c.equals(s))
        return true;
    if (s.equals(c))
        return true;
    if (o.equals(c))
        return true;
    if (s.equals(s2))
        return true;
    if (s2.equals(s3))
        return true;

    return false;
}
 
Example 11
Source File: SyntaxInitHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void triggerInitialization(Collection<IPath> roots) {

	Job job = new WorkspaceJob("Initialize Workspace") {
		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) {
			long start = System.currentTimeMillis();
			try {
				projectsManager.initializeProjects(roots, monitor);
				JavaLanguageServerPlugin.logInfo("Workspace initialized in " + (System.currentTimeMillis() - start) + "ms");
			} catch (Exception e) {
				JavaLanguageServerPlugin.logException("Initialization failed ", e);
			}

			return Status.OK_STATUS;
		}

		/* (non-Javadoc)
		 * @see org.eclipse.core.runtime.jobs.Job#belongsTo(java.lang.Object)
		 */
		@SuppressWarnings("unchecked")
		@Override
		public boolean belongsTo(Object family) {
			Collection<IPath> rootPathsSet = roots.stream().collect(Collectors.toSet());
			boolean equalToRootPaths = false;
			if (family instanceof Collection<?>) {
				equalToRootPaths = rootPathsSet.equals(((Collection<IPath>) family).stream().collect(Collectors.toSet()));
			}

			return JAVA_LS_INITIALIZATION_JOBS.equals(family) || equalToRootPaths;
		}
	};
	job.setPriority(Job.BUILD);
	job.setRule(ResourcesPlugin.getWorkspace().getRoot());
	job.schedule();
}
 
Example 12
Source File: LocalRepository.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * @return <code>true</code> if the tasks really changed
 */
boolean refreshTasks () throws CoreException {
    Collection<LocalTask> oldTasks = getCache().getAllTasks();
    for (NbTask task : MylynSupport.getInstance().getTasks(taskRepository)) {
        getLocalTask(task);
    }
    initialized = true;
    return !oldTasks.equals(getCache().getAllTasks());
}
 
Example 13
Source File: AbstractCommandTestCase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void assertNotifiedFiles(File... files) {

        Collection<File> sortedExpectedFiles = relativizeAndSortFiles(files);
        Collection<File> sortedNotifierFiles = relativizeAndSortFiles(fileNotifyListener.getFiles());
        
        if (!sortedExpectedFiles.equals(sortedNotifierFiles)) {
            // we will be fine if at least all given files were notified ...
            boolean weAreFine = true;
            for (File f : sortedExpectedFiles) {
                if(!sortedNotifierFiles.contains(f)) {
                    weAreFine = false;
                    break;
                }
            }
            if(weAreFine) return;

            String expectedNames = makeFilesList(sortedExpectedFiles);
            String actualNames   = makeFilesList(sortedNotifierFiles);

            System.err.println("Expected files: " + expectedNames);
            System.err.println("Notifier files: " + actualNames);

            String failureMsg = format("File lists do not match:", expectedNames, actualNames);
            Subversion.LOG.warning("assertNotifiedFiles: " + failureMsg);
            fail(failureMsg);
        }
    }
 
Example 14
Source File: TextCharacter.java    From lanterna with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns a copy of this TextCharacter with specified list of SGR modifiers. None of the currently active SGR codes
 * will be carried over to the copy, only those in the passed in value.
 * @param modifiers SGR modifiers the copy should have
 * @return Copy of the TextCharacter with a different set of SGR modifiers
 */
public TextCharacter withModifiers(Collection<SGR> modifiers) {
    EnumSet<SGR> newSet = EnumSet.copyOf(modifiers);
    if(modifiers.equals(newSet)) {
        return this;
    }
    return new TextCharacter(character, foregroundColor, backgroundColor, newSet);
}
 
Example 15
Source File: PdxType.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Return true if two pdx types have same class name and the same fields
 * but, unlike equals, field order does not matter.
 * Note a type that expects a domain class can be compatible with
 * one that does not expect a domain class.
 * @param other the other pdx type
 * @return true if two pdx types are compatible.
 */
public boolean compatible(PdxType other) {
  if (other == null) return false;
  if(!getClassName().equals(other.getClassName())) {
    return false;
  }

  Collection<PdxField> myFields = getSortedFields();
  Collection<PdxField> otherFields = other.getSortedFields();

  return myFields.equals(otherFields);
}
 
Example 16
Source File: GenericTestCaseBase.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static <T> void assertEquals(String msg, Collection<T> wanted, Object got) {
        if (wanted instanceof List<?> || wanted instanceof Set<?>) {
            // list.equals(list) and set.equals(set), see docs for Collection.equals
            if (got instanceof Set<?>) {
                fail("Not a collection, is a set");
            }
            if (got instanceof List<?>) {
                fail("Not a collection, is a list");
            }
        }
        if (wanted.equals(got)) {
            return;
        }
        if (!(got instanceof Collection<?>)) {
            fail(msg + "not a collection");
        }
        // Need to check the reverse, wanted may not implement equals,
        // which is the case for HashMap.values()
        if (got.equals(wanted)) {
            return;
        }
        msg = msg == null ? "" : msg + ' ';
        assertNotNull(msg + "expected a value", got);
        List<T> list = new ArrayList<>(wanted);
        Iterator<?> rightIt = ((Collection<?>) got).iterator();
OUTER:
        while (rightIt.hasNext()) {
            Object right = rightIt.next();
            for (int i = 0; i < list.size(); i++) {
                T left = list.get(i);
                if (left == null) {
                    if (right == null) {
                        list.remove(i);
                        continue OUTER;
                    }
                } else if (left.equals(right)) {
                    list.remove(i);
                    continue OUTER;
                }
            }
            fail(msg + "couldn't find " + right);
        }
        if (!list.isEmpty()) {
            fail(msg + "not enough items: " + list);
        }
    }
 
Example 17
Source File: HudsonInstanceImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Messages({"# {0} - server label", "MSG_Synchronizing=Synchronizing {0}"})
private void doSynchronize(final boolean authentication,
        final boolean showProgress) {
    final AtomicReference<Thread> synchThread = new AtomicReference<Thread>();
    final AtomicReference<ProgressHandle> handle = new AtomicReference<ProgressHandle>();
    ProgressHandle handleObject = ProgressHandleFactory.createHandle(
            Bundle.MSG_Synchronizing(getName()),
            new Cancellable() {
                @Override
                public boolean cancel() {
                    Thread t = synchThread.get();
                    if (t != null) {
                        LOG.log(Level.FINE,
                                "Cancelling synchronization of {0}",//NOI18N
                                getUrl());
                        if (!isPersisted()) {
                            properties.put(INSTANCE_SYNC, "0");     //NOI18N
                        }
                        t.interrupt();
                        handle.get().finish();
                        return true;
                    } else {
                        return false;
                    }
                }
            });
    handleObject.setInitialDelay(showProgress ? 100 : 30000);
    handle.set(handleObject);
        
        handle.get().start();

        if (authentication) {
            ConnectionBuilder.clearRejectedAuthentication();
        }
        
                synchThread.set(Thread.currentThread());
                try {
                    // Get actual views
                    Collection<HudsonView> oldViews = getViews();
                    
                    // Retrieve jobs
                    BuilderConnector.InstanceData instanceData =
                            getBuilderConnector().getInstanceData(
                            authentication);
                    configureViews(instanceData.getViewsData());
                    Collection<HudsonJob> retrieved = createJobs(
                            instanceData.getJobsData());
                    Collection<HudsonFolder> retrievedFolders = createFolders(instanceData.getFoldersData());
                    
                    // Exit when instance is terminated
                    if (terminated) {
                        return;
                    }
                    
                    // Set connected and version
                    connected = getBuilderConnector().isConnected();
                    version = getBuilderConnector().getHudsonVersion(authentication);
                    forbidden = getBuilderConnector().isForbidden();
                    
                    // Update state
                    fireStateChanges();

                    synchronized (workspaces) {
                        Iterator<Map.Entry<String,Reference<RemoteFileSystem>>> it = workspaces.entrySet().iterator();
                        while (it.hasNext()) {
                            Map.Entry<String,Reference<RemoteFileSystem>> entry = it.next();
                            RemoteFileSystem fs = entry.getValue().get();
                            if (fs != null) {
                                fs.refreshAll();
                            } else {
                                it.remove();
                            }
                        }
                    }

                    synchronized (this) {
                        // When there are no changes return and do not fire changes
                        if (jobs.equals(retrieved)
                                && folders.equals(retrievedFolders)
                                && oldViews.equals(views)) {
                            return;
                        }

                        // Update jobs
                        jobs = retrieved;
                        folders = retrievedFolders;
                    }

                    // Fire all changes
                    fireContentChanges();
                } finally {
                    handle.get().finish();
                }
}
 
Example 18
Source File: EntrySupportDefault.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Refreshes content of one entry. Updates the state of children
 * appropriately.
 */
final void refreshEntry(Entry entry) {
    // current list of nodes
    ChildrenArray holder = array.get();
    if (LOGGER.isLoggable(Level.FINER)) {
        LOGGER.finer("refreshEntry: " + entry + " holder=" + holder);
    }
    if (holder == null) {
        return;
    }
    Node[] current = holder.nodes();
    if (current == null) {
        // the initialization is not finished yet =>
        return;
    }
    checkConsistency();
    Info info = map.get(entry);
    if (info == null) {
        // refresh of entry that is not present =>
        return;
    }
    Collection<Node> oldNodes = info.nodes(false);
    Collection<Node> newNodes = info.entry.nodes(null);
    if (oldNodes.equals(newNodes)) {
        // nodes are the same =>
        return;
    }
    Set<Node> toRemove = new HashSet<Node>(oldNodes);
    toRemove.removeAll(new HashSet<Node>(newNodes));
    if (!toRemove.isEmpty()) {
        // notify removing, the set must be ready for
        // callbacks with questions
        // modifies the list associated with the info
        oldNodes.removeAll(toRemove);
        clearNodes();
        // now everything should be consistent => notify the remove
        notifyRemove(toRemove, current);
        current = holder.nodes();
    }
    List<Node> toAdd = refreshOrder(entry, oldNodes, newNodes);
    info.useNodes(newNodes);
    if (!toAdd.isEmpty()) {
        // modifies the list associated with the info
        clearNodes();
        notifyAdd(toAdd);
    }
}
 
Example 19
Source File: RPObject.java    From marauroa with GNU General Public License v2.0 3 votes vote down vote up
/**
 * compares two collections, empty collections and null collections are treated
 * as equal to allow easy working with lazy initialisation.
 *
 * @param c1 first collection
 * @param c2 second collection
 * @return true, if they are equal; false otherwise.
 */
private static boolean collectionIsEqualTreaingNullAsEmpty(Collection<?> c1, Collection<?> c2) {
	if ((c1 == null) || c1.isEmpty()) {
		return (c2 == null) || c2.isEmpty();
	}
	return c1.equals(c2);
}
 
Example 20
Source File: HostStatusTracker.java    From dyno with Apache License 2.0 2 votes vote down vote up
/**
 * All we need to check here is that whether the new active set is not exactly the same as the
 * prev active set. If there are any new hosts that have been added or any hosts that are missing
 * then return 'true' indicating that the active set has changed.
 *
 * @param hostsUp
 * @return true/false indicating whether the active set has changed from the previous set.
 */
public boolean activeSetChanged(Collection<Host> hostsUp) {

    return !hostsUp.equals(activeHosts);
}