Java Code Examples for java.util.Collection.contains()

The following are Jave code examples for showing how to use contains() of the java.util.Collection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: sstore-soft   File: TestSpecExecScheduler.java   View Source Code Vote up 6 votes
/**
 * testNonConflicting
 */
public void testNonConflicting() throws Exception {
    // Make a single-partition txn for a procedure that has no conflicts with
    // our dtxn and add it to our queue. It should always be returned 
    // and marked as speculative by the scheduler
    Collection<Procedure> conflicts = ConflictSetUtil.getAllConflicts(dtxn.getProcedure());
    Procedure proc = null;
    for (Procedure p : catalogContext.getRegularProcedures()) {
        if (conflicts.contains(p) == false) {
            proc = p;
            break;
        }
    } // FOR
    assertNotNull(proc);
    
    LocalTransaction ts = new LocalTransaction(this.hstore_site);
    ts.testInit(this.idManager.getNextUniqueTransactionId(), BASE_PARTITION, null, catalogContext.getPartitionSetSingleton(BASE_PARTITION), proc);
    assertTrue(ts.isPredictSinglePartition());
    this.addToQueue(ts);
    
    LocalTransaction next = this.scheduler.next(this.dtxn, SpeculationType.IDLE);
    //System.err.println(this.dtxn.debug());
    assertNotNull(next);
    assertEquals(ts, next);
    assertFalse(this.work_queue.contains(next));
}
 
Example 2
Project: Equella   File: CheckboxChoiceList.java   View Source Code Vote up 6 votes
@Override
public void load(STATE_TYPE state)
{
	final Collection<String> choiceIds = getSavedChoiceIds(state);
	for( Entry<NameValue, DynamicChoicePanel<STATE_TYPE>> choice : choices.entrySet() )
	{
		final DynamicChoicePanel<STATE_TYPE> choicePanel = choice.getValue();
		if( choiceIds.contains(choicePanel.getId()) )
		{
			setSelectedChoiceComponent(choice.getKey());
			choicePanel.load(state);
		}
		else if( isLoadStateForNonSelectedChoices() )
		{
			choicePanel.load(state);
		}
	}
	// since checkboxes don't fire events when setSelected() is called:
	updateChoicePanels();
}
 
Example 3
Project: lemon   File: SpringSecurityUtils.java   View Source Code Vote up 6 votes
public static boolean lackAllRoles(String... roles) {
    if (roles == null) {
        logger.warn("roles is null");

        return true;
    }

    Collection<String> attributes = getRoles();

    for (String role : roles) {
        if (attributes.contains(role)) {
            logger.debug("has : {}", role);

            return false;
        }
    }

    return true;
}
 
Example 4
Project: weex-3d-map   File: MultiFormatUPCEANReader.java   View Source Code Vote up 6 votes
public MultiFormatUPCEANReader(Map<DecodeHintType,?> hints) {
  @SuppressWarnings("unchecked")
  Collection<BarcodeFormat> possibleFormats = hints == null ? null :
      (Collection<BarcodeFormat>) hints.get(DecodeHintType.POSSIBLE_FORMATS);
  Collection<UPCEANReader> readers = new ArrayList<>();
  if (possibleFormats != null) {
    if (possibleFormats.contains(BarcodeFormat.EAN_13)) {
      readers.add(new EAN13Reader());
    } else if (possibleFormats.contains(BarcodeFormat.UPC_A)) {
      readers.add(new UPCAReader());
    }
    if (possibleFormats.contains(BarcodeFormat.EAN_8)) {
      readers.add(new EAN8Reader());
    }
    if (possibleFormats.contains(BarcodeFormat.UPC_E)) {
      readers.add(new UPCEReader());
    }
  }
  if (readers.isEmpty()) {
    readers.add(new EAN13Reader());
    // UPC-A is covered by EAN-13
    readers.add(new EAN8Reader());
    readers.add(new UPCEReader());
  }
  this.readers = readers.toArray(new UPCEANReader[readers.size()]);
}
 
