Example usage for java.util Set equals

List of usage examples for java.util Set equals

Introduction

In this page you can find the example usage for java.util Set equals.

Prototype

boolean equals(Object o);

Source Link

Document

Compares the specified object with this set for equality.

Usage

From source file:com.cloudant.sync.query.IndexCreator.java

/**
 *  Add a single, possibly compound index for the given field names and ensure all indexing
 *  constraints are met.//from  ww w  .ja v a 2 s .  co  m
 *
 *  This function generates a name for the new index.
 *
 *  @param proposedIndex The object that defines an index.  Includes field list, name, type and options.
 *  @return name of created index
 */
@SuppressWarnings("unchecked")
private String ensureIndexed(Index proposedIndex) {
    if (proposedIndex == null) {
        return null;
    }

    if (proposedIndex.indexType == IndexType.TEXT) {
        if (!IndexManager.ftsAvailable(queue, database)) {
            logger.log(Level.SEVERE, "Text search not supported.  To add support for text "
                    + "search, enable FTS compile options in SQLite.");
            return null;
        }
    }

    final List<String> fieldNamesList = removeDirectionsFromFields(proposedIndex.fieldNames);

    for (String fieldName : fieldNamesList) {
        if (!validFieldName(fieldName)) {
            // Logging handled in validFieldName
            return null;
        }
    }

    // Check there are no duplicate field names in the array
    Set<String> uniqueNames = new HashSet<String>(fieldNamesList);
    if (uniqueNames.size() != fieldNamesList.size()) {
        String msg = String.format("Cannot create index with duplicated field names %s",
                proposedIndex.fieldNames);
        logger.log(Level.SEVERE, msg);
    }

    // Prepend _id and _rev if it's not in the array
    if (!fieldNamesList.contains("_rev")) {
        fieldNamesList.add(0, "_rev");
    }

    if (!fieldNamesList.contains("_id")) {
        fieldNamesList.add(0, "_id");
    }

    // Check the index limit.  Limit is 1 for "text" indexes and unlimited for "json" indexes.
    // Then check whether the index already exists; return success if it does and is same,
    // else fail.
    try {

        Map<String, Object> existingIndexes = listIndexesInDatabaseQueue();

        if (proposedIndex.indexName == null) {
            // generate a name for the index.
            String indexName = IndexCreator.generateIndexName(existingIndexes.keySet());
            if (indexName == null) {
                logger.warning("Failed to generate unique index name");
                return null;
            }

            proposedIndex = Index.getInstance(proposedIndex.fieldNames, indexName, proposedIndex.indexType,
                    proposedIndex.indexSettings);
        }

        if (indexLimitReached(proposedIndex, existingIndexes)) {
            String msg = String.format("Index limit reached.  Cannot create index %s.",
                    proposedIndex.indexName);
            logger.log(Level.SEVERE, msg);
            return null;
        }
        if (existingIndexes != null && existingIndexes.get(proposedIndex.indexName) != null) {
            Map<String, Object> existingIndex = (Map<String, Object>) existingIndexes
                    .get(proposedIndex.indexName);
            IndexType existingType = (IndexType) existingIndex.get("type");
            String existingSettings = (String) existingIndex.get("settings");
            List<String> existingFieldsList = (List<String>) existingIndex.get("fields");
            Set<String> existingFields = new HashSet<String>(existingFieldsList);
            Set<String> newFields = new HashSet<String>(fieldNamesList);
            if (existingFields.equals(newFields)
                    && proposedIndex.compareIndexTypeTo(existingType, existingSettings)) {
                boolean success = IndexUpdater.updateIndex(proposedIndex.indexName, fieldNamesList, database,
                        datastore, queue);
                return success ? proposedIndex.indexName : null;
            }
        }
    } catch (ExecutionException e) {
        logger.log(Level.SEVERE, "Execution error encountered:", e);
        return null;
    } catch (InterruptedException e) {
        logger.log(Level.SEVERE, "Execution interrupted error encountered:", e);
        return null;
    }

    final Index index = proposedIndex;
    Future<Boolean> result = queue.submit(new Callable<Boolean>() {
        @Override
        public Boolean call() {
            Boolean transactionSuccess = true;
            database.beginTransaction();

            // Insert metadata table entries
            for (String fieldName : fieldNamesList) {
                ContentValues parameters = new ContentValues();
                parameters.put("index_name", index.indexName);
                parameters.put("index_type", index.indexType.toString());
                parameters.put("index_settings", index.settingsAsJSON());
                parameters.put("field_name", fieldName);
                parameters.put("last_sequence", 0);
                long rowId = database.insert(IndexManager.INDEX_METADATA_TABLE_NAME, parameters);
                if (rowId < 0) {
                    transactionSuccess = false;
                    break;
                }
            }

            // Create SQLite data structures to support the index
            // For JSON index type create a SQLite table and a SQLite index
            // For TEXT index type create a SQLite virtual table
            List<String> columnList = new ArrayList<String>();
            for (String field : fieldNamesList) {
                columnList.add("\"" + field + "\"");
            }

            List<String> statements = new ArrayList<String>();
            if (index.indexType == IndexType.TEXT) {
                List<String> settingsList = new ArrayList<String>();
                // Add text settings
                for (String key : index.indexSettings.keySet()) {
                    settingsList.add(String.format("%s=%s", key, index.indexSettings.get(key)));
                }
                statements.add(createVirtualTableStatementForIndex(index.indexName, columnList, settingsList));
            } else {
                statements.add(createIndexTableStatementForIndex(index.indexName, columnList));
                statements.add(createIndexIndexStatementForIndex(index.indexName, columnList));
            }
            for (String statement : statements) {
                try {
                    database.execSQL(statement);
                } catch (SQLException e) {
                    String msg = String.format("Index creation error occurred (%s):", statement);
                    logger.log(Level.SEVERE, msg, e);
                    transactionSuccess = false;
                    break;
                }
            }

            if (transactionSuccess) {
                database.setTransactionSuccessful();
            }
            database.endTransaction();

            return transactionSuccess;
        }
    });

    // Update the new index if it's been created
    boolean success;
    try {
        success = result.get();
    } catch (ExecutionException e) {
        logger.log(Level.SEVERE, "Execution error encountered:", e);
        return null;
    } catch (InterruptedException e) {
        logger.log(Level.SEVERE, "Execution interrupted error encountered:", e);
        return null;
    }

    if (success) {
        success = IndexUpdater.updateIndex(index.indexName, fieldNamesList, database, datastore, queue);
    }

    return success ? index.indexName : null;
}

