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:au.org.ala.delta.intkey.directives.BracketedTaxonListArgument.java

@Override
public Pair<List<Item>, Boolean> parseInput(Queue<String> inputTokens, IntkeyContext context,
        String directiveName, StringBuilder stringRepresentationBuilder) throws IntkeyDirectiveParseException {
    List<String> selectedKeywordsOrTaxonNumbers = new ArrayList<String>();

    boolean overrideExcludedTaxa = false;
    boolean inBrackets = false;

    String token = inputTokens.poll();
    if (token != null && token.equalsIgnoreCase(OVERRIDE_EXCLUDED_TAXA)) {
        overrideExcludedTaxa = true;/* w w  w  .j a v a2 s.com*/
        token = inputTokens.poll();
    }

    boolean includeSpecimen = false;
    List<Item> taxa = null;

    SelectionMode selectionMode = context.displayKeywords() ? SelectionMode.KEYWORD : SelectionMode.LIST;

    if (token != null) {
        if (token.equalsIgnoreCase(DEFAULT_DIALOG_WILDCARD)) {
            // do nothing - default selection mode is already set above.
        } else if (token.equalsIgnoreCase(KEYWORD_DIALOG_WILDCARD)) {
            selectionMode = SelectionMode.KEYWORD;
        } else if (token.equalsIgnoreCase(LIST_DIALOG_WILDCARD)) {
            selectionMode = SelectionMode.LIST;
        } else if (token.equalsIgnoreCase(LIST_DIALOG_AUTO_SELECT_SOLE_ITEM_WILDCARD)) {
            selectionMode = SelectionMode.LIST_AUTOSELECT_SINGLE_VALUE;
        } else {
            taxa = new ArrayList<Item>();

            if (token.equals(OPEN_BRACKET)) {
                inBrackets = true;
                token = inputTokens.poll();
            }

            while (token != null) {
                if (token.equals(CLOSE_BRACKET)) {
                    break;
                }

                try {

                    if (token.equalsIgnoreCase(IntkeyContext.SPECIMEN_KEYWORD)) {
                        includeSpecimen = true;
                    } else {
                        taxa.addAll(ParsingUtils.parseTaxonToken(token, context));
                    }

                    selectedKeywordsOrTaxonNumbers.add(token);

                    // If we are expecting a bracketed list, but no brackets
                    // are present,
                    // only parse the first token
                    if (!inBrackets) {
                        break;
                    }

                    token = inputTokens.poll();

                } catch (IllegalArgumentException ex) {
                    throw new IntkeyDirectiveParseException(
                            String.format("Unrecognized taxon keyword %s", token));
                }
            }

            if (!(overrideExcludedTaxa || _selectFromAll)) {
                taxa.retainAll(context.getIncludedTaxa());
            }
        }
    }

    if (taxa == null) {
        inBrackets = true;

        // The specimen is included as an option for these prompts
        MutableBoolean specimenSelected = new MutableBoolean(false);
        List<String> selectedKeywords = new ArrayList<String>();
        boolean includeSpecimenAsOption = !context.getSpecimen().getUsedCharacters().isEmpty();
        DirectivePopulator populator = context.getDirectivePopulator();
        if (selectionMode == SelectionMode.KEYWORD && context.displayKeywords()) {
            taxa = populator.promptForTaxaByKeyword(directiveName, !(overrideExcludedTaxa || _selectFromAll),
                    _noneSelectionPermitted, includeSpecimenAsOption, specimenSelected, selectedKeywords);

        } else {
            boolean autoSelectSingleValue = (selectionMode == SelectionMode.LIST_AUTOSELECT_SINGLE_VALUE);
            taxa = populator.promptForTaxaByList(directiveName, !(overrideExcludedTaxa || _selectFromAll),
                    autoSelectSingleValue, false, includeSpecimenAsOption, specimenSelected, selectedKeywords);
        }

        if (taxa == null) {
            // cancelled
            return null;
        }

        includeSpecimen = specimenSelected.booleanValue();

        // Put selected keywords or taxon numbers into a collection to use
        // to build the string representation.
        if (!selectedKeywords.isEmpty()) {
            for (String selectedKeyword : selectedKeywords) {
                if (selectedKeyword.contains(" ")) {
                    // Enclose any keywords that contain spaces in quotes
                    // for the string representation
                    selectedKeywordsOrTaxonNumbers.add("\"" + selectedKeyword + "\"");
                } else {
                    selectedKeywordsOrTaxonNumbers.add(selectedKeyword);
                }
            }
        } else {
            List<Integer> selectedTaxonNumbers = new ArrayList<Integer>();
            for (int i = 0; i < taxa.size(); i++) {
                Item taxon = taxa.get(i);
                selectedTaxonNumbers.add(taxon.getItemNumber());
            }
            selectedKeywordsOrTaxonNumbers.add(Utils.formatIntegersAsListOfRanges(selectedTaxonNumbers));
        }
    }

    // build the string representation of the directive call
    stringRepresentationBuilder.append(" ");

    if (overrideExcludedTaxa) {
        stringRepresentationBuilder.append(OVERRIDE_EXCLUDED_TAXA);
        stringRepresentationBuilder.append(" ");
    }

    if (inBrackets) {
        stringRepresentationBuilder.append(OPEN_BRACKET);
    }

    stringRepresentationBuilder.append(StringUtils.join(selectedKeywordsOrTaxonNumbers, " "));

    if (inBrackets) {
        stringRepresentationBuilder.append(CLOSE_BRACKET);
    }

    if (taxa.size() == 0 && includeSpecimen == false && !_noneSelectionPermitted) {
        throw new IntkeyDirectiveParseException("NoTaxaInSet.error");
    }

    Collections.sort(taxa);
    return new Pair<List<Item>, Boolean>(taxa, includeSpecimen);
}

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

