Example usage for org.apache.commons.collections CollectionUtils isEqualCollection

List of usage examples for org.apache.commons.collections CollectionUtils isEqualCollection

Introduction

In this page you can find the example usage for org.apache.commons.collections CollectionUtils isEqualCollection.

Prototype

public static boolean isEqualCollection(final Collection a, final Collection b) 

Source Link

Document

Returns true iff the given Collection s contain exactly the same elements with exactly the same cardinalities.

Usage

From source file:org.gridgain.grid.kernal.processors.cache.datastructures.GridCacheQueueMultiNodeConsistencySelfTest.java

/**
 * Starts {@code GRID_CNT} nodes, broadcasts {@code AddAllJob} to them then starts new grid and
 * reads cache queue content and finally asserts queue content is the same.
 *
 * @throws Exception If failed.// w  ww .  j  a  v  a 2  s  .  c  o  m
 */
private void checkCacheQueue() throws Exception {
    startGrids(GRID_CNT);

    final String queueName = UUID.randomUUID().toString();

    GridCacheQueue<Integer> queue0 = grid(0).cache(null).dataStructures().queue(queueName, QUEUE_CAPACITY,
            false, true);

    assertTrue(queue0.isEmpty());

    grid(0).compute().broadcast(new AddAllJob(queueName, RETRIES)).get();

    assertEquals(GRID_CNT * RETRIES, queue0.size());

    if (stopRandomGrid)
        stopGrid(1 + new Random().nextInt(GRID_CNT));

    if (forceRepartition)
        for (int i = 0; i < GRID_CNT; i++)
            grid(i).cache(null).forceRepartition();

    Grid newGrid = startGrid(GRID_CNT + 1);

    // Intentionally commented code cause in this way inconsistent queue problem doesn't appear.
    // GridCacheQueue<Integer> newQueue = newGrid.cache().queue(queueName);
    // assertTrue(CollectionUtils.isEqualCollection(queue0, newQueue));

    Collection<Integer> locQueueContent = newGrid.forLocal().compute()
            .call(new GridCallable<Collection<Integer>>() {
                @GridInstanceResource
                private Grid grid;

                /** {@inheritDoc} */
                @Override
                public Collection<Integer> call() throws Exception {
                    Collection<Integer> values = new ArrayList<>();

                    grid.log().info("Running job [node=" + grid.localNode().id() + ", job=" + this + "]");

                    GridCacheQueue<Integer> locQueue = grid.cache(null).dataStructures().queue(queueName,
                            QUEUE_CAPACITY, false, true);

                    grid.log().info("Queue size " + locQueue.size());

                    for (Integer element : locQueue)
                        values.add(element);

                    return values;
                }
            }).get();

    assertTrue(CollectionUtils.isEqualCollection(queue0, locQueueContent));

    grid(0).cache(null).dataStructures().removeQueue(queueName);
}

From source file:org.hudsonci.model.project.property.DescribableListProjectProperty.java

@Override
public boolean allowOverrideValue(DescribableList cascadingValue, DescribableList candidateValue) {
    return (null != candidateValue || null != cascadingValue)
            && ((null == cascadingValue || null == candidateValue)
                    || !CollectionUtils.isEqualCollection(cascadingValue.toList(), candidateValue.toList()));
}

From source file:org.jahia.bin.TokenChecker.java