From source file:org.osaf.cosmo.migrate.ZeroPointEightToZeroPointNineMigration.java

/**
 * Fix modification items that are out of sync with the parent item.
 *///from   www  .  ja va2  s  .c om
private void migrateModifications(Connection conn) throws Exception {

    PreparedStatement stmt = null;
    PreparedStatement updateItemStmt = null;
    PreparedStatement insertCollectionItemStmt = null;
    PreparedStatement parentsStmt = null;

    ResultSet rs = null;

    long count = 0;

    log.debug("starting migrateModifications()");

    try {
        // get all stamp/item data to migrate
        stmt = conn.prepareStatement("select id, modifiesitemid from item where modifiesitemid is not null");
        // update timestamp
        updateItemStmt = conn.prepareStatement("update item set modifydate=?, version=version+1 where id=?");
        insertCollectionItemStmt = conn
                .prepareStatement("insert into collection_item(collectionid, itemid) values (?,?)");
        parentsStmt = conn.prepareStatement("select collectionid from collection_item where itemid=?");

        rs = stmt.executeQuery();

        HashMap<Long, Set<Long>> parentMap = new HashMap<Long, Set<Long>>();

        // examine each modification and fix if necessary
        while (rs.next()) {
            long itemId = rs.getLong(1);
            long modifiesItemId = rs.getLong(2);

            Set<Long> modParents = getParents(parentsStmt, itemId);
            Set<Long> masterParents = parentMap.get(modifiesItemId);

            // cache the set of parents as it doesn't change
            if (masterParents == null) {
                masterParents = getParents(parentsStmt, modifiesItemId);
                parentMap.put(modifiesItemId, masterParents);
            }

            // If both sets of parents are equal, we are good
            if (modParents.equals(masterParents))
                continue;

            log.debug("found out-of-sync modification: id " + itemId);

            // otherwise add modification to each parent that
            // master is in
            for (Long parent : masterParents) {

                // Only care about collections that item is not in
                if (modParents.contains(parent))
                    continue;

                log.debug("adding out-of-sync modification id " + itemId + " to parent " + parent);

                // insert into parent
                insertCollectionItemStmt.setLong(1, parent);
                insertCollectionItemStmt.setLong(2, itemId);
                if (insertCollectionItemStmt.executeUpdate() != 1)
                    throw new RuntimeException("insert into collection_item failed");

                // update parent and item version/timestamps
                updateItemStmt.setLong(1, System.currentTimeMillis());
                updateItemStmt.setLong(2, itemId);
                if (updateItemStmt.executeUpdate() != 1)
                    throw new RuntimeException("update of item failed");

                updateItemStmt.setLong(1, System.currentTimeMillis());
                updateItemStmt.setLong(2, parent);
                if (updateItemStmt.executeUpdate() != 1)
                    throw new RuntimeException("update of item failed");
            }

            count++;
        }

    } finally {
        close(stmt);
        close(updateItemStmt);
        close(insertCollectionItemStmt);
        close(parentsStmt);
        close(rs);
    }

    log.debug("processed " + count + " out of sync item modifications");
}