private static List<Scope> getAllowedScopesForUserApplication(String username, Set<Scope> reqScopeSet) {
    String[] userRoles = null;/*  ww w  . j  a v  a2s  .c  om*/
    org.wso2.carbon.user.api.UserStoreManager userStoreManager = null;

    List<Scope> authorizedScopes = new ArrayList<Scope>();
    try {
        RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                .getTenantId(MultitenantUtils.getTenantDomain(username));
        userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
        userRoles = userStoreManager.getRoleListOfUser(MultitenantUtils.getTenantAwareUsername(username));
    } catch (org.wso2.carbon.user.api.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);
    }

    List<String> userRoleList;
    if (userRoles != null) {
        userRoleList = new ArrayList<String>(Arrays.asList(userRoles));
    } else {
        userRoleList = Collections.emptyList();
    }

    //Iterate the requested scopes list.
    for (Scope scope : reqScopeSet) {
        //Get the set of roles associated with the requested scope.
        String roles = scope.getRoles();

        //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>(
                    Arrays.asList(roles.replaceAll(" ", EMPTY_STRING).split(",")));
            //Check if user has at least one of the roles associated with the scope
            roleList.retainAll(userRoleList);
            if (!roleList.isEmpty()) {
                authorizedScopes.add(scope);
            }
        }
    }

    return authorizedScopes;
}

From source file:org.wso2.carbon.apimgt.core.impl.APIPublisherImpl.java

/**
 * This method retrieves the set of overall permissions for a given api for the logged in user
 *
 * @param loggedInUserName - Logged in user
 * @param api              - The API whose permissions for the logged in user is retrieved
 * @return The overall list of permissions for the given API for the logged in user
 *//*from w w  w  .  j a  va  2  s  . c  o m*/
private List<String> getAPIPermissionsOfLoggedInUser(String loggedInUserName, API api)
        throws APIManagementException {
    Set<String> permissionArrayForUser = new HashSet<>();
    Map<String, Integer> permissionMap = api.getPermissionMap();
    String provider = api.getProvider();
    //TODO: Remove the check for admin after IS adds an ID to admin user
    if (loggedInUserName.equals(provider) || permissionMap == null || permissionMap.isEmpty()
            || "admin".equals(loggedInUserName)) {
        permissionArrayForUser.add(APIMgtConstants.Permission.READ);
        permissionArrayForUser.add(APIMgtConstants.Permission.UPDATE);
        permissionArrayForUser.add(APIMgtConstants.Permission.DELETE);
        permissionArrayForUser.add(APIMgtConstants.Permission.MANAGE_SUBSCRIPTION);
    } else {
        try {
            String userId = getIdentityProvider().getIdOfUser(loggedInUserName);
            List<String> loggedInUserRoles = getIdentityProvider().getRoleIdsOfUser(userId);
            List<String> permissionRoleList = getRolesFromPermissionMap(permissionMap);
            List<String> rolesOfUserWithAPIPermissions = null;
            //To prevent a possible null pointer exception
            if (loggedInUserRoles == null) {
                loggedInUserRoles = new ArrayList<>();
            }
            //get the intersection - retainAll() transforms first set to the result of intersection
            loggedInUserRoles.retainAll(permissionRoleList);
            if (!loggedInUserRoles.isEmpty()) {
                rolesOfUserWithAPIPermissions = loggedInUserRoles;
            }
            if (rolesOfUserWithAPIPermissions != null) {
                Integer aggregatePermissions = 0;
                //Calculating aggregate permissions using Bitwise OR operation
                for (String role : rolesOfUserWithAPIPermissions) {
                    aggregatePermissions |= permissionMap.get(role);
                }
                permissionArrayForUser = new HashSet<>(
                        APIUtils.constructApiPermissionsListForValue(aggregatePermissions));
            }
        } catch (IdentityProviderException e) {
            String errorMsg = "Error occurred while calling SCIM endpoint to retrieve user " + loggedInUserName
                    + "'s information";
            log.error(errorMsg, e);
            throw new APIManagementException(errorMsg, e, e.getErrorHandler());
        }
    }
    List<String> finalAggregatedPermissionList = new ArrayList<>();
    finalAggregatedPermissionList.addAll(permissionArrayForUser);
    if (log.isDebugEnabled()) {
        String message = "Aggregate permissions of user " + loggedInUserName + " for the API " + api.getName()
                + " are " + StringUtils.join(finalAggregatedPermissionList, ", ") + ".";
        log.debug(message);
    }
    return finalAggregatedPermissionList;
}

From source file:org.opencms.workplace.tools.content.CmsElementRename.java

/**
 * Returns a retained list of xml pages that belongs to the specified template.<p>
 * /*from  w  w w .j  av a  2  s.  c o  m*/
 * @param xmlPages a list of all xml pages 
 * @return a retained list of xml pages that belongs to the specified template
 */