public static int checkToken(HttpServletRequest req, HttpServletResponse resp,
        Map<String, List<String>> parameters) throws UnsupportedEncodingException {
    String token = parameters.get("form-token") != null ? parameters.get("form-token").get(0) : null;
    if (token != null) {
        @SuppressWarnings("unchecked")
        Map<String, Map<String, List<String>>> toks = (Map<String, Map<String, List<String>>>) req.getSession()
                .getAttribute("form-tokens");
        if (toks != null && toks.containsKey(token)) {
            Map<String, List<String>> m = toks.get(token);
            if (m == null) {
                return INVALID_TOKEN;
            }//from   w  w  w .j a v  a2  s . c  o m
            Map<String, List<String>> values = new HashMap<String, List<String>>(m);
            if (!values.remove(Render.ALLOWS_MULTIPLE_SUBMITS).contains("true")) {
                toks.remove(token);
            }
            values.remove(Render.DISABLE_XSS_FILTERING);

            // Validate form token
            List<String> stringList1 = values.remove("form-action");
            String formAction = stringList1.isEmpty() ? null : stringList1.get(0);
            String characterEncoding = SettingsBean.getInstance().getCharacterEncoding();
            String requestURI = req.getRequestURI();
            if (req.getQueryString() != null) {
                requestURI += "?" + req.getQueryString();
            }
            if (formAction == null || (!URLDecoder.decode(requestURI, characterEncoding)
                    .equals(URLDecoder.decode(formAction, characterEncoding))
                    && !URLDecoder.decode(resp.encodeURL(requestURI), characterEncoding)
                            .equals(URLDecoder.decode(formAction, characterEncoding)))) {
                return INVALID_HIDDEN_FIELDS;
            }
            if (!req.getMethod().equalsIgnoreCase(values.remove("form-method").get(0))) {
                return INVALID_HIDDEN_FIELDS;
            }
            for (Map.Entry<String, List<String>> entry : values.entrySet()) {
                List<String> stringList = entry.getValue();
                List<String> parameterValues = parameters.get(entry.getKey());
                if (parameterValues == null
                        || !CollectionUtils.isEqualCollection(stringList, parameterValues)) {
                    if (entry.getKey().equals(Render.CAPTCHA)) {
                        return INVALID_CAPTCHA;
                    }
                    return INVALID_HIDDEN_FIELDS;
                }
            }
            return VALID_TOKEN;
        }
        return INVALID_TOKEN;
    }
    return NO_TOKEN;
}

From source file:org.jahia.utils.zip.DirectoryZipInputStreamTest.java

@Test
public void testDirectoryZipInputStream() throws IOException {
    createDirectoryZip();// ww w  .java  2s  .com

    File inputStreamFile = File.createTempFile("dirzip-input", null);
    FileInputStream fileInputStream = new FileInputStream(inputStreamFile);
    DirectoryZipInputStream directoryZipInputStream = new DirectoryZipInputStream(outputDirectory);

    ZipEntry zipEntry = null;
    int directoriesFound = 0;
    int filesRead = 0;
    long bytesRead = 0;
    List<String> entryNamesFound = new ArrayList<String>();
    while ((zipEntry = directoryZipInputStream.getNextEntry()) != null) {
        entryNamesFound.add(zipEntry.getName().replace('\\', '/'));
        if (zipEntry.isDirectory()) {
            directoriesFound++;
        } else {
            filesRead++;
            byte[] fileContents = IOUtils.toByteArray(directoryZipInputStream);
            bytesRead += fileContents.length;
        }
    }

    Assert.assertEquals("Bytes read does not match bytes written", bytesWritten, bytesRead);
    Assert.assertEquals("Number of files read does not match number of files created", filesCreated, filesRead);
    Assert.assertEquals("Directories found does not match number of directories created", directoriesCreated,
            directoriesFound);
    Assert.assertEquals("Number of entry names does not match !", entryNames.size(), entryNamesFound.size());
    Assert.assertTrue("Entry names do not match !",
            CollectionUtils.isEqualCollection(entryNames, entryNamesFound));

    fileInputStream.close();
    inputStreamFile.delete();
}

From source file:org.kuali.kfs.sys.batch.CsvBatchInputFileTypeBase.java

/**
 * Validates the CSV file content against the CSVEnum items as header
 * 1. content header must match CSVEnum order/value
 * 2. each data row should have same size as the header
 * //from  ww w  . ja va2s. c o  m
 * @param expectedHeaderList        expected CSV header String list 
 * @param fileContents              contents to validate 
 * 
 * @throws IOException
 */
private void validateCSVFileInput(final List<String> expectedHeaderList, InputStream fileContents)
        throws IOException {

    //use csv reader to parse the csv content
    CSVReader csvReader = new CSVReader(new InputStreamReader(fileContents));
    List<String> inputHeaderList = Arrays.asList(csvReader.readNext());

    String errorMessage = null;

    // validate
    if (!CollectionUtils.isEqualCollection(expectedHeaderList, inputHeaderList)) {
        errorMessage = "CSV Batch Input File contains incorrect number of headers";
        //collection has same elements, now check the exact content orders by looking at the toString comparisons
    } else if (!expectedHeaderList.equals(inputHeaderList)) {
        errorMessage = "CSV Batch Input File headers are different";
    } else {

        //check the content size as well if headers are validated
        int line = 1;
        List<String> inputDataList = null;
        while ((inputDataList = Arrays.asList(csvReader.readNext())) != null && errorMessage != null) {
            //if the data list size does not match header list (its missing data)
            if (inputDataList.size() != expectedHeaderList.size()) {
                errorMessage = "line " + line + " layout does not match the header";
            }
            line++;
        }
    }

    if (errorMessage != null) {
        LOG.error(errorMessage);
        throw new RuntimeException(errorMessage);
    }
}

