Example usage for java.util List retainAll

List of usage examples for java.util List retainAll

Introduction

In this page you can find the example usage for java.util List retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this list that are contained in the specified collection (optional operation).

Usage

From source file:gov.nih.nci.caintegrator.application.query.CompoundCriterionHandler.java

private void filterResults(Set<ResultRow> rowsBeforeRestriction,
        Set<StudySubjectAssignment> listOfAllowedStudySubjectAssignments,
        Set<String> listOfAllowedExperimentIdentifiers, Set<ResultRow> rowsAfterRestriction,
        ResultTypeEnum queryResultType) {
    List<StudySubjectAssignment> listOfRestrictedStudySubjectAssignments = new ArrayList<StudySubjectAssignment>();
    for (ResultRow resultRow : rowsBeforeRestriction) {
        listOfRestrictedStudySubjectAssignments.add(resultRow.getSubjectAssignment());
    }//  w w  w .j  a  v a  2s. c om

    listOfRestrictedStudySubjectAssignments.retainAll(listOfAllowedStudySubjectAssignments);
    String expId = StringUtils.EMPTY;
    for (ResultRow resultRow2 : rowsBeforeRestriction) {
        if (areQueryResultsGenomic(queryResultType)) {
            expId = resultRow2.getSampleAcquisition().getSample().getGenomicDataSource()
                    .getExperimentIdentifier();
            if (listOfRestrictedStudySubjectAssignments.contains(resultRow2.getSubjectAssignment())
                    && listOfAllowedExperimentIdentifiers.contains(expId)) {
                rowsAfterRestriction.add(resultRow2);
            }
        } else if (listOfRestrictedStudySubjectAssignments.contains(resultRow2.getSubjectAssignment())) {
            rowsAfterRestriction.add(resultRow2);
        }
    }
}

From source file:org.apache.hyracks.algebricks.rewriter.rules.AbstractIntroduceGroupByCombinerRule.java

