Example usage for java.util Collection contains

List of usage examples for java.util Collection contains

Introduction

In this page you can find the example usage for java.util Collection contains.

Prototype

boolean contains(Object o);

Source Link

Document

Returns true if this collection contains the specified element.

Usage

From source file:com.epam.cme.facades.order.converters.populator.BundleMiniCartPopulator.java

protected List<OrderEntryData> extractModifiedEntriesFromEntryList(
        final List<AbstractOrderEntryModel> lastModifiedEntries, final List<OrderEntryData> allEntries) {
    final List<OrderEntryData> filteredEntries = new ArrayList<OrderEntryData>();

    final Collection<Integer> entryList = new ArrayList<Integer>();
    for (final AbstractOrderEntryModel modifiedEntry : lastModifiedEntries) {
        entryList.add(modifiedEntry.getEntryNumber());
    }/*ww  w . j  ava2 s  .c o  m*/

    for (final OrderEntryData entry : allEntries) {
        if (entryList.contains(entry.getEntryNumber())) {
            filteredEntries.add(entry);
        }
    }

    return filteredEntries;
}

From source file:com.sun.tools.xjc.addon.xew.XmlElementWrapperPluginTest.java

/**
 * Standard test for XSD examples./*from w w w  .j ava2 s.c o  m*/
 * 
 * @param testName
 *            the prototype of XSD file name / package name
 * @param extraXewOptions
 *            to be passed to plugin
 * @param generateEpisode
 *            generate episode file and check the list of classes included into it
 * @param classesToCheck
 *            expected classes/files in target directory; these files content is checked if it is present in
 *            resources directory; {@code ObjectFactory.java} is automatically included
 */
static void assertXsd(String testName, String[] extraXewOptions, boolean generateEpisode,
        String... classesToCheck) throws Exception {
    String resourceXsd = testName + ".xsd";
    String packageName = testName.replace('-', '_');

    // Force plugin to reinitialize the logger:
    System.clearProperty(XmlElementWrapperPlugin.COMMONS_LOGGING_LOG_LEVEL_PROPERTY_KEY);

    URL xsdUrl = XmlElementWrapperPluginTest.class.getResource(resourceXsd);

    File targetDir = new File(GENERATED_SOURCES_PREFIX);

    targetDir.mkdirs();

    PrintStream loggingPrintStream = new PrintStream(
            new LoggingOutputStream(logger, LoggingOutputStream.LogLevel.INFO, "[XJC] "));

    String[] opts = ArrayUtils.addAll(extraXewOptions, "-no-header", "-extension", "-Xxew", "-d",
            targetDir.getPath(), xsdUrl.getFile());

    String episodeFile = new File(targetDir, "episode.xml").getPath();

    // Episode plugin should be triggered after Xew, see https://github.com/dmak/jaxb-xew-plugin/issues/6
    if (generateEpisode) {
        opts = ArrayUtils.addAll(opts, "-episode", episodeFile);
    }

    assertTrue("XJC compilation failed. Checked console for more info.",
            Driver.run(opts, loggingPrintStream, loggingPrintStream) == 0);

    if (generateEpisode) {
        // FIXME: Episode file actually contains only value objects
        Set<String> classReferences = getClassReferencesFromEpisodeFile(episodeFile);

        if (Arrays.asList(classesToCheck).contains("package-info")) {
            classReferences.add(packageName + ".package-info");
        }

        assertEquals("Wrong number of classes in episode file", classesToCheck.length, classReferences.size());

        for (String className : classesToCheck) {
            assertTrue(className + " class is missing in episode file;",
                    classReferences.contains(packageName + "." + className));
        }
    }

    targetDir = new File(targetDir, packageName);

    Collection<String> generatedJavaSources = new HashSet<String>();

    // *.properties files are ignored:
    for (File targetFile : FileUtils.listFiles(targetDir, new String[] { "java" }, true)) {
        // This is effectively the path of targetFile relative to targetDir:
        generatedJavaSources
                .add(targetFile.getPath().substring(targetDir.getPath().length() + 1).replace('\\', '/'));
    }

    // This class is added and checked by default:
    classesToCheck = ArrayUtils.add(classesToCheck, "ObjectFactory");

    assertEquals("Wrong number of generated classes " + generatedJavaSources + ";", classesToCheck.length,
            generatedJavaSources.size());

    for (String className : classesToCheck) {
        className = className.replace('.', '/') + ".java";

        assertTrue(className + " is missing in target directory", generatedJavaSources.contains(className));
    }

    // Check the contents for those files which exist in resources:
    for (String className : classesToCheck) {
        className = className.replace('.', '/') + ".java";

        File sourceFile = new File(PREGENERATED_SOURCES_PREFIX + packageName, className);

        if (sourceFile.exists()) {
            // To avoid CR/LF conflicts:
            assertEquals("For " + className, FileUtils.readFileToString(sourceFile).replace("\r", ""),
                    FileUtils.readFileToString(new File(targetDir, className)).replace("\r", ""));
        }
    }

    JAXBContext jaxbContext = compileAndLoad(packageName, targetDir, generatedJavaSources);

    URL xmlTestFile = XmlElementWrapperPluginTest.class.getResource(testName + ".xml");

    if (xmlTestFile != null) {
        StringWriter writer = new StringWriter();

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schemaFactory.newSchema(xsdUrl));

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        Object bean = unmarshaller.unmarshal(xmlTestFile);
        marshaller.marshal(bean, writer);

        XMLUnit.setIgnoreComments(true);
        XMLUnit.setIgnoreWhitespace(true);
        Diff xmlDiff = new Diff(IOUtils.toString(xmlTestFile), writer.toString());

        assertXMLEqual("Generated XML is wrong: " + writer.toString(), xmlDiff, true);
    }
}