From source file:edu.umass.cs.reconfiguration.reconfigurationutils.ConsistentReconfigurableNodeConfig.java

private synchronized boolean refreshActives() {
    Set<NodeIDType> curActives = this.nodeConfig.getActiveReplicas();
    // remove those slated for removal for CH ring purposes
    curActives.removeAll(this.activesSlatedForRemoval);
    if (curActives.equals(this.getLastActives()))
        return false;
    this.setLastActives(curActives);
    this.CH_AR.refresh(curActives);
    return true;//  w ww.  j av a  2  s . c om
}

From source file:org.mifosplatform.portfolio.group.service.GroupWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//from w ww. ja v  a2s. c  o m
public CommandProcessingResult updateGroup(final Long grouptId, final JsonCommand command) {

    GroupLevel groupLevel = null;

    try {
        this.context.authenticatedUser();

        final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(9);

        this.fromApiJsonDeserializer.validateForUpdate(command.json());

        final Group groupForUpdate = this.groupRepository.findOne(grouptId);
        if (groupForUpdate == null || groupForUpdate.isDeleted()) {
            throw new GroupNotFoundException(grouptId);
        }

        final Long officeId = groupForUpdate.getOfficeId();

        final String nameParamName = "name";
        if (command.isChangeInStringParameterNamed(nameParamName, groupForUpdate.getName())) {
            final String newValue = command.stringValueOfParameterNamed(nameParamName);
            actualChanges.put(nameParamName, newValue);
            groupForUpdate.setName(StringUtils.defaultIfEmpty(newValue, null));
        }

        final String externalIdParamName = "externalId";
        if (command.isChangeInStringParameterNamed(externalIdParamName, groupForUpdate.getExternalId())) {
            final String newValue = command.stringValueOfParameterNamed(externalIdParamName);
            actualChanges.put(externalIdParamName, newValue);
            groupForUpdate.setExternalId(StringUtils.defaultIfEmpty(newValue, null));
        }

        final Staff presentStaff = groupForUpdate.getStaff();
        Long presentStaffId = null;
        if (presentStaff != null) {
            presentStaffId = presentStaff.getId();
        }

        final String staffIdParamName = "staffId";
        if (command.isChangeInLongParameterNamed(staffIdParamName, presentStaffId)) {
            final Long newValue = command.longValueOfParameterNamed(staffIdParamName);
            actualChanges.put(staffIdParamName, newValue);

            Staff newStaff = null;
            if (newValue != null) {
                newStaff = this.staffRepository.findByOffice(newValue, officeId);
                if (newStaff == null) {
                    throw new StaffNotFoundException(newValue);
                }
            }
            groupForUpdate.setStaff(newStaff);
        }

        groupLevel = this.groupLevelRepository.findOne(groupForUpdate.getGroupLevel().getId());

        /*
         * Ignoring parentId param, if group for update is super parent.
         * TODO Need to check: Ignoring is correct or need throw unsupported
         * param
         */
        if (!groupLevel.isSuperParent()) {

            final String parentIdParamName = "parentId";
            Long parentId = null;
            final Group presentParentGroup = groupForUpdate.getParent();

            if (presentParentGroup != null) {
                parentId = presentParentGroup.getId();
            }

            if (command.isChangeInLongParameterNamed(parentIdParamName, parentId)) {

                final Long newValue = command.longValueOfParameterNamed(parentIdParamName);
                actualChanges.put(parentIdParamName, newValue);
                Group newParentGroup = null;
                if (newValue != null) {
                    newParentGroup = this.groupRepository.findOne(newValue);
                    if (newParentGroup == null || newParentGroup.isDeleted()) {
                        throw new StaffNotFoundException(newValue);
                    }

                    if (!newParentGroup.isOfficeIdentifiedBy(officeId)) {
                        final String errorMessage = "Group and parent group must have the same office";
                        throw new InvalidOfficeException("group", "attach.to.parent.group", errorMessage);
                    }
                    /*
                     * If Group is not super parent then validate group
                     * level's parent level is same as group parent's level
                     * this check makes sure new group is added at immediate
                     * next level in hierarchy
                     */

                    if (!groupForUpdate.getGroupLevel()
                            .isIdentifiedByParentId(newParentGroup.getGroupLevel().getId())) {
                        final String errorMessage = "Parent group's level is  not equal to child level's parent level ";
                        throw new InvalidGroupLevelException("add", "invalid.level", errorMessage);
                    }
                }

                groupForUpdate.setParent(newParentGroup);

                // Parent has changed, re-generate 'Hierarchy' as parent is changed   
                groupForUpdate.generateHierarchy();

            }
        }

        final Set<Client> clientMembers = assembleSetOfClients(officeId, command);
        final String clientMembersParamName = "clientMembers";

        if (!clientMembers.equals(groupForUpdate.getClientMembers())) {
            Set<Client> diffClients = Sets.symmetricDifference(clientMembers,
                    groupForUpdate.getClientMembers());
            final String[] diffClientsIds = getClientIds(diffClients);
            actualChanges.put(clientMembersParamName, diffClientsIds);
            groupForUpdate.setClientMembers(clientMembers);
        }

        this.groupRepository.saveAndFlush(groupForUpdate);

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withOfficeId(groupForUpdate.getId()) //
                .withGroupId(groupForUpdate.getOfficeId()) //
                .withEntityId(groupForUpdate.getId()) //
                .with(actualChanges) //
                .build();

    } catch (final DataIntegrityViolationException dve) {
        handleGroupDataIntegrityIssues(command, dve, groupLevel);
        return new CommandProcessingResult(Long.valueOf(-1));
    }
}