private boolean tryToPushRoot(Mutable<ILogicalOperator> root, GroupByOperator oldGbyOp,
        GroupByOperator newGbyOp, BookkeepingInfo bi, List<LogicalVariable> gbyVars,
        IOptimizationContext context, List<Mutable<ILogicalOperator>> toPushAccumulate,
        Set<SimilarAggregatesInfo> toReplaceSet) throws AlgebricksException {
    AbstractLogicalOperator op1 = (AbstractLogicalOperator) root.getValue();
    if (op1.getOperatorTag() != LogicalOperatorTag.AGGREGATE) {
        return false;
    }/*from www  .  j  a  v  a 2 s.  c o m*/
    AbstractLogicalOperator op2 = (AbstractLogicalOperator) op1.getInputs().get(0).getValue();
    // Finds nested group-by if any.
    AbstractLogicalOperator op3 = op2;
    while (op3.getOperatorTag() != LogicalOperatorTag.GROUP && op3.getInputs().size() == 1) {
        op3 = (AbstractLogicalOperator) op3.getInputs().get(0).getValue();
    }

    if (op3.getOperatorTag() != LogicalOperatorTag.GROUP) {
        AggregateOperator initAgg = (AggregateOperator) op1;
        Pair<Boolean, Mutable<ILogicalOperator>> pOpRef = tryToPushAgg(initAgg, newGbyOp, toReplaceSet,
                context);
        if (!pOpRef.first) {
            return false;
        }
        Mutable<ILogicalOperator> opRef = pOpRef.second;
        if (opRef != null) {
            toPushAccumulate.add(opRef);
        }
        bi.modifyGbyMap.put(oldGbyOp, gbyVars);
        return true;
    } else {
        GroupByOperator nestedGby = (GroupByOperator) op3;
        List<LogicalVariable> gbyVars2 = nestedGby.getGbyVarList();
        Set<LogicalVariable> freeVars = new HashSet<>();
        // Removes non-free variables defined in the nested plan.
        OperatorPropertiesUtil.getFreeVariablesInSelfOrDesc(nestedGby, freeVars);
        gbyVars2.retainAll(freeVars);

        List<LogicalVariable> concatGbyVars = new ArrayList<LogicalVariable>(gbyVars);
        concatGbyVars.addAll(gbyVars2);
        for (ILogicalPlan p : nestedGby.getNestedPlans()) {
            for (Mutable<ILogicalOperator> r2 : p.getRoots()) {
                if (!tryToPushRoot(r2, nestedGby, newGbyOp, bi, concatGbyVars, context, toPushAccumulate,
                        toReplaceSet)) {
                    return false;
                }
            }
        }

        /***
         * Push the nested pipeline which provides the input to the nested group operator into newGbyOp (the combined gby op).
         * The change is to fix asterixdb issue 782.
         */
        // Finds the reference of the bottom-most operator in the pipeline that
        // should not be pushed to the combiner group-by.
        Mutable<ILogicalOperator> currentOpRef = new MutableObject<ILogicalOperator>(nestedGby);
        Mutable<ILogicalOperator> bottomOpRef = findBottomOpRefStayInOldGby(currentOpRef);

        // Adds the used variables in the pipeline from <code>currentOpRef</code> to <code>bottomOpRef</code>
        // into the group-by keys for the introduced combiner group-by operator.
        Set<LogicalVariable> usedVars = collectUsedFreeVariables(currentOpRef, bottomOpRef);
        for (LogicalVariable usedVar : usedVars) {
            if (!concatGbyVars.contains(usedVar)) {
                concatGbyVars.add(usedVar);
            }
        }

        // Retains the nested pipeline above the identified operator in the old group-by operator.
        // Pushes the nested pipeline under the select operator into the new group-by operator.
        Mutable<ILogicalOperator> oldNtsRef = findNtsRef(currentOpRef);
        ILogicalOperator opToCombiner = bottomOpRef.getValue().getInputs().get(0).getValue();
        if (opToCombiner.getOperatorTag() == LogicalOperatorTag.NESTEDTUPLESOURCE) {
            // No pipeline other than the aggregate operator needs to push to combiner.
            return true;
        }
        bottomOpRef.getValue().getInputs().set(0, new MutableObject<ILogicalOperator>(oldNtsRef.getValue()));
        Mutable<ILogicalOperator> newGbyNestedOpRef = findNtsRef(toPushAccumulate.get(0));
        NestedTupleSourceOperator newNts = (NestedTupleSourceOperator) newGbyNestedOpRef.getValue();
        newGbyNestedOpRef.setValue(opToCombiner);
        oldNtsRef.setValue(newNts);
        return true;
    }
}

From source file:org.apache.syncope.core.persistence.jpa.content.XMLContentExporter.java

private List<String> sortByForeignKeys(final String dbSchema, final Connection conn,
        final Set<String> tableNames) throws SQLException {

    Set<MultiParentNode<String>> roots = new HashSet<>();

    final DatabaseMetaData meta = conn.getMetaData();

    final Map<String, MultiParentNode<String>> exploited = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    final Set<String> pkTableNames = new HashSet<>();

    for (String tableName : tableNames) {
        MultiParentNode<String> node = exploited.get(tableName);
        if (node == null) {
            node = new MultiParentNode<>(tableName);
            roots.add(node);/*from  w w w. j  a  v a2s.  c o  m*/
            exploited.put(tableName, node);
        }

        pkTableNames.clear();

        ResultSet rs = null;
        try {
            rs = meta.getImportedKeys(conn.getCatalog(), dbSchema, tableName);

            // this is to avoid repetition
            while (rs.next()) {
                pkTableNames.add(rs.getString("PKTABLE_NAME"));
            }
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    LOG.error("While closing tables result set", e);
                }
            }
        }

        for (String pkTableName : pkTableNames) {
            if (!tableName.equalsIgnoreCase(pkTableName)) {
                MultiParentNode<String> pkNode = exploited.get(pkTableName);
                if (pkNode == null) {
                    pkNode = new MultiParentNode<>(pkTableName);
                    roots.add(pkNode);
                    exploited.put(pkTableName, pkNode);
                }

                pkNode.addChild(node);

                if (roots.contains(node)) {
                    roots.remove(node);
                }
            }
        }
    }

    final List<String> sortedTableNames = new ArrayList<>(tableNames.size());
    MultiParentNodeOp.traverseTree(roots, sortedTableNames);

    // remove from sortedTableNames any table possibly added during lookup 
    // but matching some item in this.tablePrefixesToBeExcluded
    sortedTableNames.retainAll(tableNames);

    LOG.debug("Tables after retainAll {}", sortedTableNames);

    Collections.reverse(sortedTableNames);

    return sortedTableNames;
}