From source file:HotelManagerImplTest.java

@Test
public void testFindGuestsFromRoom() {
    Room room = newRoom(2, 4, 3);/*from w w  w.ja v  a 2  s.  c  o  m*/
    roomManager.createRoom(room);
    Guest guest1 = newGuest("Anna", "1113552");
    Guest guest2 = newGuest("Jana", "222454532");
    Guest guest3 = newGuest("Hanka", "33345254");
    guestManager.createGuest(guest1);
    guestManager.createGuest(guest2);
    guestManager.createGuest(guest3);
    Date startDate = date("2014-2-2");
    hotelManager.addGuestToRoom(room, guest1, startDate, date("2017-3-3"));
    hotelManager.addGuestToRoom(room, guest2, startDate, date("2018-3-3"));
    hotelManager.addGuestToRoom(room, guest3, startDate, date("2019-3-3"));

    Collection<Guest> result = new ArrayList<>();
    result = hotelManager.findGuestsfromRoom(room, startDate);

    assertTrue(result.contains(guest1));
    assertTrue(result.contains(guest2));
    assertTrue(result.contains(guest3));
    assertTrue(result.remove(guest1));
    assertTrue(result.remove(guest2));
    assertTrue(result.remove(guest3));
    assertTrue(result.isEmpty());
}

From source file:com.github.dozermapper.core.MappingProcessor.java

static void removeOrphans(Collection<?> mappedElements, List<Object> result) {
    for (Iterator<?> iterator = result.iterator(); iterator.hasNext();) {
        Object object = iterator.next();
        if (!mappedElements.contains(object)) {
            iterator.remove();//from  w w  w .  j ava2s .c om
        }
    }
    for (Object object : mappedElements) {
        if (!result.contains(object)) {
            result.add(object);
        }
    }
}

From source file:com.github.umeshawasthi.struts2.jsr303.validation.interceptor.JSR303ValidationInterceptor.java

@SuppressWarnings("nls")
@Override//from   w  w  w . j  av  a  2s .com
protected String doIntercept(ActionInvocation invocation) throws Exception {
    Validator validator = this.jsr303ValidationManager.getValidator();
    if (validator == null) {

        if (LOG.isDebugEnabled()) {
            LOG.debug("There is no Bean Validator configured in class path. Skipping Bean validation..");
        }
        return invocation.invoke();

    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Starting bean validation using " + validator.getClass());
    }

    Object action = invocation.getAction();
    ActionProxy actionProxy = invocation.getProxy();
    ValueStack valueStack = invocation.getStack();
    String methodName = actionProxy.getMethod();
    String context = actionProxy.getConfig().getName();

    if (LOG.isDebugEnabled()) {
        LOG.debug("Validating [#0/#1] with method [#2]", invocation.getProxy().getNamespace(),
                invocation.getProxy().getActionName(), methodName);
    }

    Collection<Method> annotatedMethods = AnnotationUtils.getAnnotatedMethods(action.getClass(),
            SkipValidation.class);

    if (!annotatedMethods.contains(getActionMethod(action.getClass(), methodName))) {
        // performing jsr303 bean validation
        performBeanValidation(action, valueStack, methodName, context, validator);
    }

    return invocation.invoke();

}