Example 5
Project: OCCI-Studio   File: OCCIActionBarContributor.java   View Source Code Vote up 6 votes
/**
 * This removes from the specified <code>manager</code> all {@link org.eclipse.jface.action.ActionContributionItem}s
 * based on the {@link org.eclipse.jface.action.IAction}s contained in the <code>actions</code> collection.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void depopulateManager(IContributionManager manager, Collection<? extends IAction> actions) {
	if (actions != null) {
		IContributionItem[] items = manager.getItems();
		for (int i = 0; i < items.length; i++) {
			// Look into SubContributionItems
			//
			IContributionItem contributionItem = items[i];
			while (contributionItem instanceof SubContributionItem) {
				contributionItem = ((SubContributionItem)contributionItem).getInnerItem();
			}

			// Delete the ActionContributionItems with matching action.
			//
			if (contributionItem instanceof ActionContributionItem) {
				IAction action = ((ActionContributionItem)contributionItem).getAction();
				if (actions.contains(action)) {
					manager.remove(contributionItem);
				}
			}
		}
	}
}
 
Example 6
Project: cas4.0.x-server-wechat   File: JBossCacheTicketRegistryTests.java   View Source Code Vote up 5 votes
@Test
public void testGetTicketsFromRegistryEqualToTicketsAdded() {
    final Collection<Ticket> tickets = new ArrayList<Ticket>();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("service", "test");

    for (int i = 0; i < TICKETS_IN_REGISTRY; i++) {
        final TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl(
                "TEST" + i, TestUtils.getAuthentication(),
                new NeverExpiresExpirationPolicy());
        final ServiceTicket st = ticketGrantingTicket.grantServiceTicket(
                "tests" + i, SimpleWebApplicationServiceImpl.createServiceFrom(request),
                new NeverExpiresExpirationPolicy(), false);
        tickets.add(ticketGrantingTicket);
        tickets.add(st);
        this.ticketRegistry.addTicket(ticketGrantingTicket);
        this.ticketRegistry.addTicket(st);
    }

    try {
        Collection<Ticket> ticketRegistryTickets = this.ticketRegistry.getTickets();
        assertEquals(
                "The size of the registry is not the same as the collection.",
                ticketRegistryTickets.size(), tickets.size());

        for (final Ticket ticket : tickets) {
            if (!ticketRegistryTickets.contains(ticket)) {
                fail("Ticket was added to registry but was not found in retrieval of collection of all tickets.");
            }
        }
    } catch (final Exception e) {
        fail("Caught an exception. But no exception should have been thrown.");
    }
}
 
Example 7
Project: mpd-2017-i41d   File: LazyQueries.java   View Source Code Vote up 5 votes
public static <T> boolean containsAll(Collection<T> col, Iterable<T> data) {
    for (T item:data) {
        if(!col.contains(item))
            return false;
    }
    return true;
}
 
Example 8
Project: myfaces-trinidad   File: UIXComponentBase.java   View Source Code Vote up 5 votes
/**
 * Utility method to assist sub-classes in the implementation of the
 * {@link javax.faces.component.behavior.ClientBehaviorHolder} interface.
 * <p>This method must only
 * be called by classes that implement the interface, doing otherwise will result in an exception.
 * </p>
 * @param eventName The event name
 * @param behavior The behavior to add
 * @see javax.faces.component.behavior.ClientBehaviorHolder#addClientBehavior(String, ClientBehavior)
 */
protected void addClientBehavior(
  String         eventName,
  ClientBehavior behavior)
{
  // This will throw a class cast exception when illegally called by a class that does not
  // implement ClientBehaviorHolder
  Collection<String> events = ((ClientBehaviorHolder)this).getEventNames();

  // This will throw a null pointer exception if the component author did not correctly implement
  // the ClientBehaviorHolder contract which requires a non-empty collection to be returned from
  // getEventNames
  if (!events.contains(eventName))
  {
    return;
  }

  FacesBean bean = getFacesBean();

  AttachedObjects<String, ClientBehavior> behaviors = (
          AttachedObjects<String, ClientBehavior>)bean.getProperty(_CLIENT_BEHAVIORS_KEY);

  if (behaviors == null)
  {
    behaviors = new AttachedObjects<String, ClientBehavior>();
    bean.setProperty(_CLIENT_BEHAVIORS_KEY, behaviors);
  }

  behaviors.addAttachedObject(eventName, behavior);
}
 