From source file:ubic.gemma.core.visualization.ExperimentalDesignVisualizationServiceImpl.java

@Override
public Map<Long, LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>>> sortVectorDataByDesign(
        Collection<DoubleVectorValueObject> dedVs) {

    // cachedLayouts.clear(); // uncomment FOR DEBUGGING.

    if (dedVs == null) {
        return new HashMap<>(0);
    }/*from   ww  w.  j av  a 2 s  .  c  om*/

    Map<Long, LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>>> returnedLayouts = new HashMap<>(
            dedVs.size());

    StopWatch timer = new StopWatch();
    timer.start();

    /*
     * This is shared across experiments that might show up in the dedVs; this should be okay...saves computation.
     * This is the only slow part.
     */
    this.prepare(dedVs);

    /*
     * This loop is not a performance issue.
     */
    Map<DoubleVectorValueObject, List<BioAssayValueObject>> newOrderingsForBioAssayDimensions = new HashMap<>();
    for (DoubleVectorValueObject vec : dedVs) {

        if (vec.isReorganized()) {
            continue;
        }

        assert !vec.getBioAssays().isEmpty();

        LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>> layout = null;

        if (cachedLayouts.containsKey(vec.getExpressionExperiment().getId())) {
            layout = cachedLayouts.get(vec.getExpressionExperiment().getId());
        } else if (vec.getExpressionExperiment().getClass()
                .isInstance(ExpressionExperimentSubsetValueObject.class)) {
            // subset.
            layout = cachedLayouts.get(((ExpressionExperimentSubsetValueObject) vec.getExpressionExperiment())
                    .getSourceExperiment());
        }

        if (layout == null || layout.isEmpty()) {
            log.error("Did not find cached layout for " + vec.getId());
            continue;
        }

        List<BioAssayValueObject> newOrdering = new ArrayList<>(layout.keySet());

        newOrdering.retainAll(vec.getBioAssays());

        /*
         * This can happen if the vectors are out of whack with the bioassays - e.g. two platforms were used but
         * merging is not done. See bug 3775. Skipping the ordering is not the right thing to do.
         */
        if (newOrdering.isEmpty()) {

            boolean allNaN = this.allNaN(vec);

            if (allNaN) {
                // reordering will have no effect.
                continue;
            }

            /*
             * Add to the layout.
             */
            layout = this.extendLayout(vec, vec.getExpressionExperiment().getId());
            newOrdering = new ArrayList<>(layout.keySet());
            newOrdering.retainAll(vec.getBioAssays());
            assert !newOrdering.isEmpty();
        }

        newOrderingsForBioAssayDimensions.put(vec, newOrdering);

        Map<BioAssayValueObject, Integer> ordering = this.getOrdering(newOrdering);

        Long eeId;
        eeId = vec.getExpressionExperiment().getId(); // might be subset id.

        if (!returnedLayouts.containsKey(eeId)) {
            if (vec.isSliced()) {
                LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>> trimmedLayout = new LinkedHashMap<>();

                for (BioAssayValueObject baVo : newOrdering) {
                    trimmedLayout.put(baVo, layout.get(baVo));
                }

                returnedLayouts.put(eeId, trimmedLayout);

            } else {
                returnedLayouts.put(eeId, layout);
            }
        }

        /*
         * Might be a faster way.
         */
        double[] data = vec.getData();
        double[] dol = ArrayUtils.clone(data);

        // assert ordering.size() == data.length : "got " + ordering.size() + " expected " + data.length;

        List<BioAssayValueObject> oldOrdering = vec.getBioAssayDimension().getBioAssays();
        int j = 0;
        if (log.isTraceEnabled())
            log.trace("Old order: " + StringUtils.join(ArrayUtils.toObject(data), ","));
        for (BioAssayValueObject ba : oldOrdering) {

            if (ordering.get(ba) == null) {
                assert Double.isNaN(dol[j]);
                j++;
                continue;
            }

            assert ordering.containsKey(ba);
            assert ordering.get(ba) != null;

            Integer targetIndex = ordering.get(ba);

            data[targetIndex] = dol[j++];

        }
        if (log.isTraceEnabled())
            log.trace("New order: " + StringUtils.join(ArrayUtils.toObject(data), ","));

        vec.setReorganized(true);

    }

    for (DoubleVectorValueObject vec : dedVs) {
        if (vec.getBioAssayDimension().isReordered())
            continue;
        List<BioAssayValueObject> newOrdering = newOrderingsForBioAssayDimensions.get(vec);
        if (newOrdering == null)
            continue; // data was empty, etc.
        vec.getBioAssayDimension().reorder(newOrdering);
    }

    if (timer.getTime() > 1500) {
        log.info("Sort vectors by design: " + timer.getTime() + "ms");
    }

    return returnedLayouts;

}