From source file:org.kuali.rice.kew.actionrequest.service.impl.NotificationSuppressionTest.java

License:asdf

/**
 * Tests that the notification suppression keys work equivalently for ActionRequestDTO and
 * ActionRequestValue//w w  w .ja  va 2 s. co  m
 * 
 * @throws Exception
 */
@Test
public void testNotificationSuppressionKeys() throws Exception {
    WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("ewestfal"),
            TEST_DOC_TYPE);
    document.route("");
    List<ActionRequest> requests = document.getRootActionRequests();
    assertTrue("there must be ActionRequestDTOs to test!", requests != null && requests.size() > 0);

    NotificationSuppression notificationSuppression = new NotificationSuppression();

    boolean atLeastOne = false;
    for (ActionRequest reqDTO : requests)
        if (reqDTO.getParentActionRequestId() == null) {
            atLeastOne = true;
            ActionRequestValue reqVal = ActionRequestValue.from(reqDTO);
            assertTrue(CollectionUtils.isEqualCollection(
                    notificationSuppression.getSuppressNotifyNodeStateKeys(reqVal),
                    notificationSuppression.getSuppressNotifyNodeStateKeys(reqDTO)));

            // test that changing the responsible party changes the key

            ActionRequest.Builder builder = ActionRequest.Builder.create(reqDTO);
            builder.setPrincipalId("asdf");
            reqDTO = builder.build();
            assertFalse(CollectionUtils.isEqualCollection(
                    notificationSuppression.getSuppressNotifyNodeStateKeys(reqVal),
                    notificationSuppression.getSuppressNotifyNodeStateKeys(reqDTO)));
        }
    assertTrue(atLeastOne);

}

From source file:org.kuali.student.enrollment.class2.coursewaitlist.model.CourseWaitListEntity.java

public void fromDto(CourseWaitList courseWaitList) {

    super.fromDTO(courseWaitList);

    this.setAllowHoldUntilEntries(courseWaitList.getAllowHoldUntilEntries());
    this.setAttributes(new HashSet<CourseWaitListAttributeEntity>());
    for (Attribute att : courseWaitList.getAttributes()) {
        CourseWaitListAttributeEntity attEntity = new CourseWaitListAttributeEntity(att, this);
        this.getAttributes().add(attEntity);
    }//from ww w . j a va2 s .co m

    if (courseWaitList.getActivityOfferingIds() != null) {
        if (activityOfferingIds == null || !CollectionUtils.isEqualCollection(activityOfferingIds,
                courseWaitList.getActivityOfferingIds())) {
            activityOfferingIds = new ArrayList<String>(courseWaitList.getActivityOfferingIds());
        }
    } else {
        activityOfferingIds = null;
    }

    if (courseWaitList.getFormatOfferingIds() != null) {
        if (formatOfferingIds == null || !CollectionUtils.isEqualCollection(formatOfferingIds,
                courseWaitList.getFormatOfferingIds())) {
            formatOfferingIds = new ArrayList<String>(courseWaitList.getFormatOfferingIds());
        }
    } else {
        formatOfferingIds = null;
    }
    this.setAutomaticallyProcessed(courseWaitList.getAutomaticallyProcessed());
    this.setAllowHoldUntilEntries(courseWaitList.getAllowHoldUntilEntries());
    this.setCheckInRequired(courseWaitList.getCheckInRequired());
    this.setConfirmationRequired(courseWaitList.getConfirmationRequired());
    this.setEffectiveDate(courseWaitList.getEffectiveDate());
    this.setExpirationDate(courseWaitList.getExpirationDate());
    this.setMaxSize(courseWaitList.getMaxSize());
    this.setRegisterInFirstAvailableActivityOffering(
            courseWaitList.getRegisterInFirstAvailableActivityOffering());
    this.setState(courseWaitList.getStateKey());
    if (courseWaitList.getCheckInFrequency() != null) {
        this.setStandardDurationTime(courseWaitList.getCheckInFrequency().getTimeQuantity());
        this.setStandardDurationType(courseWaitList.getCheckInFrequency().getAtpDurationTypeKey());
    }
}