Example 9
Project: xm-ms-balance   File: BalanceApp.java   View Source Code Vote up 5 votes
/**
 * Initializes balance.
 *
 * <p>Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile
 *
 * <p>You can find more information on how profiles work with JHipster on <a href="http://www.jhipster.tech/profiles/">http://www.jhipster.tech/profiles/</a>.
 */
@PostConstruct
public void initApplication() {
    Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
    if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)
        && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
        log.error("You have misconfigured your application! It should not run "
            + "with both the 'dev' and 'prod' profiles at the same time.");
    }
    if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)
        && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) {
        log.error("You have misconfigured your application! It should not "
            + "run with both the 'dev' and 'cloud' profiles at the same time.");
    }
}
 
Example 10
Project: sstore-soft   File: Maps.java   View Source Code Vote up 5 votes
@Override public boolean removeAll(Collection<?> c) {
  try {
    return super.removeAll(checkNotNull(c));
  } catch (UnsupportedOperationException e) {
    Set<K> toRemove = Sets.newHashSet();
    for (Entry<K, V> entry : map().entrySet()) {
      if (c.contains(entry.getValue())) {
        toRemove.add(entry.getKey());
      }
    }
    return map().keySet().removeAll(toRemove);
  }
}
 
Example 11
Project: guava-mock   File: StandardTable.java   View Source Code Vote up 5 votes
@Override
public boolean retainAll(Collection<?> c) {
  checkNotNull(c);
  boolean changed = false;
  for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) {
    if (!c.contains(Maps.immutableEntry(columnKey, column(columnKey)))) {
      removeColumn(columnKey);
      changed = true;
    }
  }
  return changed;
}
 
Example 12
Project: jwala   File: UserServiceRestImpl.java   View Source Code Vote up 5 votes
@Override
public Response isUserAdmin(HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        @SuppressWarnings("unchecked")
        Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) auth.getAuthorities();
        if (authorities!= null &&  authorities.contains(new SimpleGrantedAuthority(ApplicationProperties.get(PROP_JWALA_ROLE_ADMIN)))) {
            return ResponseBuilder.ok(JSON_RESPONSE_TRUE);
        }
    }
    return ResponseBuilder.ok(JSON_RESPONSE_FALSE);
}
 
Example 13
Project: incubator-netbeans   File: OptionImpl.java   View Source Code Vote up 5 votes
/** Clones itself into a working copy option. For most options just add "this", for 
 * more complex ones override
 * @return the reference to new itself
 */
public final OptionImpl addWorkingCopy(Collection<OptionImpl> allOptions) {
    if (allOptions.contains(this)) {
        // find element that is equal
        Iterator it = allOptions.iterator();
        for(;;) {
            OptionImpl elem = (OptionImpl) it.next();
            if (elem.equals(this)) {
                return (OptionImpl)elem;
            }
        }
    } else {
        return handleAdd(allOptions);
    }
}
 
Example 14
Project: yaess   File: Contract.java   View Source Code Vote up 5 votes
public static <T> T inAllowedValues(T objectValue, String objectName, Collection<T> allowedObjectValues) {

		notNull(objectValue, "objectValue");
		notNullOrEmpty(objectName, "objectName");
		notNull(allowedObjectValues, "allowedObjectValues");

		if (!allowedObjectValues.contains(objectValue)) {
			throw new IncorrectValueException(objectName, objectValue, allowedObjectValues);
		}
		return objectValue;
	}
 
Example 15
Project: springboot-shiro-cas-mybatis   File: AbstractTicketRegistryTests.java   View Source Code Vote up 5 votes
@Test
public void verifyGetTicketsFromRegistryEqualToTicketsAdded() {
    final Collection<Ticket> tickets = new ArrayList<>();

    for (int i = 0; i < TICKETS_IN_REGISTRY; i++) {
        final TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl("TEST" + i,
                TestUtils.getAuthentication(), new NeverExpiresExpirationPolicy());
        final ServiceTicket st = ticketGrantingTicket.grantServiceTicket("tests" + i, TestUtils.getService(),
                new NeverExpiresExpirationPolicy(), false);
        tickets.add(ticketGrantingTicket);
        tickets.add(st);
        this.ticketRegistry.addTicket(ticketGrantingTicket);
        this.ticketRegistry.addTicket(st);
    }

    try {
        final Collection<Ticket> ticketRegistryTickets = this.ticketRegistry.getTickets();
        assertEquals("The size of the registry is not the same as the collection.", ticketRegistryTickets.size(),
                tickets.size());

        for (final Ticket ticket : tickets) {
            if (!ticketRegistryTickets.contains(ticket)) {
                fail("Ticket was added to registry but was not found in retrieval of collection of all tickets.");
            }
        }
    } catch (final Exception e) {
        fail("Caught an exception. But no exception should have been thrown.");
    }
}
 