From source file:org.silverpeas.core.notification.user.delayed.DelayedNotificationManagerIT.java

/**
 * Centralizing assertions/* ww w  .j  a va 2  s  . c o  m*/
 *
 * @param date
 * @param aimedChannels
 * @param defaultDelayedNotificationFrequency
 * @param expectedUsers
 */
private void assertFindUsersToBeNotified(final Date date, final Set<NotifChannel> aimedChannels,
        final DelayedNotificationFrequency defaultDelayedNotificationFrequency,
        final Integer... expectedUsers) {
    Integer[] notExpectedUsers = new Integer[] { 51, 52, 53, 54, 55, 56 };
    final List<Integer> usersToNotify = manager.findUsersToBeNotified(date, aimedChannels,
            defaultDelayedNotificationFrequency);
    usersToNotify.retainAll(Arrays.asList(notExpectedUsers));
    if (expectedUsers != null && expectedUsers.length > 0) {
        notExpectedUsers = ArrayUtils.removeElements(notExpectedUsers, expectedUsers);
    }
    assertThat(usersToNotify, notNullValue());
    if (expectedUsers != null && expectedUsers.length > 0) {
        assertThat(usersToNotify.toArray(new Integer[] {}), arrayContainingInAnyOrder(expectedUsers));
    }
    if (notExpectedUsers.length > 0) {
        assertThat(usersToNotify.toArray(new Integer[] {}), not(arrayContainingInAnyOrder(notExpectedUsers)));
    }
}

From source file:org.wso2.carbon.apimgt.keymgt.issuers.RoleBasedScopesIssuer.java