From source file:org.mitre.openid.connect.request.ConnectOAuth2RequestFactory.java

/**
 * @param inputParams//w w w . j  a  v a 2s .  c  o m
 * @return
 */
private void processRequestObject(String jwtString, AuthorizationRequest request) {

    // parse the request object
    try {
        JWT jwt = JWTParser.parse(jwtString);

        if (jwt instanceof SignedJWT) {
            // it's a signed JWT, check the signature

            SignedJWT signedJwt = (SignedJWT) jwt;

            // need to check clientId first so that we can load the client to check other fields
            if (request.getClientId() == null) {
                request.setClientId(signedJwt.getJWTClaimsSet().getStringClaim(CLIENT_ID));
            }

            ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

            if (client == null) {
                throw new InvalidClientException("Client not found: " + request.getClientId());
            }

            JWSAlgorithm alg = signedJwt.getHeader().getAlgorithm();

            if (client.getRequestObjectSigningAlg() == null
                    || !client.getRequestObjectSigningAlg().equals(alg)) {
                throw new InvalidClientException("Client's registered request object signing algorithm ("
                        + client.getRequestObjectSigningAlg()
                        + ") does not match request object's actual algorithm (" + alg.getName() + ")");
            }

            JWTSigningAndValidationService validator = validators.getValidator(client, alg);

            if (validator == null) {
                throw new InvalidClientException(
                        "Unable to create signature validator for client " + client + " and algorithm " + alg);
            }

            if (!validator.validateSignature(signedJwt)) {
                throw new InvalidClientException(
                        "Signature did not validate for presented JWT request object.");
            }

        } else if (jwt instanceof PlainJWT) {
            PlainJWT plainJwt = (PlainJWT) jwt;

            // need to check clientId first so that we can load the client to check other fields
            if (request.getClientId() == null) {
                request.setClientId(plainJwt.getJWTClaimsSet().getStringClaim(CLIENT_ID));
            }

            ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

            if (client == null) {
                throw new InvalidClientException("Client not found: " + request.getClientId());
            }

            if (client.getRequestObjectSigningAlg() == null) {
                throw new InvalidClientException(
                        "Client is not registered for unsigned request objects (no request_object_signing_alg registered)");
            } else if (!client.getRequestObjectSigningAlg().equals(Algorithm.NONE)) {
                throw new InvalidClientException(
                        "Client is not registered for unsigned request objects (request_object_signing_alg is "
                                + client.getRequestObjectSigningAlg() + ")");
            }

            // if we got here, we're OK, keep processing

        } else if (jwt instanceof EncryptedJWT) {

            EncryptedJWT encryptedJWT = (EncryptedJWT) jwt;

            // decrypt the jwt if we can

            encryptionService.decryptJwt(encryptedJWT);

            // TODO: what if the content is a signed JWT? (#525)

            if (!encryptedJWT.getState().equals(State.DECRYPTED)) {
                throw new InvalidClientException("Unable to decrypt the request object");
            }

            // need to check clientId first so that we can load the client to check other fields
            if (request.getClientId() == null) {
                request.setClientId(encryptedJWT.getJWTClaimsSet().getStringClaim(CLIENT_ID));
            }

            ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

            if (client == null) {
                throw new InvalidClientException("Client not found: " + request.getClientId());
            }

        }

        /*
         * NOTE: Claims inside the request object always take precedence over those in the parameter map.
         */

        // now that we've got the JWT, and it's been parsed, validated, and/or decrypted, we can process the claims

        JWTClaimsSet claims = jwt.getJWTClaimsSet();

        Set<String> responseTypes = OAuth2Utils.parseParameterList(claims.getStringClaim(RESPONSE_TYPE));
        if (responseTypes != null && !responseTypes.isEmpty()) {
            if (!responseTypes.equals(request.getResponseTypes())) {
                logger.info(
                        "Mismatch between request object and regular parameter for response_type, using request object");
            }
            request.setResponseTypes(responseTypes);
        }

        String redirectUri = claims.getStringClaim(REDIRECT_URI);
        if (redirectUri != null) {
            if (!redirectUri.equals(request.getRedirectUri())) {
                logger.info(
                        "Mismatch between request object and regular parameter for redirect_uri, using request object");
            }
            request.setRedirectUri(redirectUri);
        }

        String state = claims.getStringClaim(STATE);
        if (state != null) {
            if (!state.equals(request.getState())) {
                logger.info(
                        "Mismatch between request object and regular parameter for state, using request object");
            }
            request.setState(state);
        }

        String nonce = claims.getStringClaim(NONCE);
        if (nonce != null) {
            if (!nonce.equals(request.getExtensions().get(NONCE))) {
                logger.info(
                        "Mismatch between request object and regular parameter for nonce, using request object");
            }
            request.getExtensions().put(NONCE, nonce);
        }

        String display = claims.getStringClaim(DISPLAY);
        if (display != null) {
            if (!display.equals(request.getExtensions().get(DISPLAY))) {
                logger.info(
                        "Mismatch between request object and regular parameter for display, using request object");
            }
            request.getExtensions().put(DISPLAY, display);
        }

        String prompt = claims.getStringClaim(PROMPT);
        if (prompt != null) {
            if (!prompt.equals(request.getExtensions().get(PROMPT))) {
                logger.info(
                        "Mismatch between request object and regular parameter for prompt, using request object");
            }
            request.getExtensions().put(PROMPT, prompt);
        }

        Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim(SCOPE));
        if (scope != null && !scope.isEmpty()) {
            if (!scope.equals(request.getScope())) {
                logger.info(
                        "Mismatch between request object and regular parameter for scope, using request object");
            }
            request.setScope(scope);
        }

        JsonObject claimRequest = parseClaimRequest(claims.getStringClaim(CLAIMS));
        if (claimRequest != null) {
            if (!claimRequest.equals(parseClaimRequest(request.getExtensions().get(CLAIMS).toString()))) {
                logger.info(
                        "Mismatch between request object and regular parameter for claims, using request object");
            }
            // we save the string because the object might not be a Java Serializable, and we can parse it easily enough anyway
            request.getExtensions().put(CLAIMS, claimRequest.toString());
        }

        String loginHint = claims.getStringClaim(LOGIN_HINT);
        if (loginHint != null) {
            if (!loginHint.equals(request.getExtensions().get(LOGIN_HINT))) {
                logger.info(
                        "Mistmatch between request object and regular parameter for login_hint, using requst object");
            }
            request.getExtensions().put(LOGIN_HINT, loginHint);
        }

    } catch (ParseException e) {
        logger.error("ParseException while parsing RequestObject:", e);
    }
}

