/*
Callback establishing group principals within the argument subject. This callback is intended to be called by
a serverAuthModule during its validateRequest processing.
497655
@SuppressWarnings("unchecked")
    protected void handleGroupPrincipalCallback(GroupPrincipalCallback callback) throws CustomRegistryException, EntryNotFoundException, RemoteException {
        Subject clientSubject = callback.getSubject();
        Hashtable<String, Object> credData = null;
        if (clientSubject != null) {
            String[] groupsFromCallback = callback.getGroups();
            if (groupsFromCallback != null && groupsFromCallback.length > 0) {
                if (tc.isDebugEnabled()) {
                    Tr.debug(tc, "Group names in Callback: ", Arrays.asList(groupsFromCallback));
                }
                credData = getSubjectCustomData(clientSubject);
                List<String> groupsFromSubject = (List<String>) credData.get(AttributeNameConstants.WSCREDENTIAL_GROUPS);
                if (groupsFromSubject == null) {
                    groupsFromSubject = new ArrayList<String>();
                    credData.put(AttributeNameConstants.WSCREDENTIAL_GROUPS, groupsFromSubject);
                }

                for (int i = 0; i < groupsFromCallback.length; i++) {
                    String groupFromCallback = groupsFromCallback[i];
                    if (groupFromCallback == null || groupFromCallback.isEmpty()) {
                        if (tc.isDebugEnabled()) {
                            Tr.debug(tc, "Group is null or an empty string, it has been ignored.");
                        }
                        continue;
                    }

                    String group = mapGroup(groupFromCallback);

                    if (!groupsFromSubject.contains(group)) {
                        groupsFromSubject.add(group);
                        if (tc.isDebugEnabled()) {
                            Tr.debug(tc, "Added groupId: " + group);
                        }
                    } else {
                        if (tc.isDebugEnabled()) {
                            Tr.debug(tc, group + " already exists in custom credential data, avoid duplicates.");
                        }
                    }
                }
            } else {
                if (tc.isDebugEnabled()) {
                    Tr.debug(tc, "Callback has no groups.");
                }
            }
        }
        if (tc.isDebugEnabled()) {
            Tr.debug(tc, "handleGroupPrincipalCallback", credData);
        }
    }
1081836
function(callback) {
        var self = this,
            requestOptions = {
            uri: '/loadbalancers',
            endpoint: rackspace.Endpoints.CloudLoadBalancer
        };

        self.authorizedRequest(requestOptions, function(err, res, body) {
            if (err || !body.loadBalancers) {
                callback(err);
                return;
            }

            var loadBalancers = [];

            for (var i = 0; i < body.loadBalancers.length; i++) {
                loadBalancers.push(new rackspace.LoadBalancer(self, body.loadBalancers[i]));
            }

            callback(err, loadBalancers);
        });
    }
871599
function(groupName, callback) {
        var url = this.getResourceUrl({ path: '/groups/' + groupName, user: null });
        request.del(this.getSignedResourceUrl('DELETE', url), callback);

        return this;
    }
802818
private void setJettyAuthentication(Subject subject) {
        // In unit test environments there may not be a current connection.  If any nulls are encountered
        // then, by definition, there is no container to update.
        HttpConnection connection = HttpConnection.getCurrentConnection();
        if (connection == null) {
            return;
        }
        Request jettyRequest = connection.getHttpChannel().getRequest();
        if (jettyRequest == null) {
            return;
        }

        // This cast down is safe; subject is always created with this type of principal
        PrincipalWithRoles principal = (PrincipalWithRoles) subject.getPrincipal();
        UserIdentity identity = principal.toUserIdentity();

        jettyRequest.setAuthentication(new UserAuthentication(SecurityContext.BASIC_AUTH, identity));
    }
1214504
public boolean doInnerCallback(ModificationQueue modificationQueue, SecurityContext securityContext, ErrorBuffer errorBuffer) throws FrameworkException {

		// check for modification propagation along the relationships
		if ((status & STATE_PROPAGATING_MODIFICATION) == STATE_PROPAGATING_MODIFICATION && object instanceof AbstractNode) {

			Set<AbstractNode> nodes = ((AbstractNode)object).getNodesForModificationPropagation();
			if (nodes != null) {

				for (AbstractNode node : nodes) {

					modificationQueue.propagatedModification(node);
				}
			}

		}

		// examine only the last 4 bits here
		switch (status & 0x000f) {

			case 15:
			case 14:
			case 13:
			case 12:
			case 11:
			case 10:
			case  9:
			case  8: // since all values >= 8 mean that the object was passively deleted, no action has to be taken
				 // (no callback for passive deletion!)
				break;

			case 7:	// created, modified, deleted, poor guy => no callback
				break;

			case 6: // created, modified => only creation callback will be called
				object.onCreation(securityContext, errorBuffer);
				break;

			case 5: // created, deleted => no callback
				break;

			case 4: // created => creation callback
				object.onCreation(securityContext, errorBuffer);
				break;

			case 3: // modified, deleted => deletion callback
				object.onDeletion(securityContext, errorBuffer, removedProperties);
				break;

			case 2: // modified => modification callback
				object.onModification(securityContext, errorBuffer, modificationQueue);
				break;

			case 1: // deleted => deletion callback
				object.onDeletion(securityContext, errorBuffer, removedProperties);
				break;

			case 0:	// no action, no callback
				break;

			default:
				break;
		}

		// mark as finished
		modified = false;

		return !errorBuffer.hasError();
	}
1277465
private void onPublicKeysGroupAdded(int uid, ApiEncryptionKeyGroup keyGroup) {
        UserKeys userKeys = getCachedUserKeys(uid);
        if (userKeys == null) {
            return;
        }
        UserKeysGroup validatedKeysGroup = validateUserKeysGroup(uid, keyGroup);
        if (validatedKeysGroup != null) {
            UserKeys updatedUserKeys = userKeys.addUserKeyGroup(validatedKeysGroup);
            cacheUserKeys(updatedUserKeys);
            context().getEncryption().getEncryptedChatManager(uid)
                    .send(new EncryptedPeerActor.KeyGroupUpdated(userKeys));
        }
    }
191471
function startGroup(&$group, $required, $error) 
    {
        $this->_currentGroup = $this->_elementToObject($group, $required, $error);
        if(!empty($error)) {
            $name = $this->_currentGroup->name;
            $this->_obj->errors->$name = $error;
        }
    }
912113
public static Principal getSubjectUserPrincipal(Subject s) {
      if (s != null) {
         for (Principal p : s.getPrincipals()) {
            if (!(p instanceof Group)) {
               return p;
            }
         }
      }
      return null;
   }
1209048
function (domain, poString, callback) {
        var icuObject = this.poStringToICUSync(domain, poString);
        callback(null, icuObject);
    }
151926
@Override
    @Deprecated
    public void loadServerInstances(final String serverGroup, final AsyncCallback<List<ServerInstance>> callback) {
        final List<ServerInstance> instancesOfGroup = new LinkedList<ServerInstance>();
        loadHostsAndServerInstances(new SimpleCallback<List<HostInfo>>() {
            @Override
            public void onSuccess(final List<HostInfo> result) {
                for (HostInfo host : result) {
                    List<ServerInstance> instances = host.getServerInstances();
                    for (ServerInstance instance : instances) {
                        if (serverGroup == null) {
                            instancesOfGroup.add(instance);
                        } else if (instance.getGroup().equals(instance.getGroup())) {
                            instancesOfGroup.add(instance);
                        }
                    }
                }
                callback.onSuccess(instancesOfGroup);
            }
        });
    }
641884
@PUT
    @Path("{group}/{id}")
    @Consumes("application/x.json-update-role")
    public SuccessResponse updateRoleFromUpdateRequest(@PathParam("group") String group, @PathParam("id") String id,
                                                       UpdateEmoRoleRequest request, @Authenticated Subject subject) {
        _uac.updateRole(subject, request.setRoleKey(new EmoRoleKey(group, id)));
        return SuccessResponse.instance();
    }
1361421
function(server, callback) {
        var self = this, serverId;

        serverId = server instanceof rackspace.Server ? server.id : server;

        if (!server) {
            throw new Error('Server is a required argument.');
        }

        var requestOptions = {
            uri: '/servers/' + serverId,
            method: 'DELETE'
        };

        self.authorizedRequest(requestOptions, function(err, res, body) {
            if (err) {
                callback(err);
                return;
            }

            callback(err, res.statusCode === 204);
        });
    }
440518
private void postSetValidationGroups()
    {
        if (this.validationGroups == null || this.validationGroups.matches(EMPTY_VALIDATION_GROUPS_PATTERN))
        {
            this.validationGroupsArray = DEFAULT_VALIDATION_GROUPS_ARRAY;
        }
        else
        {
            String[] classes = this.validationGroups.split(VALIDATION_GROUPS_DELIMITER);
            List<Class<?>> validationGroupsList = new ArrayList<Class<?>>(classes.length);

            for (String clazz : classes)
            {
                clazz = clazz.trim();
                if (!clazz.isEmpty())
                {
                    Class<?> theClass = null;
                    ClassLoader cl = null;
                    if (System.getSecurityManager() != null) 
                    {
                        try 
                        {
                            cl = AccessController.doPrivileged(new PrivilegedExceptionAction<ClassLoader>()
                                    {
                                        public ClassLoader run() throws PrivilegedActionException
                                        {
                                            return Thread.currentThread().getContextClassLoader();
                                        }
                                    });
                        }
                        catch (PrivilegedActionException pae)
                        {
                            throw new FacesException(pae);
                        }
                    }
                    else
                    {
                        cl = Thread.currentThread().getContextClassLoader();
                    }
                    
                    try
                    {                        
                        // Try WebApp ClassLoader first
                        theClass = Class.forName(clazz,false,cl);
                    }
                    catch (ClassNotFoundException ignore)
                    {
                        try
                        {
                            // fallback: Try ClassLoader for BeanValidator (i.e. the myfaces.jar lib)
                            theClass = Class.forName(clazz,false, BeanValidator.class.getClassLoader());
                        }
                        catch (ClassNotFoundException e)
                        {
                            throw new RuntimeException("Could not load validation group", e);
                        }                        
                    }
                    // the class was found
                    validationGroupsList.add(theClass);
                }
            }
                    
            this.validationGroupsArray = validationGroupsList.toArray(new Class[validationGroupsList.size()]);
        }
    }
458079
public function updateRole($projectId, $roleId, $user = null, $group = null)
    {
        $parameters = [];
        if ((is_null($user) && is_null($group)) || (!is_null($user) && !is_null($group))) {
            throw new EndpointParameterException('User or group should be given');
        } elseif (!is_null($user)) {
            $parameters['user'] = $user;
        } else {
            $parameters['group'] = $group;
        }

        return $this->apiClient->callEndpoint(
            sprintf('%s/%s/role/%s', self::ENDPOINT, $projectId, $roleId),
            $parameters,
            null,
            HttpMethod::REQUEST_PUT
        );
    }
277583
@Override
    public boolean isValidGroup(String groupSecurityName) throws RegistryException {
        if (groupSecurityName == null) {
            throw new IllegalArgumentException("groupSecurityName is null");
        }
        if (groupSecurityName.isEmpty()) {
            throw new IllegalArgumentException("groupSecurityName is an empty String");
        }
        return false;
    }
301697
protected function registerDirectly($request, $callback, $registerUrL, $vo = null, $group = null)
    {
        $params = array();
        if (!is_null($vo)) {
            $params['vo'] = $vo->getShortName();
            if (!is_null($group)) {
                $params['group'] = $group->getName();
            }
        }
        $params[self::TARGET_NEW] = $callback;
        $params[self::TARGET_EXISTING] = $callback;
        $params[self::TARGET_EXTENDED] = $callback;

        $id = State::saveState($request, 'perun:PerunIdentity');

        if (in_array($this->spEntityId, $this->listOfSpsWithoutInfoAboutRedirection)) {
            HTTP::redirectTrustedURL($registerUrL, $params);
        }

        $url = Module::getModuleURL('perun/unauthorized_access_go_to_registration.php');
        HTTP::redirectTrustedURL(
            $url,
            array(
                'StateId' => $id,
                'SPMetadata' => $request['SPMetadata'],
                'registerUrL' => $registerUrL,
                'params' => $params
            )
        );
    }
889123
private void setCredential(Subject subject, WSPrincipal principal) throws CredentialException {
        String securityName = principal.getName();
        Hashtable<String, ?> customProperties = getUniqueIdHashtableFromSubject(subject);
        if (customProperties == null || customProperties.isEmpty()) {
            UserRegistryService urService = userRegistryServiceRef.getService();
            if (urService != null) {
                String urType = urService.getUserRegistryType();
                if ("WIM".equalsIgnoreCase(urType) || "LDAP".equalsIgnoreCase(urType)) {
                    try {
                        securityName = urService.getUserRegistry().getUserDisplayName(securityName);
                    } catch (Exception e) {
                        //do nothing
                    }
                }
            }
        }
        if (securityName == null || securityName.length() == 0) {
            securityName = principal.getName();
        }
        String accessId = principal.getAccessId();

        String customRealm = null;
        String realm = null;
        String uniqueName = null;

        if (customProperties != null) {
            customRealm = (String) customProperties.get(AttributeNameConstants.WSCREDENTIAL_REALM);
        }

        if (customRealm != null) {
            realm = customRealm;
            String[] parts = accessId.split(realm + "/");
            if (parts != null && parts.length == 2)
                uniqueName = parts[1];
        } else {
            realm = AccessIdUtil.getRealm(accessId);
            uniqueName = AccessIdUtil.getUniqueId(accessId);
        }
        if (AccessIdUtil.isServerAccessId(accessId)) {
            // Create a server WSCredential
            setCredential(null, subject, realm, securityName, uniqueName, null, accessId, null, null);
        } else {
            CredentialsService cs = credentialsServiceRef.getService();
            String unauthenticatedUserid = cs.getUnauthenticatedUserid();

            if (securityName != null && unauthenticatedUserid != null &&
                securityName.equals(unauthenticatedUserid)) {
                // Create an unauthenticated WSCredential
                setCredential(unauthenticatedUserid, subject, realm, securityName, uniqueName, null, null, null, null);
            } else if (AccessIdUtil.isUserAccessId(accessId)) {
                // Create a user WSCredential
                createUserWSCredential(subject, securityName, accessId, realm, uniqueName, unauthenticatedUserid);
            }
        }
    }