@Override
public List<String> getScopes(OAuthTokenReqMessageContext tokReqMsgCtx, List<String> whiteListedScopes) {
    String[] requestedScopes = tokReqMsgCtx.getScope();
    List<String> defaultScope = new ArrayList<String>();
    defaultScope.add(DEFAULT_SCOPE_NAME);

    String consumerKey = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();
    String username = tokReqMsgCtx.getAuthorizedUser().getUserName();
    String endUsernameWithDomain = addDomainToName(username,
            tokReqMsgCtx.getAuthorizedUser().getUserStoreDomain());
    List<String> reqScopeList = Arrays.asList(requestedScopes);
    Map<String, String> restAPIScopesOfCurrentTenant;

    try {/*from w  w  w.  j  a  va2s. c om*/
        Map<String, String> appScopes;
        ApiMgtDAO apiMgtDAO = getApiMgtDAOInstance();
        //Get all the scopes and roles against the scopes defined for the APIs subscribed to the application.
        appScopes = apiMgtDAO.getScopeRolesOfApplication(consumerKey);
        //Add API Manager rest API scopes set. This list should be loaded at server start up and keep
        //in memory and add it to each and every request coming.
        String tenantDomain = tokReqMsgCtx.getAuthorizedUser().getTenantDomain();
        restAPIScopesOfCurrentTenant = (Map) getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)
                .getCache("REST_API_SCOPE_CACHE").get(tenantDomain);
        if (restAPIScopesOfCurrentTenant != null) {
            appScopes.putAll(restAPIScopesOfCurrentTenant);
        } else {
            restAPIScopesOfCurrentTenant = getRESTAPIScopesFromConfig(
                    getTenantRESTAPIScopesConfig(tenantDomain));
            //call load tenant config for rest API.
            //then put cache
            appScopes.putAll(restAPIScopesOfCurrentTenant);
            getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache("REST_API_SCOPE_CACHE")
                    .put(tenantDomain, restAPIScopesOfCurrentTenant);
        }

        //If no scopes can be found in the context of the application
        if (appScopes.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug("No scopes defined for the Application "
                        + tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId());
            }

            List<String> allowedScopes = getAllowedScopes(whiteListedScopes, reqScopeList);
            return allowedScopes;
        }

        int tenantId;
        RealmService realmService = getRealmService();
        UserStoreManager userStoreManager;
        String[] userRoles;

        try {
            tenantId = realmService.getTenantManager().getTenantId(tenantDomain);

            // If tenant Id is not set in the tokenReqContext, deriving it from username.
            if (tenantId == 0 || tenantId == -1) {
                tenantId = getTenantIdOfUser(username);
            }

            String grantType = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType();
            userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();

            // If GrantType is SAML20_BEARER and CHECK_ROLES_FROM_SAML_ASSERTION is true,
            // use user roles from assertion otherwise use roles from userstore.
            String isSAML2Enabled = System.getProperty(ResourceConstants.CHECK_ROLES_FROM_SAML_ASSERTION);
            if (GrantType.SAML20_BEARER.toString().equals(grantType) && Boolean.parseBoolean(isSAML2Enabled)) {
                Assertion assertion = (Assertion) tokReqMsgCtx.getProperty(ResourceConstants.SAML2_ASSERTION);
                userRoles = getRolesFromAssertion(assertion);
            } else {
                userRoles = userStoreManager.getRoleListOfUser(endUsernameWithDomain);
            }

        } catch (UserStoreException e) {
            //Log and return since we do not want to stop issuing the token in case of scope validation failures.
            log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e);
            return null;
        }

        if (userRoles == null || userRoles.length == 0) {
            if (log.isDebugEnabled()) {
                log.debug("Could not find roles of the user.");
            }
            return defaultScope;
        }

        List<String> authorizedScopes = new ArrayList<String>();
        String preservedCaseSensitiveValue = System.getProperty(PRESERVED_CASE_SENSITIVE_VARIABLE);
        boolean preservedCaseSensitive = JavaUtils.isTrueExplicitly(preservedCaseSensitiveValue);
        List<String> userRoleList;
        if (preservedCaseSensitive) {
            userRoleList = Arrays.asList(userRoles);
        } else {
            userRoleList = new ArrayList<String>();
            for (String aRole : userRoles) {
                userRoleList.add(aRole.toLowerCase());
            }
        }

        //Iterate the requested scopes list.
        for (String scope : requestedScopes) {
            //Get the set of roles associated with the requested scope.
            String roles = appScopes.get(scope);
            //If the scope has been defined in the context of the App and if roles have been defined for the scope
            if (roles != null && roles.length() != 0) {
                List<String> roleList = new ArrayList<String>();
                for (String aRole : roles.split(",")) {
                    if (preservedCaseSensitive) {
                        roleList.add(aRole.trim());
                    } else {
                        roleList.add(aRole.trim().toLowerCase());
                    }
                }
                //Check if user has at least one of the roles associated with the scope
                roleList.retainAll(userRoleList);
                if (!roleList.isEmpty()) {
                    authorizedScopes.add(scope);
                }
            }
            // The requested scope is defined for the context of the App but no roles have been associated with the
            // scope
            // OR
            // The scope string starts with 'device_'.
            else if (appScopes.containsKey(scope) || isWhiteListedScope(whiteListedScopes, scope)) {
                authorizedScopes.add(scope);
            }
        }
        if (!authorizedScopes.isEmpty()) {
            return authorizedScopes;
        } else {
            return defaultScope;
        }
    } catch (APIManagementException e) {
        log.error("Error while getting scopes of application " + e.getMessage(), e);
        return null;
    }
}

From source file:specminers.evaluation.MopExtractor.java