From source file:com.linkedin.pinot.integration.tests.Pql2CompilerTest.java

private boolean filterQueryIsEquivalent(List<Integer> leftIds, List<Integer> rightIds,
        FilterQueryMap leftFilterQueries, FilterQueryMap rightFilterQueries) {
    ArrayList<Integer> leftIdsCopy = new ArrayList<>(leftIds);
    ArrayList<Integer> rightIdsCopy = new ArrayList<>(rightIds);

    if (leftIdsCopy.size() != rightIdsCopy.size()) {
        return false;
    }//from  ww w. j a  v  a2  s  .  c o  m

    Iterator<Integer> leftIterator = leftIdsCopy.iterator();

    while (leftIterator.hasNext()) {
        Integer leftId = leftIterator.next();
        FilterQuery leftQuery = leftFilterQueries.getFilterQueryMap().get(leftId);

        Iterator<Integer> rightIterator = rightIdsCopy.iterator();
        while (rightIterator.hasNext()) {
            Integer rightId = rightIterator.next();
            FilterQuery rightQuery = rightFilterQueries.getFilterQueryMap().get(rightId);

            boolean operatorsAreEqual = EqualityUtils.isEqual(leftQuery.getOperator(),
                    rightQuery.getOperator());
            boolean columnsAreEqual = EqualityUtils.isEqual(leftQuery.getColumn(), rightQuery.getColumn());
            boolean valuesAreEqual = EqualityUtils.isEqual(leftQuery.getValue(), rightQuery.getValue());
            boolean fieldsAreEqual = columnsAreEqual && operatorsAreEqual && valuesAreEqual;

            // Compare sets if the op is IN
            if (operatorsAreEqual && columnsAreEqual && leftQuery.getOperator() == FilterOperator.IN) {
                Set<String> leftValues = new HashSet<>(
                        Arrays.asList(leftQuery.getValue().get(0).split("\t\t")));
                Set<String> rightValues = new HashSet<>(
                        Arrays.asList(rightQuery.getValue().get(0).split("\t\t")));
                fieldsAreEqual = leftValues.equals(rightValues);
                if (!fieldsAreEqual) {
                    System.out.println("in clause not the same?");
                    System.out.println("leftValues = " + leftValues);
                    System.out.println("rightValues = " + rightValues);
                }
            }

            // NOT_IN and NOT are equivalent
            if (!operatorsAreEqual && columnsAreEqual && valuesAreEqual) {
                if ((leftQuery.getOperator() == FilterOperator.NOT
                        || leftQuery.getOperator() == FilterOperator.NOT_IN)
                        && (rightQuery.getOperator() == FilterOperator.NOT
                                || rightQuery.getOperator() == FilterOperator.NOT_IN)) {
                    fieldsAreEqual = true;
                }
            }

            if (fieldsAreEqual) {
                if (filterQueryIsEquivalent(leftQuery.getNestedFilterQueryIds(),
                        rightQuery.getNestedFilterQueryIds(), leftFilterQueries, rightFilterQueries)) {
                    leftIterator.remove();
                    rightIterator.remove();
                    break;
                }
            }
        }
    }

    return leftIdsCopy.isEmpty();
}