Example 16
Project: fresco_floodlight   File: FloodlightModuleLoader.java   View Source Code Vote up 4 votes
/**
 * Finds all IFloodlightModule(s) in the classpath. It creates 3 Maps.
 * serviceMap -> Maps a service to a module
 * moduleServiceMap -> Maps a module to all the services it provides
 * moduleNameMap -> Maps the string name to the module
 * @throws FloodlightModuleException If two modules are specified in the
 * configuration that provide the same service.
 */
protected synchronized void findAllModules(Collection<String> mList)
        throws FloodlightModuleException {
    if (serviceMap != null)
        return;

    serviceMap = new HashMap<>();
    moduleServiceMap = new HashMap<>();
    moduleNameMap = new HashMap<>();

    // Get all the current modules in the classpath
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    ServiceLoader<IFloodlightModule> moduleLoader =
            ServiceLoader.load(IFloodlightModule.class, cl);
    // Iterate for each module, iterate through and add it's services
    Iterator<IFloodlightModule> moduleIter = moduleLoader.iterator();
    while (moduleIter.hasNext()) {
        IFloodlightModule m = null;
        try {
            m = moduleIter.next();
        } catch (ServiceConfigurationError sce) {
            logger.error("Could not find module: {}", sce.getMessage());
            continue;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Found module " + m.getClass().getName());
        }

        // Set up moduleNameMap
        moduleNameMap.put(m.getClass().getCanonicalName(), m);

        // Set up serviceMap
        Collection<Class<? extends IFloodlightService>> servs =
                m.getModuleServices();
        if (servs != null) {
            moduleServiceMap.put(m, servs);
            for (Class<? extends IFloodlightService> s : servs) {
                Collection<IFloodlightModule> mods =
                        serviceMap.get(s);
                if (mods == null) {
                    mods = new ArrayList<IFloodlightModule>();
                    serviceMap.put(s, mods);
                }
                mods.add(m);
                // Make sure they haven't specified duplicate modules in
                // the config
                int dupInConf = 0;
                for (IFloodlightModule cMod : mods) {
                    if (mList.contains(cMod.getClass().getCanonicalName()))
                        dupInConf += 1;
                }

                if (dupInConf > 1) {
                    StringBuilder sb = new StringBuilder();
                    for (IFloodlightModule mod : mods) {
                        sb.append(mod.getClass().getCanonicalName());
                        sb.append(", ");
                    }
                    String duplicateMods = sb.toString();
                    String mess = "ERROR! The configuration file " +
                            "specifies more than one module that " +
                            "provides the service " +
                            s.getCanonicalName() +
                            ". Please specify only ONE of the " +
                            "following modules in the config file: " +
                            duplicateMods;
                    throw new FloodlightModuleException(mess);
                }
            }
        }
    }
}
 
Example 17
Project: winter   File: P.java   View Source Code Vote up 4 votes
@Override
public Boolean invoke(Collection<T> in) {
	return in.contains(value);
}
 