private List<String> convertEventsToMethodSignatures(List<String> forbidden) throws ParseException {
    if (this.correspondingMethodSignaturesOfEvents == null) {
        this.correspondingMethodSignaturesOfEvents = new HashMap<>();

        Map<String, EventDefinitionExt> evs;
        evs = getJavaMopSpec().getEvents().stream().collect(Collectors.toMap(ev -> ev.getId(), ev -> ev));

        for (String ev : evs.keySet()) {
            if (!this.correspondingMethodSignaturesOfEvents.containsKey(ev)) {
                this.correspondingMethodSignaturesOfEvents.put(ev, new LinkedList<>());
            }//from w  ww.j a  va 2s.  c  o m

            this.correspondingMethodSignaturesOfEvents.get(ev)
                    .addAll(getCorrespondingMethodSignatureSequences(evs.get(ev)));
        }
    }

    List<String> expandedForbiddenSequence;
    expandedForbiddenSequence = new LinkedList<>();

    Predicate<String> packageSigFilter = sig -> sig.startsWith("java.util") || sig.startsWith("java.net");

    for (String seq : forbidden) {
        String[] forbEvents = seq.split("\\s");
        List<String> joinedList = this.correspondingMethodSignaturesOfEvents.get(forbEvents[0]);
        List<String> cartesianProduct = new LinkedList<>();
        joinedList.retainAll(joinedList.stream().filter(packageSigFilter).collect(Collectors.toSet()));

        for (int i = 1; i < forbEvents.length; i++) {
            List<String> currentList = this.correspondingMethodSignaturesOfEvents.get(forbEvents[i]);
            currentList.retainAll(currentList.stream().filter(packageSigFilter).collect(Collectors.toSet()));
            makeListsCartesianProduct(joinedList, currentList, cartesianProduct);
        }

        expandedForbiddenSequence.addAll(cartesianProduct);
    }

    return expandedForbiddenSequence;

}

From source file:org.finra.herd.service.impl.BusinessObjectDataStorageFileServiceImpl.java

/**
 * Validates a list of storage files to be added to the specified storage unit.
 *
 * @param storageFiles the list of storage files
 * @param storageUnitEntity the storage unit entity
 * @param validatePathPrefix the validate path prefix flag
 * @param validateFileExistence the validate file existence flag
 * @param validateFileSize the validate file size flag
 *///w w w  . j ava2s  . co m