From source file:edu.umass.cs.reconfiguration.reconfigurationutils.ConsistentReconfigurableNodeConfig.java

private synchronized boolean refreshReconfigurators() {
    Set<NodeIDType> curReconfigurators = this.nodeConfig.getReconfigurators();
    // remove those slated for removal for CH ring purposes
    curReconfigurators.removeAll(this.reconfiguratorsSlatedForRemoval);
    if (curReconfigurators.equals(this.getLastReconfigurators()))
        return false;
    this.setLastReconfigurators(curReconfigurators);
    this.CH_RC.refresh(curReconfigurators);
    return true;/* w  ww  .  j av a  2 s .  c  om*/
}

From source file:org.libreplan.web.common.entrypoints.EntryPointsHandler.java

private <S> boolean applyIfMatches(final S controller, Map<String, String> matrixParams) {
    flagAlreadyExecutedInThisRequest();/*from  w ww .j a v  a2  s  .c  o m*/

    Set<String> matrixParamsNames = matrixParams.keySet();

    for (Entry<String, EntryPointMetadata> entry : metadata.entrySet()) {

        final EntryPointMetadata entryPointMetadata = entry.getValue();

        EntryPoint entryPointAnnotation = entryPointMetadata.annotation;

        HashSet<String> requiredParams = new HashSet<>(Arrays.asList(entryPointAnnotation.value()));

        if (matrixParamsNames.equals(requiredParams)) {

            final Object[] arguments = retrieveArguments(matrixParams, entryPointAnnotation,
                    entryPointMetadata.method.getParameterTypes());

            Util.executeIgnoringCreationOfBindings(
                    () -> callMethod(controller, entryPointMetadata.method, arguments));

            return true;
        }
    }

    return false;
}