private List getRetainedPagesWithTemplate(List xmlPages) {

    // list of resources belongs to the selected template
    List resourcesWithTemplate = new ArrayList();
    TreeMap templates = null;
    try {
        templates = CmsNewResourceXmlPage.getTemplates(getCms(), null);
    } catch (CmsException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
    // check if the users selected template is valid. 
    if ((templates != null) && templates.containsValue(getParamTemplate())) {
        // iterate the xmlPages list and add all resources with the specified template to the resourcesWithTemplate list
        Iterator i = xmlPages.iterator();
        while (i.hasNext()) {
            CmsResource currentPage = (CmsResource) i.next();
            // read the template property
            CmsProperty templateProperty;
            try {
                templateProperty = getCms().readPropertyObject(getCms().getSitePath(currentPage),
                        CmsPropertyDefinition.PROPERTY_TEMPLATE, false);
            } catch (CmsException e2) {
                if (LOG.isErrorEnabled()) {
                    LOG.error(e2);
                }
                continue;
            }
            // add currentResource if the template property value is the same as the given template
            if (getParamTemplate().equals(templateProperty.getValue())) {
                resourcesWithTemplate.add(currentPage);
            }
        }
        // retain the list of pages against the list with template 
        xmlPages.retainAll(resourcesWithTemplate);
    }

    return xmlPages;
}

From source file:org.egov.works.web.actions.estimate.SearchEstimateAction.java

public List<String> getEstimateActions() {
    final List<Role> copyEstActionRoles = new ArrayList<Role>();
    boolean allowCopyEst = false;
    String copyEstActionName;//w  ww . jav  a 2  s  .  c om

    final List<String> actionList = new ArrayList<String>();
    actionList.add(0, WorksConstants.ACTION_VIEW);
    actionList.add(1, WorksConstants.ACTION_VIEW_PDF);
    actionList.add(2, WorksConstants.ACTION_WF_HISTORY);
    actionList.add(3, WorksConstants.ACTION_VIEW_DOCUMENT);
    actionList.add(4, WorksConstants.ACTION_COPY_ESTIMATE);

    if (actionList != null && !actionList.isEmpty()) {
        copyEstActionName = actionList.get(actionList.size() - 1);

        // get the roles for the Copy Estimate action
        final org.egov.infra.admin.master.entity.Action copyEstimateAction = actionService
                .getActionByName(copyEstActionName);
        if (copyEstimateAction != null)
            copyEstActionRoles.addAll(copyEstimateAction.getRoles());

        // check if the userroles contains the copy estimate action roles
        for (final Role copyEstrole : copyEstActionRoles)
            if (roles.contains(copyEstrole)) {
                allowCopyEst = true;
                break;
            }

        // To remove the last element(ie.Copy Estimate) from action list
        if (!allowCopyEst) {
            final List<String> tempActionList = new ArrayList<String>();
            for (final String action : actionList)
                if (!action.equals(copyEstActionName))
                    tempActionList.add(action);
            actionList.retainAll(tempActionList);
        }
    }

    return actionList;
}

From source file:com.gargoylesoftware.htmlunit.general.ElementPropertiesTest.java

private void testString(final String string) throws Exception {
    final String html = HtmlPageTest.STANDARDS_MODE_PREFIX_ + "<html><head><script>\n"
            + "  var ieMethods = ['abort', 'add', 'addBehavior', 'AddChannel', 'AddDesktopComponent', "
            + "'addElement', 'AddFavorite', 'addFilter', 'addImport', 'AddInPrivateSubscription', 'addPageRule', "
            + "'addReadRequest', 'addRule', 'AddSearchProvider', 'AddService', 'AddToFavoritesBar', 'alert', "
            + "'appendChild', 'appendData', 'applyElement', 'assign', 'attachEvent', 'AutoCompleteSaveForm', "
            + "'AutoScan', 'back', 'blur', 'bubbleEvent', 'ChooseColorDlg', 'clear', 'clearAttributes', "
            + "'clearData', 'clearInterval', 'clearRequest', 'clearTimeout', 'click', 'cloneNode', 'close', "
            + "'collapse', 'compareEndPoints', 'componentFromPoint', 'confirm', 'contains', "
            + "'ContentDiscoveryReset', 'createAttribute', 'createCaption', 'createComment', "
            + "'createControlRange', 'createDocumentFragment', 'createElement', 'createEventObject', "
            + "'createPopup', 'createRange', 'createRangeCollection', 'createStyleSheet', 'createTextNode', "
            + "'createTextRange', 'createTFoot', 'createTHead', 'deleteCaption', 'deleteCell', 'deleteData', "
            + "'deleteRow', 'deleteTFoot', 'deleteTHead', 'detachEvent', 'doImport', 'doReadRequest', 'doScroll', "
            + "'dragDrop', 'duplicate', 'elementFromPoint', 'empty', 'execCommand', 'execScript', 'expand', "
            + "'findText', 'fireEvent', 'firstPage', 'focus', 'forward', 'getAdjacentText', "
            + "'getAllResponseHeaders', 'getAttribute', 'getAttributeNode', 'getBookmark', "
            + "'getBoundingClientRect', 'getCharset', 'getClientRects', 'getData', 'getElementById', "
            + "'getElementsByName', 'getElementsByTagName', 'getExpression', 'getItem', 'getNamedItem', "
            + "'getResponseHeader', 'go', 'hasAttribute', 'hasChildNodes', 'hasFeature', 'hasFocus', 'hide', "
            + "'ImportExportFavorites', 'inRange', 'insertAdjacentElement', 'insertAdjacentHTML', "
            + "'insertAdjacentText', 'insertBefore', 'insertCell', 'insertData', 'insertRow', 'isEqual', "
            + "'IsSearchProviderInstalled', 'IsServiceInstalled', 'IsSubscribed', 'item', 'Item', 'javaEnabled', "
            + "'key', 'lastPage', 'mergeAttributes', 'move', 'moveBy', 'moveEnd', 'moveRow', 'moveStart', "
            + "'moveTo', 'moveToBookmark', 'moveToElementText', 'moveToPoint', 'namedItem', 'namedRecordset', "
            + "'navigate', 'NavigateAndFind', 'nextPage', 'normalize', 'open', 'parentElement', 'pasteHTML', "
            + "'postMessage', 'previousPage', 'print', 'prompt', 'queryCommandEnabled', 'queryCommandIndeterm', "
            + "'queryCommandState', 'queryCommandSupported', 'queryCommandValue', 'querySelector', "
            + "'querySelectorAll', 'raiseEvent', 'recalc', 'refresh', 'releaseCapture', 'reload', 'remove', "
            + "'removeAttribute', 'removeAttributeNode', 'removeBehavior', 'removeChild', 'removeExpression', "
            + "'removeImport', 'removeItem', 'removeNamedItem', 'removeNode', 'removeRule', 'replace', "
            + "'replaceAdjacentText', 'replaceChild', 'replaceData', 'replaceNode', 'reset', 'resizeBy', "
            + "'resizeTo', 'scroll', 'scrollBy', 'scrollIntoView', 'scrollTo', 'select', 'send', 'setActive', "
            + "'setAttribute', 'setAttributeNode', 'setCapture', 'setContextMenu', 'setData', 'setEndPoint', "
            + "'setExpression', 'setInterval', 'setItem', 'setNamedItem', 'setRequestHeader', 'setTimeout', "
            + "'show', 'ShowBrowserUI', 'showHelp', 'showModalDialog', 'showModelessDialog', 'splitText', "
            + "'start', 'stop', 'submit', 'substringData', 'swapNode', 'tags', 'taintEnabled', 'toStaticHTML', "
            + "'updateSettings', 'urns', 'write', 'writeln'];\n"

            + "  function test(event) {\n" + "    var xmlDocument = createXmlDocument();\n"
            + "    var element = xmlDocument.createElement('wakwak');\n"
            + "    var unknown = document.createElement('harhar');\n"
            + "    var div = document.createElement('div');\n" + "    process(" + string + ");\n" + "  }\n"
            + "\n" + "  /*\n" + "   * Alerts all properties (including functions) of the specified object.\n"
            + "   *\n" + "   * @param object the object to write the property of\n"
            + "   * @param parent the direct parent of the object (or child of that parent), can be null.\n"
            + "   *        The parent is used to exclude any inherited properties.\n" + "   */\n"
            + "  function process(object, parent) {\n" + "    var all = [];\n"
            + "    for (var property in object) {\n" + "      try {\n"
            + "        if (parent == null || !(property in parent)) {\n"
            + "          if (typeof object[property] == 'function')\n"
            + "            all.push(property + '()');\n" + "          else\n"
            + "            all.push(property);\n" + "        }\n" + "      } catch(e) {\n" + "        try{\n"
            + "          if (typeof object[property] == 'function')\n"
            + "            all.push(property + '()');\n" + "          else\n"
            + "            all.push(property);\n" + "        } catch (e) {\n"
            + "          all.push(property.toString());\n" + "        }\n" + "      }\n" + "    }\n"
            + "    if (document.all) {\n" + "      for (var index in ieMethods) {\n"
            + "        var method = ieMethods[index];\n" + "        try {\n"
            + "          if (object[method] !== undefined && (parent == null || parent[method] === undefined)) {\n"
            + "            all.push(method + '()');\n" + "          }\n" + "        } catch(e) {\n"
            + "           all.push(method + '()');\n" + "        }\n" + "      }\n" + "    }\n"
            + "    all.sort(sortFunction);\n" + "    alert(all);\n" + "  }\n"
            + "  function sortFunction(s1, s2) {\n"
            + "    return s1.toLowerCase() > s2.toLowerCase() ? 1 : -1;\n" + "  }\n"
            + "  function createXmlDocument() {\n"
            + "    if (document.implementation && document.implementation.createDocument)\n"
            + "      return document.implementation.createDocument('', '', null);\n"
            + "    else if (window.ActiveXObject)\n" + "      return new ActiveXObject('Microsoft.XMLDOM');\n"
            + "  }\n" + "</script></head><body onload='test(event)'>\n" + "</body></html>";

    if (BROWSER_VERSION_ == null) {
        BROWSER_VERSION_ = getBrowserVersion();
    }//  w  w w. jav  a  2s . c o m
    final String expected = getExpectedAlerts().length == 0 ? "" : getExpectedAlerts()[0];
    String actual;

    ComparisonFailure failure = null;
    try {
        loadPageWithAlerts2(html);
        actual = expected;
    } catch (final ComparisonFailure c) {
        failure = c;
        actual = c.getActual();
        actual = actual.substring(1, actual.length() - 1);
    }

    final List<String> realProperties = stringAsArray(expected);
    final List<String> simulatedProperties = stringAsArray(actual);

    final List<String> erroredProperties = new ArrayList<>(simulatedProperties);
    erroredProperties.removeAll(realProperties);

    final List<String> implementedProperties = new ArrayList<>(simulatedProperties);
    implementedProperties.retainAll(realProperties);

    IMPLEMENTED_COUNT_ += implementedProperties.size();
    TOTAL_COUNT_ += realProperties.size();

    String methodName = null;
    for (final StackTraceElement e : new Exception().getStackTrace()) {
        if (e.getClassName().equals(getClass().getName())) {
            methodName = e.getMethodName();
        } else {
            break;
        }
    }

    htmlDetails(methodName, HTML_, realProperties, implementedProperties, erroredProperties);

    DATASET_.addValue(implementedProperties.size(), "Implemented", methodName);
    DATASET_.addValue(realProperties.size(),
            getBrowserVersion().getNickname().replace("FF", "Firefox ").replace("IE", "Internet Explorer "),
            methodName);
    DATASET_.addValue(erroredProperties.size(), "Should not be implemented", methodName);

    if (failure != null) {
        throw failure;
    }
}

From source file:org.sakaiproject.nakamura.files.pool.ManageMembersContentPoolServlet.java

/**
 * Manipulate the member list for this file.
 *
 * {@inheritDoc}/*from   w  w  w  .  j  a v a 2s . c  o m*/
 *
 * @see org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest,
 *      org.apache.sling.api.SlingHttpServletResponse)
 */