private void validateStorageFiles(List<StorageFile> storageFiles, StorageUnitEntity storageUnitEntity,
        boolean validatePathPrefix, boolean validateFileExistence, boolean validateFileSize) {
    // Retrieve all storage files already registered for this storage unit loaded in a map for easy access.
    Map<String, StorageFileEntity> storageFileEntities = storageFileHelper
            .getStorageFileEntitiesMap(storageUnitEntity.getStorageFiles());

    // Perform validation of storage files listed in the request per storage directory path and/or validation flags.
    String directoryPath = null;
    String directoryPathWithTrailingSlash = null;
    if (StringUtils.isNotBlank(storageUnitEntity.getDirectoryPath())) {
        // Use the storage directory path from the storage unit.
        directoryPath = storageUnitEntity.getDirectoryPath();

        // Add a trailing slash to the storage directory path if it doesn't already have it.
        directoryPathWithTrailingSlash = StringUtils.appendIfMissing(directoryPath, "/");

        // If a storage directory path exists, then validate that all files being added are contained within that directory.
        for (StorageFile storageFile : storageFiles) {
            Assert.isTrue(storageFile.getFilePath().startsWith(directoryPathWithTrailingSlash),
                    String.format("Storage file path \"%s\" does not match the storage directory path \"%s\".",
                            storageFile.getFilePath(), directoryPathWithTrailingSlash));
        }
    } else if (validatePathPrefix || validateFileExistence) {
        // Use the expected S3 key prefix value as the storage directory path.
        directoryPath = s3KeyPrefixHelper.buildS3KeyPrefix(storageUnitEntity.getStorage(),
                storageUnitEntity.getBusinessObjectData().getBusinessObjectFormat(),
                businessObjectDataHelper.getBusinessObjectDataKey(storageUnitEntity.getBusinessObjectData()));

        // Add a trailing slash to the expected S3 key prefix if it doesn't already have it.
        directoryPathWithTrailingSlash = StringUtils.appendIfMissing(directoryPath, "/");

        // Validate that all files are contained within the expected S3 key prefix.
        for (StorageFile storageFile : storageFiles) {
            Assert.isTrue(storageFile.getFilePath().startsWith(directoryPathWithTrailingSlash), String.format(
                    "Specified storage file path \"%s\" does not match the expected S3 key prefix \"%s\".",
                    storageFile.getFilePath(), directoryPathWithTrailingSlash));
        }
    }

    // Validate that files in the request does not already exist in the database.
    if (StringUtils.isNotBlank(directoryPath)) {
        // Get a list of request storage file paths.
        List<String> requestStorageFilePaths = storageFileHelper.getFilePathsFromStorageFiles(storageFiles);

        // Retrieve all already registered storage files from the storage that start with the directory path.
        List<String> registeredStorageFilePaths = storageFileDao.getStorageFilesByStorageAndFilePathPrefix(
                storageUnitEntity.getStorage().getName(), directoryPathWithTrailingSlash);

        // Check if request contains any of the already registered files.
        registeredStorageFilePaths.retainAll(requestStorageFilePaths);
        if (!CollectionUtils.isEmpty(registeredStorageFilePaths)) {
            // Retrieve the storage file entity for the first "already registered" storage file.
            // Since the discovered storage file path exists in the database, we should not get a null back.
            StorageFileEntity storageFileEntity = storageFileDao.getStorageFileByStorageNameAndFilePath(
                    storageUnitEntity.getStorage().getName(), registeredStorageFilePaths.get(0));

            // Throw an exception reporting the information on the "already registered" storage file.
            throw new AlreadyExistsException(String.format(
                    "S3 file \"%s\" in \"%s\" storage is already registered by the business object data {%s}.",
                    registeredStorageFilePaths.get(0), storageUnitEntity.getStorage().getName(),
                    businessObjectDataHelper.businessObjectDataEntityAltKeyToString(
                            storageFileEntity.getStorageUnit().getBusinessObjectData())));
        }
    } else {
        // Since directory path is not available, we need to validate each storage file specified in the request individually.
        for (StorageFile storageFile : storageFiles) {
            // Ensure that the file is not already registered in this storage by some other business object data.
            StorageFileEntity storageFileEntity = storageFileDao.getStorageFileByStorageNameAndFilePath(
                    storageUnitEntity.getStorage().getName(), storageFile.getFilePath());
            if (storageFileEntity != null) {
                throw new AlreadyExistsException(String.format(
                        "S3 file \"%s\" in \"%s\" storage is already registered by the business object data {%s}.",
                        storageFile.getFilePath(), storageUnitEntity.getStorage().getName(),
                        businessObjectDataHelper.businessObjectDataEntityAltKeyToString(
                                storageFileEntity.getStorageUnit().getBusinessObjectData())));
            }
        }
    }

    // Validate file existence.
    if (validateFileExistence) {
        // Get S3 bucket access parameters and set the key prefix to the directory path with a trailing slash.
        // Please note that since we got here, the directory path can not be empty.
        S3FileTransferRequestParamsDto params = storageHelper
                .getS3BucketAccessParams(storageUnitEntity.getStorage());
        params.setS3KeyPrefix(directoryPathWithTrailingSlash);

        // When listing S3 files, we ignore 0 byte objects that represent S3 directories.
        Map<String, StorageFile> actualS3Keys = storageFileHelper
                .getStorageFilesMapFromS3ObjectSummaries(s3Service.listDirectory(params, true));

        // For the already registered storage files, validate each storage file against S3 keys and metadata reported by S3.
        for (Map.Entry<String, StorageFileEntity> entry : storageFileEntities.entrySet()) {
            storageFileHelper.validateStorageFileEntity(entry.getValue(), params.getS3BucketName(),
                    actualS3Keys, validateFileSize);
        }

        // Validate each storage file listed in the request.
        for (StorageFile storageFile : storageFiles) {
            storageFileHelper.validateStorageFile(storageFile, params.getS3BucketName(), actualS3Keys,
                    validateFileSize);
        }
    }
}

From source file:org.opendaylight.vpnservice.dhcpservice.DhcpExternalTunnelManager.java