From source file:org.musicrecital.service.UserSecurityAdvice.java

/**
 * Method to enforce security and only allow administrators to modify users. Regular
 * users are allowed to modify themselves.
 *
 * @param method the name of the method executed
 * @param args   the arguments to the method
 * @param target the target class/*from   w w  w  .  j a v a  2 s. c  om*/
 * @throws Throwable thrown when args[0] is null or not a User object
 */
public void before(Method method, Object[] args, Object target) throws Throwable {
    SecurityContext ctx = SecurityContextHolder.getContext();

    if (ctx.getAuthentication() != null) {
        Authentication auth = ctx.getAuthentication();
        boolean administrator = false;
        Collection<? extends GrantedAuthority> roles = auth.getAuthorities();
        for (GrantedAuthority role : roles) {
            if (role.getAuthority().equals(Constants.ADMIN_ROLE)) {
                administrator = true;
                break;
            }
        }

        User user = (User) args[0];

        AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        // allow new users to signup - this is OK b/c Signup doesn't allow setting of roles
        boolean signupUser = resolver.isAnonymous(auth);

        if (!signupUser) {
            UserManager userManager = (UserManager) target;
            User currentUser = getCurrentUser(auth, userManager);

            if (user.getId() != null && !user.getId().equals(currentUser.getId()) && !administrator) {
                log.warn("Access Denied: '" + currentUser.getUsername() + "' tried to modify '"
                        + user.getUsername() + "'!");
                throw new AccessDeniedException(ACCESS_DENIED);
            } else if (user.getId() != null && user.getId().equals(currentUser.getId()) && !administrator) {
                // get the list of roles the user is trying add
                Set<String> userRoles = new HashSet<String>();
                if (user.getRoles() != null) {
                    for (Object o : user.getRoles()) {
                        Role role = (Role) o;
                        userRoles.add(role.getName());
                    }
                }

                // get the list of roles the user currently has
                Set<String> authorizedRoles = new HashSet<String>();
                for (GrantedAuthority role : roles) {
                    authorizedRoles.add(role.getAuthority());
                }

                // if they don't match - access denied
                // regular users aren't allowed to change their roles
                if (!CollectionUtils.isEqualCollection(userRoles, authorizedRoles)) {
                    log.warn("Access Denied: '" + currentUser.getUsername()
                            + "' tried to change their role(s)!");
                    throw new AccessDeniedException(ACCESS_DENIED);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Registering new user '" + user.getUsername() + "'");
            }
        }
    }
}

From source file:org.nuclos.common.collect.collectable.searchcondition.CollectableIdListCondition.java

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }//from w  ww. j  av  a2s.  c o  m
    if (!(o instanceof CollectableIdListCondition)) {
        return false;
    }
    final CollectableIdListCondition that = (CollectableIdListCondition) o;

    return CollectionUtils.isEqualCollection(this.oIds, that.oIds);
}

From source file:org.nuxeo.common.codec.CryptoKeyStoreTest.java

@Override
public void setUp() throws Exception {
    super.setUp();
    Map<String, SecretKey> secretKeys = new HashMap<>();
    secretKeys.put(Crypto.AES, crypto.getSecretKey(Crypto.AES, secretKey));
    secretKeys.put(Crypto.DES, crypto.getSecretKey(Crypto.DES, secretKey));
    crypto.clear();/*from  w  ww  .j a  v  a 2 s.  co m*/

    // Generate a keystore where to store the key
    File keystoreFile = File.createTempFile("keystore", ".jceks",
            new File(System.getProperty("java.io.tmpdir")));
    keystoreFile.delete(); // ensure new keystore creation
    for (SecretKey key : secretKeys.values()) {
        Crypto.setKeyInKeyStore(keystoreFile.getPath(), keystorePass, keyAlias + key.getAlgorithm(), keyPass,
                key);
    }
    assertTrue(CollectionUtils.isEqualCollection(secretKeys.values(),
            Crypto.getKeysFromKeyStore(keystoreFile.getPath(), keystorePass, keyAlias, keyPass).values()));
    crypto = new Crypto(keystoreFile.getPath(), keystorePass, keyAlias, keyPass);
}