Example 18
Project: incubator-netbeans   File: XMLFileSystem.java   View Source Code Vote up 4 votes
private synchronized void setXmlUrls(URL[] urls, boolean validate)
throws IOException, PropertyVetoException {
    if (urls == null) {
        throw new NullPointerException("Null URL list"); // NOI18N
    }
    Collection<URL> asList = Arrays.asList(urls);
    if (asList.contains(null)) {
        throw new NullPointerException("Null URL list member: " + asList); // NOI18N
    }

    ResourceElem rootElem;
    String oldDisplayName = getDisplayName();

    if (urls.length == 0) {
        urlsToXml = urls;
        refreshChildrenInAtomicAction((AbstractFolder) getRoot(), rootElem = new ResourceElem(true, urls)); // NOI18N
        rootElem = null;

        return;
    }

    Handler handler = new Handler(DTD_MAP, rootElem = new ResourceElem(true, urls), validate); // NOI18N        

    try {
        _setSystemName("XML_" + urls[0].toExternalForm().replace('/','-')); // NOI18N
    } catch (PropertyVetoException pvx) {
        rootElem = null;
        throw pvx;
    }

    URL act = null;

    try {
        XMLReader xp = XMLUtil.createXMLReader(validate, false);
        xp.setEntityResolver(handler);
        xp.setContentHandler(handler);
        xp.setErrorHandler(handler);

        for (int index = 0; index < urls.length; index++) {
            act = urls[index];
            handler.urlContext = act;

            String systemId = act.toExternalForm();

            xp.parse(systemId);
        }
        urlsToXml = urls.clone();
        refreshChildrenInAtomicAction((AbstractFolder) getRoot(), rootElem);
    } catch (IOException iox) {
        Exceptions.attachMessage(iox, Arrays.toString(urls));
        throw iox;
    } catch (Exception e) {
        throw (IOException) new IOException(act + ": " + e.toString()).initCause(e); // NOI18N
    } finally {
        rootElem = null;
    }

    firePropertyChange(PROP_DISPLAY_NAME, oldDisplayName, getDisplayName());
}
 
Example 19
Project: elasticsearch_my   File: ESIntegTestCase.java   View Source Code Vote up 4 votes
protected TestCluster buildTestCluster(Scope scope, long seed) throws IOException {
    String clusterAddresses = System.getProperty(TESTS_CLUSTER);
    if (Strings.hasLength(clusterAddresses) && ignoreExternalCluster() == false) {
        if (scope == Scope.TEST) {
            throw new IllegalArgumentException("Cannot run TEST scope test with " + TESTS_CLUSTER);
        }
        return buildExternalCluster(clusterAddresses);
    }

    final String nodePrefix;
    switch (scope) {
        case TEST:
            nodePrefix = TEST_CLUSTER_NODE_PREFIX;
            break;
        case SUITE:
            nodePrefix = SUITE_CLUSTER_NODE_PREFIX;
            break;
        default:
            throw new ElasticsearchException("Scope not supported: " + scope);
    }


    boolean supportsDedicatedMasters = getSupportsDedicatedMasters();
    int numDataNodes = getNumDataNodes();
    int minNumDataNodes;
    int maxNumDataNodes;
    if (numDataNodes >= 0) {
        minNumDataNodes = maxNumDataNodes = numDataNodes;
    } else {
        minNumDataNodes = getMinNumDataNodes();
        maxNumDataNodes = getMaxNumDataNodes();
    }
    Collection<Class<? extends Plugin>> mockPlugins = getMockPlugins();
    final NodeConfigurationSource nodeConfigurationSource = getNodeConfigSource();
    if (addMockTransportService()) {
        ArrayList<Class<? extends Plugin>> mocks = new ArrayList<>(mockPlugins);
        // add both mock plugins - local and tcp if they are not there
        // we do this in case somebody overrides getMockPlugins and misses to call super
        if (mockPlugins.contains(MockTcpTransportPlugin.class) == false) {
            mocks.add(MockTcpTransportPlugin.class);
        }
        mockPlugins = mocks;
    }
    return new InternalTestCluster(seed, createTempDir(), supportsDedicatedMasters, getAutoMinMasterNodes(),
        minNumDataNodes, maxNumDataNodes,
        InternalTestCluster.clusterName(scope.name(), seed) + "-cluster", nodeConfigurationSource, getNumClientNodes(),
        InternalTestCluster.DEFAULT_ENABLE_HTTP_PIPELINING, nodePrefix, mockPlugins, getClientWrapper());
}
 
Example 20
Project: kafka-0.11.0.0-src-with-comment   File: ScramCredentialUtils.java   View Source Code Vote up 4 votes
public static void createCache(CredentialCache cache, Collection<String> enabledMechanisms) {
    for (String mechanism : ScramMechanism.mechanismNames()) {
        if (enabledMechanisms.contains(mechanism))
            cache.createCache(mechanism, ScramCredential.class);
    }
}