From source file:cz.PA165.vozovyPark.dao.VehicleDAOTest.java

/**
 * Test of findByUserClass method, of class VehicleDAO.
 *///from w ww  . j  av  a2 s  .  c  om
@Test
public void testFindByUserClass() {
    try {
        Vehicle mercedes1 = VehicleDAOTest.getVehicle("Mercedes", 20000, "R4 Diesel", "E",
                UserClassEnum.PRESIDENT, "2a-447i-882a45", 2009, "UEW6828");
        Vehicle mercedes2 = VehicleDAOTest.getVehicle("Mercedes", 20000, "R4 Diesel", "C",
                UserClassEnum.MANAGER, "98-447i-883345", 2009, "UEW6828");
        this.vehicleDao.createVehicle(mercedes1);
        this.vehicleDao.createVehicle(mercedes2);
        em.getTransaction().begin();
        Collection<Vehicle> required = this.vehicleDao.findByUserClass(UserClassEnum.MANAGER);
        em.getTransaction().commit();
        Assert.assertTrue("Vehicle with right user class was not loaded.", required.contains(mercedes2));
        Assert.assertFalse("Vehicle with different user class was loaded as well",
                required.contains(mercedes1));
    } catch (Exception ex) {
        Assert.fail("Unexpected exception was throwed: " + ex + " " + ex.getMessage());
    }
}

From source file:org.socialsignin.springsocial.security.signin.SpringSocialSecurityConnectInterceptor.java

/**
 * This callback 1)  Ensures that 2 different local users
 * cannot share the same 3rd party connection 2) Updates the current
 * user's authentication if the set of roles they are assigned
 * needs to change now that this connection has been made.
 * 3) Looks for a request previously saved by an access denied
 * handler, and if present, sets the url of this original
 * pre-authorisation request as a session attribute
 * //from  w ww. j  ava  2  s.  c  o  m
 */
@Override
public void postConnect(Connection<S> connection, WebRequest webRequest) {

    super.postConnect(connection, webRequest);

    /**
     * User roles are generated according to connected
     * providers in spring-social-security
     * 
     * Now that this connection has been made,
     * doe we need to update the user roles?
     * 
     * If so, update the current user's authentication and update
     * remember-me services accordingly.
     */
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    Collection<? extends GrantedAuthority> existingAuthorities = authentication.getAuthorities();

    GrantedAuthority newAuthority = userAuthoritiesService.getProviderAuthority(connection.getKey());

    if (!existingAuthorities.contains(newAuthority)) {

        Authentication newAuthentication = authenticationFactory
                .updateAuthenticationForNewConnection(authentication, connection);
        SecurityContextHolder.getContext().setAuthentication(newAuthentication);

        if (rememberMeServices != null && webRequest instanceof ServletWebRequest) {

            ServletWebRequest servletWebRequest = ((ServletWebRequest) webRequest);
            rememberMeServices.loginSuccess(servletWebRequest.getRequest(), servletWebRequest.getResponse(),
                    newAuthentication);
        }
    }

    /**
     * This connection may have been instigated by an 
     * access denied handler which may have saved the
     * original request made by the user before their access
     * was denied.  
     * 
     * Spring Social sends the user to a particular view
     * on completion of connection.  We may wish to offer the
     * user a "continue" link on this view, allowing their
     * original request (if saved by the access denied handler)
     * to be re-attempted
     *
     */
    if (webRequest instanceof ServletWebRequest) {
        ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
        SavedRequest savedRequest = requestCache.getRequest(servletWebRequest.getRequest(),
                servletWebRequest.getResponse());
        if (savedRequest != null) {
            String redirectUrl = savedRequest.getRedirectUrl();
            if (redirectUrl != null && savedRequest.getMethod().equalsIgnoreCase("get")) {
                servletWebRequest.setAttribute(SAVED_REQUEST_URL_ATTRIBUTE_NAME, savedRequest.getRedirectUrl(),
                        RequestAttributes.SCOPE_SESSION);
            }
        }
    }
}

From source file:de.hybris.platform.assistedservicefacades.solrfacetsearch.processors.AsmResultDataPostProcessor.java