From source file:com.adaptris.core.AdaptrisMessageCase.java

@Test
public void testSetMetadata() throws Exception {
    AdaptrisMessage msg1 = createMessage();

    MetadataElement mez = new MetadataElement("key6", "val6");
    Set newMetadata = new HashSet();
    newMetadata.add(mez);/*from  w w w . ja  v  a2 s.  co m*/

    msg1.clearMetadata();
    msg1.setMetadata(newMetadata);

    assertTrue(newMetadata.equals(msg1.getMetadata()));
}

From source file:org.apache.syncope.core.provisioning.java.propagation.AbstractPropagationTaskExecutor.java

protected Uid createOrUpdate(final PropagationTask task, final ConnectorObject beforeObj,
        final Connector connector, final Boolean[] propagationAttempted) {

    // set of attributes to be propagated
    Set<Attribute> attributes = new HashSet<>(task.getAttributes());

    // check if there is any missing or null / empty mandatory attribute
    Set<Object> mandatoryAttrNames = new HashSet<>();
    Attribute mandatoryMissing = AttributeUtil.find(MANDATORY_MISSING_ATTR_NAME, task.getAttributes());
    if (mandatoryMissing != null) {
        attributes.remove(mandatoryMissing);

        if (beforeObj == null) {
            mandatoryAttrNames.addAll(mandatoryMissing.getValue());
        }//ww  w.j a v a 2 s  .  co m
    }
    Attribute mandatoryNullOrEmpty = AttributeUtil.find(MANDATORY_NULL_OR_EMPTY_ATTR_NAME,
            task.getAttributes());
    if (mandatoryNullOrEmpty != null) {
        attributes.remove(mandatoryNullOrEmpty);

        mandatoryAttrNames.addAll(mandatoryNullOrEmpty.getValue());
    }
    if (!mandatoryAttrNames.isEmpty()) {
        throw new IllegalArgumentException(
                "Not attempted because there are mandatory attributes without value(s): " + mandatoryAttrNames);
    }

    Uid result;
    if (beforeObj == null) {
        LOG.debug("Create {} on {}", attributes, task.getResource().getKey());
        result = connector.create(new ObjectClass(task.getObjectClassName()), attributes, null,
                propagationAttempted);
    } else {
        // 1. check if rename is really required
        Name newName = AttributeUtil.getNameFromAttributes(attributes);

        LOG.debug("Rename required with value {}", newName);

        if (newName != null && newName.equals(beforeObj.getName())
                && !newName.getNameValue().equals(beforeObj.getUid().getUidValue())) {

            LOG.debug("Remote object name unchanged");
            attributes.remove(newName);
        }

        // 2. check wether anything is actually needing to be propagated, i.e. if there is attribute
        // difference between beforeObj - just read above from the connector - and the values to be propagated
        Map<String, Attribute> originalAttrMap = beforeObj.getAttributes().stream()
                .collect(Collectors.toMap(attr -> attr.getName().toUpperCase(), attr -> attr));
        Map<String, Attribute> updateAttrMap = attributes.stream()
                .collect(Collectors.toMap(attr -> attr.getName().toUpperCase(), attr -> attr));

        // Only compare attribute from beforeObj that are also being updated
        Set<String> skipAttrNames = originalAttrMap.keySet();
        skipAttrNames.removeAll(updateAttrMap.keySet());
        new HashSet<>(skipAttrNames).forEach(attrName -> {
            originalAttrMap.remove(attrName);
        });

        Set<Attribute> originalAttrs = new HashSet<>(originalAttrMap.values());

        if (originalAttrs.equals(attributes)) {
            LOG.debug("Don't need to propagate anything: {} is equal to {}", originalAttrs, attributes);
            result = AttributeUtil.getUidAttribute(attributes);
        } else {
            LOG.debug("Attributes that would be updated {}", attributes);

            Set<Attribute> strictlyModified = new HashSet<>();
            attributes.stream().filter(attr -> (!originalAttrs.contains(attr))).forEachOrdered(attr -> {
                strictlyModified.add(attr);
            });

            // 3. provision entry
            LOG.debug("Update {} on {}", strictlyModified, task.getResource().getKey());

            result = connector.update(beforeObj.getObjectClass(), new Uid(beforeObj.getUid().getUidValue()),
                    strictlyModified, null, propagationAttempted);
        }
    }

    return result;
}