@SuppressWarnings("unchecked")
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    // fail if anonymous
    String remoteUser = request.getRemoteUser();
    if (User.ANON_USER.equals(remoteUser)) {
        response.sendError(SC_FORBIDDEN, "Anonymous users cannot update content members.");
        return;
    }
    Session session = null;
    boolean releaseSession = false;
    try {
        Resource resource = request.getResource();
        session = resource.adaptTo(Session.class);
        Content pooledContent = resource.adaptTo(Content.class);
        AccessControlManager accessControlManager = session.getAccessControlManager();
        AuthorizableManager authorizableManager = session.getAuthorizableManager();
        User thisUser = authorizableManager.getUser();
        if (!accessControlManager.can(thisUser, Security.ZONE_CONTENT, pooledContent.getPath(),
                Permissions.CAN_READ)) {
            response.sendError(SC_FORBIDDEN, "Insufficient permission to read this content.");
        }

        Map<String, Object> properties = pooledContent.getProperties();
        String[] managers = StorageClientUtils
                .nonNullStringArray((String[]) properties.get(POOLED_CONTENT_USER_MANAGER));
        String[] editors = StorageClientUtils
                .nonNullStringArray((String[]) properties.get(POOLED_CONTENT_USER_EDITOR));
        String[] viewers = StorageClientUtils
                .nonNullStringArray((String[]) properties.get(POOLED_CONTENT_USER_VIEWER));

        Set<String> managerSet = Sets.newHashSet(managers);
        Set<String> editorSet = Sets.newHashSet(editors);
        Set<String> viewerSet = Sets.newHashSet(viewers);

        List<String> removeViewers = Arrays
                .asList(StorageClientUtils.nonNullStringArray(request.getParameterValues(":viewer@Delete")));
        List<String> removeManagers = Arrays
                .asList(StorageClientUtils.nonNullStringArray(request.getParameterValues(":manager@Delete")));
        List<String> removeEditors = Arrays
                .asList(StorageClientUtils.nonNullStringArray(request.getParameterValues(":editor@Delete")));
        List<String> addViewers = Arrays
                .asList(StorageClientUtils.nonNullStringArray(request.getParameterValues(":viewer")));
        List<String> addManagers = Arrays
                .asList(StorageClientUtils.nonNullStringArray(request.getParameterValues(":manager")));
        List<String> addEditors = Arrays
                .asList(StorageClientUtils.nonNullStringArray(request.getParameterValues(":editor")));

        // get rid of blank values and trim non-blank values
        removeViewers = sanitizeUsernames(removeViewers);
        removeManagers = sanitizeUsernames(removeManagers);
        removeEditors = sanitizeUsernames(removeEditors);
        addViewers = sanitizeUsernames(addViewers);
        addManagers = sanitizeUsernames(addManagers);
        addEditors = sanitizeUsernames(addEditors);

        /*
         * limit the add and remove lists to only those operations that should be performed:
         * 
         * 1. If you have both an add and a remove operation, the remove takes precedence
         * 2. If you add a user to a role to which they are already in, no operation is performed
         * 3. If you remove a user from a role to which they don't belong, no operation is performed
         */

        // 1.
        addManagers.removeAll(removeManagers);
        addEditors.removeAll(removeEditors);
        addViewers.removeAll(removeViewers);

        // 2.
        addManagers.removeAll(managerSet);
        addEditors.removeAll(editorSet);
        addEditors.removeAll(managerSet);
        addViewers.removeAll(viewerSet);
        addViewers.removeAll(editorSet);
        addViewers.removeAll(managerSet);

        // 3.
        removeManagers.retainAll(managerSet);
        removeEditors.retainAll(editorSet);
        removeViewers.retainAll(viewerSet);

        // don't continue any further if there are no relevant operations to perform
        if (addManagers.isEmpty() && removeManagers.isEmpty() && addEditors.isEmpty() && removeEditors.isEmpty()
                && addViewers.isEmpty() && removeViewers.isEmpty()) {
            response.setStatus(SC_OK);
            return;
        }

        //Checking for non-managers
        if (!accessControlManager.can(thisUser, Security.ZONE_CONTENT, pooledContent.getPath(),
                Permissions.CAN_WRITE)) {
            if (!addManagers.isEmpty()) {
                response.sendError(SC_FORBIDDEN, "Non-managers may not add managers to content.");
                return;
            }

            for (String name : removeManagers) {
                // asking to remove managers who don't exist is harmless
                if (managerSet.contains(name)) {
                    response.sendError(SC_FORBIDDEN, "Non-managers may not remove managers from content.");
                    return;
                }
            }

            if (addViewers.contains(User.ANON_USER) || addViewers.contains(Group.EVERYONE)) {
                response.sendError(SC_FORBIDDEN,
                        "Non-managers may not add 'anonymous' or 'everyone' as viewers.");
                return;
            }

            if (addEditors.contains(User.ANON_USER) || addEditors.contains(Group.EVERYONE)) {
                response.sendError(SC_FORBIDDEN,
                        "Non-managers may not add 'anonymous' or 'everyone' as editors.");
                return;
            }

            for (String name : removeViewers) {
                if (!thisUser.getId().equals(name)) {
                    Authorizable viewer = authorizableManager.findAuthorizable(name);
                    if (viewer != null && !accessControlManager.can(thisUser, Security.ZONE_AUTHORIZABLES, name,
                            Permissions.CAN_WRITE)) {
                        response.sendError(SC_FORBIDDEN,
                                "Non-managers may not remove any viewer other than themselves or a group which they manage.");
                        return;
                    }
                }
            }

            // the request has passed all the rules that govern non-manager users
            // so we'll grant an administrative session
            session = session.getRepository().loginAdministrative();
            releaseSession = true;
        }
        List<AclModification> aclModifications = Lists.newArrayList();

        // apply the removals before the adds, because the permission grants should take
        // precedence
        for (String removeManager : removeManagers) {
            AclModification.removeAcl(true, Permissions.CAN_MANAGE, removeManager, aclModifications);
        }

        for (String removeEditor : removeEditors) {
            AclModification.removeAcl(true, PERMISSION_EDITOR, removeEditor, aclModifications);
        }

        for (String removeViewer : removeViewers) {
            AclModification.removeAcl(true, Permissions.CAN_READ, removeViewer, aclModifications);
        }

        for (String addManager : addManagers) {
            AclModification.addAcl(true, Permissions.CAN_MANAGE, addManager, aclModifications);
        }

        for (String addEditor : addEditors) {
            AclModification.addAcl(true, PERMISSION_EDITOR, addEditor, aclModifications);
        }

        for (String addViewer : addViewers) {
            AclModification.addAcl(true, Permissions.CAN_READ, addViewer, aclModifications);
        }

        // apply the operations to the final set of content roles
        managerSet.removeAll(removeManagers);
        managerSet.addAll(addManagers);
        editorSet.removeAll(removeEditors);
        editorSet.addAll(addEditors);
        viewerSet.removeAll(removeViewers);
        viewerSet.addAll(addViewers);

        updateContentMembers(session, pooledContent, viewerSet, managerSet, editorSet);
        updateContentAccess(session, pooledContent, aclModifications);

        this.authorizableCountChanger.notify(UserConstants.CONTENT_ITEMS_PROP, addViewers, addEditors,
                addManagers, removeViewers, removeEditors, removeManagers);

        response.setStatus(SC_OK);

    } catch (StorageClientException e) {
        LOGGER.error(e.getMessage());
        response.sendError(SC_INTERNAL_SERVER_ERROR, "StorageClientException: " + e.getLocalizedMessage());
    } catch (AccessDeniedException e) {
        response.sendError(SC_FORBIDDEN,
                "Insufficient permission to update content members at " + request.getRequestURI());
    } finally {
        if (session != null && releaseSession) {
            try {
                session.logout();
            } catch (ClientPoolException e) {
                LOGGER.error(e.getMessage());
            }
        }
    }
}