@Override
public SearchResult process(final SearchResult solrSearchResult) {
    // do not filter out ASM category products if AS agent is logged in
    if (getAssistedServiceFacade().isAssistedServiceAgentLoggedIn()) {
        return solrSearchResult;
    }/*ww  w . j a  v  a  2s. co m*/

    //make sure we have results to filter
    if (solrSearchResult != null && solrSearchResult.getTotalNumberOfResults() > 0) {
        try {
            final List<? extends ItemModel> results = solrSearchResult.getResults();

            final SolrDocumentList queryResponseResults = ((SolrSearchResult) solrSearchResult)
                    .getQueryResponse().getResults();

            CategoryModel asmCategory = null;

            final SolrDocumentList removedList = new SolrDocumentList();
            for (int i = 0; i < results.size(); i++) {
                final ItemModel item = results.get(i);
                if (item instanceof ProductModel) {

                    final ProductModel productModel = (ProductModel) item;

                    //here we are getting the ASM Category which has the Id of 1500
                    if (asmCategory == null) {
                        asmCategory = getCategoryService().getCategoryForCode(productModel.getCatalogVersion(),
                                "1500");
                    }

                    //get categories for the current product
                    final Collection<CategoryModel> categories = productModel.getSupercategories();

                    //check to see if the ASM Category is part of the associated categories or no
                    if (CollectionUtils.isNotEmpty(categories)) {
                        if (categories.contains(asmCategory)
                                && queryResponseResults.get(i).containsValue(productModel.getCode())) {
                            removedList.add(queryResponseResults.get(i)); //add the search item to be removed
                        }
                    }

                }
            }
            queryResponseResults.removeAll(removedList); //remove matching products that should only be displayed to ASM agent
        } catch (final FacetSearchException e) {
            LOG.error(e.getMessage(), e);
            return solrSearchResult;
        }
    }
    return solrSearchResult;
}

From source file:edu.uci.ics.asterix.optimizer.rules.PushAggFuncIntoStandaloneAggregateRule.java

private boolean fingAggFuncExprRef(List<Mutable<ILogicalExpression>> exprRefs, LogicalVariable aggVar,
        List<Mutable<ILogicalExpression>> srcAssignExprRefs) {
    for (Mutable<ILogicalExpression> exprRef : exprRefs) {
        ILogicalExpression expr = exprRef.getValue();

        if (expr.getExpressionTag() == LogicalExpressionTag.VARIABLE) {
            if (((VariableReferenceExpression) expr).getVariableReference().equals(aggVar)) {
                return false;
            }/* w ww .java2 s  .co  m*/
        }

        if (expr.getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) {
            continue;
        }
        AbstractFunctionCallExpression funcExpr = (AbstractFunctionCallExpression) expr;
        FunctionIdentifier funcIdent = AsterixBuiltinFunctions
                .getAggregateFunction(funcExpr.getFunctionIdentifier());
        if (funcIdent == null) {
            // Recursively look in func args.
            if (fingAggFuncExprRef(funcExpr.getArguments(), aggVar, srcAssignExprRefs) == false) {
                return false;
            }

        } else {
            // Check if this is the expr that uses aggVar.
            Collection<LogicalVariable> usedVars = new HashSet<LogicalVariable>();
            funcExpr.getUsedVariables(usedVars);
            if (usedVars.contains(aggVar)) {
                srcAssignExprRefs.add(exprRef);
            }
        }
    }
    return true;
}

From source file:org.openvpms.component.business.service.lookup.AbstractLookupServiceTest.java

/**
 * Tests the {@link ILookupService#getSourceLookups(Lookup)} and
 * {@link ILookupService#getTargetLookups(Lookup)} method.
 *///from   w  ww. j av  a  2 s. c  o  m
@Test
public void testGetSourceAndTargetLookups() {
    removeLookups("lookup.country");
    removeLookups("lookup.state");

    Lookup au = createLookup("lookup.country", "AU");
    createLookup("lookup.country", "UK");
    Lookup vic = createLookup("lookup.state", "VIC");
    LookupUtil.addRelationship(getArchetypeService(), "lookupRelationship.countryState", au, vic);
    save(au, vic);

    assertEquals(0, lookupService.getSourceLookups(au).size());
    Collection<Lookup> targets = lookupService.getTargetLookups(au);
    assertEquals(1, targets.size());
    assertTrue(targets.contains(vic));

    assertEquals(0, lookupService.getTargetLookups(vic).size());
    Collection<Lookup> sources = lookupService.getSourceLookups(vic);
    assertEquals(1, sources.size());
    assertTrue(sources.contains(au));
}