/**
 * Choose a dpn among the list of elanDpns such that it has lowest count of being the designated dpn.
 * @param tunnelIp/*from  w w  w . ja  v  a2  s  .  c om*/
 * @param elanInstanceName
 * @param dpns
 * @return
 */
private BigInteger chooseDpn(IpAddress tunnelIp, String elanInstanceName, List<BigInteger> dpns) {
    BigInteger designatedDpnId = DHCPMConstants.INVALID_DPID;
    if (dpns != null && dpns.size() != 0) {
        List<BigInteger> candidateDpns = DhcpServiceUtils.getDpnsForElan(elanInstanceName, broker);
        candidateDpns.retainAll(dpns);
        logger.trace("Choosing new dpn for tunnelIp {}, elanInstanceName {}, among elanDpns {}", tunnelIp,
                elanInstanceName, candidateDpns);
        boolean elanDpnAvailableFlag = true;
        if (candidateDpns == null || candidateDpns.isEmpty()) {
            candidateDpns = dpns;
            elanDpnAvailableFlag = false;
        }
        int size = 0;
        L2GatewayDevice device = getDeviceFromTunnelIp(elanInstanceName, tunnelIp);
        if (device == null) {
            logger.trace("Could not find any device for elanInstanceName {} and tunnelIp {}", elanInstanceName,
                    tunnelIp);
            handleUnableToDesignateDpn(tunnelIp, elanInstanceName);
            return designatedDpnId;
        }
        for (BigInteger dpn : candidateDpns) {
            String hwvtepNodeId = device.getHwvtepNodeId();
            if (!elanDpnAvailableFlag) {
                if (!isTunnelConfigured(dpn, hwvtepNodeId)) {
                    logger.trace("Tunnel is not configured on dpn {} to TOR {}", dpn, hwvtepNodeId);
                    continue;
                }
            } else if (!isTunnelUp(hwvtepNodeId, dpn)) {
                logger.trace("Tunnel is not up between dpn {} and TOR {}", dpn, hwvtepNodeId);
                continue;
            }
            List<Pair<IpAddress, String>> tunnelIpElanNameList = designatedDpnsToTunnelIpElanNameCache.get(dpn);
            if (tunnelIpElanNameList == null) {
                designatedDpnId = dpn;
                break;
            }
            if (size == 0 || tunnelIpElanNameList.size() < size) {
                size = tunnelIpElanNameList.size();
                designatedDpnId = dpn;
            }
        }
        writeDesignatedSwitchForExternalTunnel(designatedDpnId, tunnelIp, elanInstanceName);
        return designatedDpnId;
    }
    handleUnableToDesignateDpn(tunnelIp, elanInstanceName);
    return designatedDpnId;
}

From source file:uk.ac.cam.caret.sakai.rwiki.component.service.impl.SiteEmailNotificationRWiki.java

/**
 * @inheritDoc/*w w  w  .  ja v  a 2  s  .  c o  m*/
 */
protected List getRecipients(Event event) {
    // get the resource reference
    Reference ref = entityManager.newReference(event.getResource());

    // use either the configured site, or if not configured, the site
    // (context) of the resource
    String siteId = getSite();

    if (siteId == null) {
        siteId = getSiteId(ref.getContext());
    }

    // if the site is published, use the list of users who can SITE_VISIT
    // the site,
    // else use the list of users who can SITE_VISIT_UNP the site.
    try {
        Site site = siteService.getSite(siteId);
        String ability = SiteService.SITE_VISIT;
        if (!site.isPublished()) {
            ability = SiteService.SITE_VISIT_UNPUBLISHED;
        }

        // get the list of users who can do the right kind of visit
        List users = securityService.unlockUsers(ability, ref.getReference());

        // get the list of users who have the appropriate access to the
        // resource
        if (getResourceAbility() != null) {
            List users2 = securityService.unlockUsers(getResourceAbility(), ref.getReference());

            // find intersection of users and user2
            users.retainAll(users2);
        }

        // add any other users
        addSpecialRecipients(users, ref);

        return users;
    } catch (Exception any) {
        log.error("Exception in getRecipients()", any); //$NON-NLS-1$
        return new Vector();
    }
}