From source file:com.smict.person.data.DoctorData.java

public void UpdateMgrBranch(List<BranchModel> branch, int doctor_id) {
    try {//from ww w.j a  v  a 2 s . c o  m
        conn = agent.getConnectMYSql();
        String selectSQL = "SELECT * FROM branch WHERE doctor_id=" + doctor_id;
        pStmt = conn.prepareStatement(selectSQL);
        List<String> rsList = new ArrayList<String>();
        rs = pStmt.executeQuery();
        while (rs.next()) {
            rsList.add(rs.getString("branch_id"));
        }
        List<String> rsList2 = new ArrayList<String>();
        for (BranchModel branchModel : branch) {
            rsList2.add(branchModel.getBranch_id());
        }
        List<String> similar = new ArrayList<String>(rsList);
        List<String> different = new ArrayList<String>();
        different.addAll(rsList);
        different.addAll(rsList2);
        similar.retainAll(rsList2);
        different.removeAll(similar);
        //System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", rsList, rsList2, similar, different);
        for (String branchID : different) {

            String transacSLQ = "UPDATE branch_mgr_history a " + "INNER JOIN "
                    + "(SELECT a.brand_id,b.brand_name,a.branch_id,a.branch_name,a.doctor_id,a.price_doctor,a.addr_id,a.tel_id "
                    + "FROM branch a INNER JOIN brand b ON b.brand_id = a.brand_id ) as b "
                    + "ON b.branch_id = a.branch_id_start " + "SET a.brand_id_end = b.brand_id , "
                    + "a.brand_name_end = b.brand_name , " + "a.branch_id_end = b.branch_id, "
                    + "a.branch_name_end = b.branch_name, " + "a.doctor_id_end = b.doctor_id, "
                    + "a.price_doctor_end = b.price_doctor, " + "a.end_date = NOW() "
                    + "WHERE a.branch_id_start = '" + branchID + "' AND  a.branch_id_end IS NULL ";
            pStmt2 = conn.prepareStatement(transacSLQ);
            pStmt2.executeUpdate();

            String sql = "UPDATE branch set doctor_id=0 WHERE branch_id ='" + branchID + "'";
            pStmt = conn.prepareStatement(sql);
            pStmt.executeUpdate();
        }
        for (String branchID : rsList2) {
            String sql = "UPDATE branch set doctor_id=" + doctor_id + " WHERE branch_id ='" + branchID + "'";
            pStmt = conn.prepareStatement(sql);
            pStmt.executeUpdate();
            String transacSLQ = "INSERT INTO branch_mgr_history "
                    + "(brand_id_start,brand_name_start,branch_id_start,branch_name_start,doctor_id_start,price_doctor_start,start_date) "
                    + "SELECT branch.brand_id,brand.brand_name,branch.branch_id,branch.branch_name,branch.doctor_id,branch.price_doctor,NOW() "
                    + "FROM branch " + "INNER JOIN brand ON brand.brand_id = branch.brand_id "
                    + "WHERE branch.doctor_id = " + doctor_id + " AND branch.branch_id = '" + branchID + "'";
            pStmt2 = conn.prepareStatement(transacSLQ);
            pStmt2.executeUpdate();
        }
        if (!rs.isClosed())
            rs.close();
        if (!Stmt.isClosed())
            Stmt.close();
        if (!pStmt.isClosed())
            pStmt.close();
        if (!pStmt2.isClosed())
            pStmt2.close();
        if (!conn.isClosed())
            conn.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:eu.dasish.annotation.backend.dao.impl.DBDispatcherImlp.java

@Override
public List<Number> getFilteredAnnotationIDs(UUID ownerId, String link, MatchMode matchMode, String text,
        Number inloggedPrincipalID, String accessMode, String namespace, String after, String before)
        throws NotInDataBaseException {

    Number ownerID;/*from w w  w  .ja  va2 s.  c om*/

    if (ownerId != null) {
        if (accessMode.equals("owner")) { // inloggedUser is the owner of the annotations
            if (!ownerId.equals(principalDao.getExternalID(inloggedPrincipalID))) {
                logger.info(
                        "The inlogged principal is demanded to be the owner of the annotations, however the expected owner is different and has the UUID "
                                + ownerId.toString());
                return new ArrayList<Number>();
            } else {
                ownerID = inloggedPrincipalID;
            }
        } else {
            ownerID = principalDao.getInternalID(ownerId);
        }

    } else {
        if (accessMode.equals("owner")) {
            ownerID = inloggedPrincipalID;
        } else {
            ownerID = null;
        }
    }

    //Filtering on the columns  of the annotation table 
    List<Number> annotationIDs = annotationDao.getFilteredAnnotationIDs(ownerID, text, namespace, after,
            before);

    // Filetring on accessMode, the junction table
    if (annotationIDs != null) {
        if (!annotationIDs.isEmpty()) {
            if (!accessMode.equals("owner")) {
                Access access = Access.fromValue(accessMode);
                if (access.equals(Access.NONE)) {
                    List<Number> annotationIDsfiletered = new ArrayList<Number>();
                    Access accessCurrent;
                    for (Number annotationID : annotationIDs) {
                        accessCurrent = annotationDao.getAccess(inloggedPrincipalID, annotationID);
                        if (accessCurrent.equals(Access.NONE)) {
                            annotationIDsfiletered.add(annotationID);
                        }
                    }
                    annotationIDs = annotationIDsfiletered; // yeaahhh I'm relying on garbage collector here                         
                } else {
                    List<Number> annotationIDsAccess = annotationDao
                            .getAnnotationIDsPermissionAtLeast(inloggedPrincipalID, access);
                    List<Number> annotationIDsPublic = annotationDao.getAnnotationIDsPublicAtLeast(access);
                    List<Number> annotationIDsOwned = annotationDao
                            .getFilteredAnnotationIDs(inloggedPrincipalID, text, namespace, after, before);
                    int check1 = this.addAllNoRepetitions(annotationIDsAccess, annotationIDsPublic);
                    int check2 = this.addAllNoRepetitions(annotationIDsAccess, annotationIDsOwned);
                    annotationIDs.retainAll(annotationIDsAccess);// intersection
                }
            }
        }

        // filtering on reference        
        return this.filterAnnotationIDsOnReference(annotationIDs, link, matchMode);
    }

    return annotationIDs;

}

From source file:com.redsqirl.workflow.server.Workflow.java

public List<RunnableElement> subsetToRun(List<String> dataFlowElements) throws Exception {
    logger.debug("subsetToRun " + getName());

    List<DataFlowElement> elementToRun = null;
    List<RunnableElement> toRun = null;

    // Need to check that we have a DAG
    try {/*from  w  w  w. j  a v a 2  s .com*/
        topoligicalSort();
    } catch (Exception e) {
        logger.error(e, e);
        throw new Exception(e);
    }

    elementToRun = subsetElementToRun(dataFlowElements);

    if (elementToRun != null && !elementToRun.isEmpty()) {

        String error = check(elementToRun);
        if (error != null) {
            throw new Exception(error);
        }
        nbOozieRunningActions = elementToRun.size();

        toRun = new ArrayList<RunnableElement>(elementToRun.size());
        Iterator<DataFlowElement> it = elementToRun.iterator();
        Map<String, Boolean> endOfThread = new HashMap<String, Boolean>(elementToRun.size());
        while (it.hasNext()) {
            DataFlowElement cur = it.next();
            logger.debug("Element " + cur.getComponentId());
            //0. Get the thread optimiser if it exists
            //1. Check if it is the end of a thread
            //2. If the optimiser exists
            //2.a. Either add to the new optimiser or write the old optimiser and 2.b
            //2.b  Either create a new optimiser or add the action
            //3. If it is an optimiser and it is the end of a thread, write it.
            DFEOptimiser oldOpt = null;
            DFEOptimiser newOpt = null;

            if (cur.getAllInputComponent().size() == 1) {
                DataFlowElement prev = cur.getAllInputComponent().get(0);
                if (endOfThread.containsKey(prev.getComponentId()) && !endOfThread.get(prev.getComponentId())) {
                    oldOpt = prev.getDFEOptimiser();
                }
            } else if (cur.getAllInputComponent().size() > 1) {
                List<DataFlowElement> prevs = new LinkedList<DataFlowElement>();
                prevs.addAll(cur.getAllInputComponent());
                prevs.retainAll(elementToRun);
                if (prevs.size() == 1) {
                    DataFlowElement prev = prevs.get(0);
                    if (endOfThread.containsKey(prev.getComponentId())
                            && !endOfThread.get(prev.getComponentId())) {
                        oldOpt = prevs.get(0).getDFEOptimiser();
                    }
                }
            }

            boolean stopOptimiser = cur.getDFEOutput().size() > 1 || cur.getAllOutputComponent().size() == 0;
            if (!stopOptimiser) {
                List<DataFlowElement> succs = new LinkedList<DataFlowElement>();
                succs.addAll(cur.getAllOutputComponent());
                succs.retainAll(elementToRun);
                stopOptimiser = succs.size() != 1;
                if (!stopOptimiser) {
                    List<DataFlowElement> descOfSuccs = new LinkedList<DataFlowElement>();
                    descOfSuccs.addAll(succs.get(0).getAllInputComponent());
                    descOfSuccs.retainAll(elementToRun);
                    stopOptimiser = descOfSuccs.size() != 1;
                }
            }

            Iterator<String> itOut = cur.getDFEOutput().keySet().iterator();
            while (itOut.hasNext()) {
                String outName = itOut.next();
                DFEOutput outCur = cur.getDFEOutput().get(outName);
                if (!SavingState.RECORDED.equals(outCur.getSavingState()) && !outCur.isPathExist()) {
                    outCur.generatePath(cur.getComponentId(), outName);
                }
                if (!SavingState.TEMPORARY.equals(outCur.getSavingState())) {
                    stopOptimiser = true;
                }
            }
            logger.debug("Stop Optimiser " + stopOptimiser);
            endOfThread.put(cur.getComponentId(), stopOptimiser);

            newOpt = cur.getDFEOptimiser();
            if (newOpt != null) {
                newOpt.resetElementList();
            }
            if (oldOpt != null && (newOpt == null || !newOpt.addAllElement(oldOpt.getElements()))) {
                logger.debug("Cannot continue optimisation");
                if (oldOpt.getElements().size() > 1) {
                    toRun.add(oldOpt);
                } else {
                    toRun.add(oldOpt.getElements().get(0));
                }
                if (newOpt == null) {
                    logger.debug("Add Individual action");
                    toRun.add(cur);
                } else {
                    newOpt.addElement(cur);
                }
            } else if (oldOpt == null && newOpt != null) {
                logger.debug("Start optimisation");
                newOpt.addElement(cur);
            } else if (oldOpt == null && newOpt == null) {
                logger.debug("Add Individual action");
                toRun.add(cur);
            } else {
                newOpt.addElement(cur);
            }

            if (newOpt != null && stopOptimiser) {
                logger.debug("End of thread");
                if (newOpt.getElements().size() > 1) {
                    toRun.add(newOpt);
                } else {
                    toRun.add(newOpt.getElements().get(0));
                }
            }
        }
    }
    return toRun;
}