Helper function that moves permissions from a namespace being deleted to
its parent namespace

@param trans
@param parent
@param sb
@param rpdc
- list of permissions in namespace being deleted
320242
private void movePerms(AuthzTrans trans, NsDAO.Data parent,
			StringBuilder sb, Result<List<PermDAO.Data>> rpdc) {

		Result<Void> rv;
		Result<PermDAO.Data> pd;

		if (rpdc.isOKhasData()) {
			for (PermDAO.Data pdd : rpdc.value) {
				String delP2 = pdd.type;
				if ("access".equals(delP2)) {
				    continue;
				}
				// Remove old Perm from Roles, save them off
				List<RoleDAO.Data> lrdd = new ArrayList<RoleDAO.Data>();
				
				for(String rl : pdd.roles(false)) {
					Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,q,rl);
					if(rrdd.isOKhasData()) {
						RoleDAO.Data rdd = rrdd.value;
						lrdd.add(rdd);
						q.roleDAO.delPerm(trans, rdd, pdd);
					} else{
						trans.error().log(rrdd.errorString());
					}
				}
				
				// Save off Old keys
				String delP1 = pdd.ns;
				NsSplit nss = new NsSplit(parent, pdd.fullType());
				pdd.ns = nss.ns;
				pdd.type = nss.name;
				// Use direct Create/Delete, because switching namespaces
				if ((pd = q.permDAO.create(trans, pdd)).isOK()) {
					// Put Role back into Perm, with correct info
					for(RoleDAO.Data rdd : lrdd) {
						q.roleDAO.addPerm(trans, rdd, pdd);
					}

					pdd.ns = delP1;
					pdd.type = delP2;
					if ((rv = q.permDAO.delete(trans, pdd, false)).notOK()) {
						sb.append(rv.details);
						sb.append('\n');
						// } else {
						// Need to invalidate directly, because we're switching
						// places in NS, not normal cache behavior
						// q.permDAO.invalidate(trans,pdd);
					}
				} else {
					sb.append(pd.details);
					sb.append('\n');
				}
			}
		}
	}
1109246
public static void serializeWriterDirPermissions(State state, int numBranches, int branchId,
      FsPermission fsPermissions) {
    serializeFsPermissions(state,
        ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_DIR_PERMISSIONS, numBranches, branchId),
        fsPermissions);
  }
282197
void topicSpaceDeleted(DestinationHandler destination) throws SIResourceException
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "topicSpaceDeleted", destination);

    // Synchronize around the topic space references to stop removal and
    // additions occuring at the same time. 
    synchronized (_topicSpaces)
    {
      // Get the list of the different PubSubOutputHandlers from the Destination
      // Clone the list as the original is locked
      final HashMap pubsubOutputHandlers = (HashMap)(destination.getAllPubSubOutputHandlers()).clone();
      
      // Unlock the list as leaving it locked results in deadlock
      destination.unlockPubsubOutputHandlers();

      // Check that there are some output handlers as they may have all been 
      // removed or none have ever been created on this topicSpace destination
      if (pubsubOutputHandlers != null && pubsubOutputHandlers.size() > 0)
      {
        final ArrayList topicSpacesDeleted = new ArrayList();
        final ArrayList topicsDeleted = new ArrayList();

        // Get the set of keys from the pubsubOutputHandlers which is infact the
        // list of meNames
        final Iterator neighbourUuids = pubsubOutputHandlers.keySet().iterator();

        // Iterate over the list of meNames
        while (neighbourUuids.hasNext())
        {
          // Reset the created topicSpaces
          topicSpacesDeleted.clear();

          // Reset the created topics
          topicsDeleted.clear();

          // Get the next me Name
          final SIBUuid8 neighbourUuid = (SIBUuid8) neighbourUuids.next();

          // Get the PubSubOutputHandler associated with this ME.
          final PubSubOutputHandler handler =
            (PubSubOutputHandler) pubsubOutputHandlers.get(neighbourUuid);

          final String topics[] = handler.getTopics();
          
          Neighbour neighbour = getNeighbour(neighbourUuid);
          
          // In the case that this neighbour is recovered, but not activated,
          // this neighbour should be got from the recovered list
          boolean warmRestarted = false;
          if (neighbour == null)
          {          
            synchronized(_recoveredNeighbours)
            {
              neighbour = (Neighbour)_recoveredNeighbours.get(neighbourUuid);
            }
            warmRestarted = true;
          } 
          
          // Cycle through the topics removing each one from this ME.
          // but only if there are topics to remove.
          if ( neighbour != null && topics != null)
          {
            for (int i = 0; i < topics.length; i++)
            {              
              // Remove this Handler from the MatchSpace 
              if (!warmRestarted)
              {
                MESubscription meSub = neighbour.getSubscription(destination.getUuid(), topics[i]);
              
                ControllableProxySubscription sub = meSub.getMatchspaceSub();              
                _proxyHandler
                  .getMessageProcessor()
                  .getMessageProcessorMatching()
                  .removePubSubOutputHandlerMatchTarget(sub);
                  
                destination.getSubscriptionIndex().remove(sub);
              }  
              
              // Remove the topic from the referenced topics in the handler.
              handler.removeTopic(topics[i]);
  
              // Add a reference into the reference list so when a delete arrives
              // The proxy can be removed.
              addTopicSpaceReference(neighbourUuid, destination.getUuid(), topics[i], warmRestarted);
  
              // Add the topicSpace and topic to the set of deleted topics.
              topicSpacesDeleted.add(destination.getUuid());
              topicsDeleted.add(topics[i]);
            }
          }
          
          // Having cleaned all the topics out from the handler
          // delete the handler.
          destination.deletePubSubOutputHandler(neighbourUuid);                                        
          
          
          // Publish the deleted event for the deleted topics on the topic space
          if ( neighbour!= null )
            _proxyHandler.unsubscribeEvent(
              topicSpacesDeleted,
              topicsDeleted,
              neighbour.getBusId(),
              null);
        }
      }
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "topicSpaceDeleted");
  }
1079220
void revoke(SchemaObject object, Right right, Grantee grantor,
                boolean grantOption) {

        final HsqlName name     = object.getName();
        Iterator       it       = directRightsMap.get(name);
        Right          existing = null;

        while (it.hasNext()) {
            existing = (Right) it.next();

            if (existing.grantor == grantor) {
                break;
            }
        }

        if (existing == null) {
            return;
        }

        if (existing.grantableRights != null) {
            existing.grantableRights.remove(object, right);
        }

        if (grantOption) {
            return;
        }

        if (right.isFull) {
            directRightsMap.remove(name, existing);
            grantor.grantedRightsMap.remove(name, existing);
            updateAllRights();

            return;
        }

        existing.remove(object, right);

        if (existing.isEmpty()) {
            directRightsMap.remove(name, existing);
            grantor.grantedRightsMap.remove(object, existing);
        }

        updateAllRights();

        return;
    }
156885
@Override
    public boolean handleChild(DDParser parser, String localName) throws ParseException {
        if ("permission".equals(localName)) {
            parsePermission(parser);
            return true;
        }
        return false;
    }
481536
public final void checkPermission( Destination destination , String action ) throws JMSException
    {
    	if (securityContext == null)
            return; // Security is disabled
    	
    	DestinationRef destinationRef = DestinationTools.asRef(destination);
    	securityContext.checkPermission(destinationRef.getResourceName(), action);        
    }
67463
public Result<Void> addPermToRole(AuthzTrans trans, RoleDAO.Data role,PermDAO.Data pd, boolean fromApproval) {
		String user = trans.user();
		
		if (!fromApproval) {
			Result<NsDAO.Data> rRoleCo = q.deriveFirstNsForType(trans, role.ns, NsType.COMPANY);
			if(rRoleCo.notOK()) {
				return Result.err(rRoleCo);
			}
			Result<NsDAO.Data> rPermCo = q.deriveFirstNsForType(trans, pd.ns, NsType.COMPANY);
			if(rPermCo.notOK()) {
				return Result.err(rPermCo);
			}

			// Not from same company
			if(!rRoleCo.value.name.equals(rPermCo.value.name)) {
				Result<Data> r;
				// Only grant if User ALSO has Write ability in Other Company
				if((r = q.mayUser(trans, user, role, Access.write)).notOK()) {
					return Result.err(r);
				}
			}
			

			// Must be Perm Admin, or Granted Special Permission
			Result<NsDAO.Data> ucp = q.mayUser(trans, user, pd, Access.write);
			if (ucp.notOK()) {
				// Don't allow CLI potential Grantees to change their own AAF
				// Perms,
				if ((Define.ROOT_NS.equals(pd.ns) && Question.NS.equals(pd.type)) 
						|| !q.isGranted(trans, trans.user(),Define.ROOT_NS,Question.PERM, rPermCo.value.name, "grant")) {
				// Not otherwise granted
				// TODO Needed?
					return Result.err(ucp);
				}
				// Final Check... Don't allow Grantees to add to Roles they are
				// part of
				Result<List<UserRoleDAO.Data>> rlurd = q.userRoleDAO
						.readByUser(trans, trans.user());
				if (rlurd.isOK()) {
					for (UserRoleDAO.Data ur : rlurd.value) {
						if (role.ns.equals(ur.ns) && role.name.equals(ur.rname)) {
							return Result.err(ucp);
						}
					}
				}
			}
		}

		Result<List<PermDAO.Data>> rlpd = q.permDAO.read(trans, pd);
		if (rlpd.notOKorIsEmpty()) {
			return Result.err(Status.ERR_PermissionNotFound,
					"Permission must exist to add to Role");
		}

		Result<List<RoleDAO.Data>> rlrd = q.roleDAO.read(trans, role); // Already
																		// Checked
																		// for
																		// can
																		// change
																		// Role
		Result<Void> rv;

		if (rlrd.notOKorIsEmpty()) {
			if (trans.forceRequested()) {
				Result<NsDAO.Data> ucr = q.mayUser(trans, user, role,
						Access.write);
				if (ucr.notOK()) {
				    return Result
				    		.err(Status.ERR_Denied,
				    				"Role [%s.%s] does not exist. User [%s] cannot create.",
				    				role.ns, role.name, user);
				}

				role.perms(true).add(pd.encode());
				Result<RoleDAO.Data> rdd = q.roleDAO.create(trans, role);
				if (rdd.isOK()) {
					rv = Result.ok();
				} else {
					rv = Result.err(rdd);
				}
			} else {
			    return Result.err(Status.ERR_RoleNotFound,
			    		"Role [%s.%s] does not exist.", role.ns, role.name);
			}
		} else {
			role = rlrd.value.get(0);
			if (role.perms(false).contains(pd.encode())) {
				return Result.err(Status.ERR_ConflictAlreadyExists,
								"Permission [%s.%s] is already a member of role [%s,%s]",
								pd.ns, pd.type, role.ns, role.name);
			}
			role.perms(true).add(pd.encode()); // this is added for Caching
												// access purposes... doesn't
												// affect addPerm
			rv = q.roleDAO.addPerm(trans, role, pd);
		}
		if (rv.status == Status.OK) {
			return q.permDAO.addRole(trans, pd, role);
			// exploring how to add information message to successful http
			// request
		}
		return rv;
	}
124412
public function rescanAreaPermissionsChain()
    {
        $db = Database::connection();
        if ($this->overrideCollectionPermissions()) {
            return false;
        }
        // first, we obtain the inheritance of permissions for this particular collection
        $areac = $this->getAreaCollectionObject();
        if (is_a($areac, 'Page')) {
            if ($areac->getCollectionInheritance() == 'PARENT') {
                $cIDToCheck = $areac->getCollectionParentID();
                // first, we temporarily set the arInheritPermissionsFromAreaOnCID to whatever the arInheritPermissionsFromAreaOnCID is set to
                // in the immediate parent collection
                $arInheritPermissionsFromAreaOnCID = $db->fetchColumn(
                    'select a.arInheritPermissionsFromAreaOnCID from Pages c inner join Areas a on (c.cID = a.cID) where c.cID = ? and a.arHandle = ?',
                    array($cIDToCheck, $this->getAreaHandle())
                );
                if ($arInheritPermissionsFromAreaOnCID > 0) {
                    $db->executeQuery(
                        'update Areas set arInheritPermissionsFromAreaOnCID = ? where arID = ?',
                        array($arInheritPermissionsFromAreaOnCID, $this->getAreaID())
                    );
                }

                // now we do the recursive rescan to see if any areas themselves override collection permissions

                while ($cIDToCheck > 0) {
                    $row = $db->fetchAssoc(
                        'select c.cParentID, c.cID, a.arHandle, a.arOverrideCollectionPermissions, a.arID from Pages c inner join Areas a on (c.cID = a.cID) where c.cID = ? and a.arHandle = ?',
                        array($cIDToCheck, $this->getAreaHandle())
                    );
                    if (empty($row)) {
                        break;
                    }
                    if ($row['arOverrideCollectionPermissions'] == 1) {
                        if ($row['cID'] > 0) {
                            // then that means we have successfully found a parent area record that we can inherit from. So we set
                            // out current area to inherit from that COLLECTION ID (not area ID - from the collection ID)
                            $db->executeQuery(
                                'update Areas set arInheritPermissionsFromAreaOnCID = ? where arID = ?',
                                array($row['cID'], $this->getAreaID())
                            );
                            $this->arInheritPermissionsFromAreaOnCID = $row['cID'];
                        }
                        break;
                    }
                    $cIDToCheck = $row['cParentID'];
                }
            } else {
                if ($areac->getCollectionInheritance() == 'TEMPLATE') {
                    // we grab an area on the master collection (if it exists)
                    $doOverride = $db->fetchColumn(
                        'select arOverrideCollectionPermissions from Pages c inner join Areas a on (c.cID = a.cID) where c.cID = ? and a.arHandle = ?',
                        array($areac->getPermissionsCollectionID(), $this->getAreaHandle())
                    );
                    if ($doOverride && $areac->getPermissionsCollectionID() > 0) {
                        $db->executeQuery(
                            'update Areas set arInheritPermissionsFromAreaOnCID = ? where arID = ?',
                            array($areac->getPermissionsCollectionID(), $this->getAreaID())
                        );
                        $this->arInheritPermissionsFromAreaOnCID = $areac->getPermissionsCollectionID();
                    }
                }
            }
        }
    }
10741
public static List<String> transformText(Context context, String... permissions) {
        return transformText(context, Arrays.asList(permissions));
    }
1369204
private Permission createReadPermission(String table) {
        return _permissionResolver.resolvePermission(Permissions.readSorTable(new NamedResource(table)));
    }
6627
public void deleteProjectPermission(DbSession dbSession, int userId, String permission, long projectId) {
    mapper(dbSession).deleteProjectPermission(userId, permission, projectId);
  }
539307
private void requestPermissionsToSystem(Collection<String> permissions) {
    if (!isShowingNativeDialog.get()) {
      androidPermissionService.requestPermissions(activity,
          permissions.toArray(new String[permissions.size()]), PERMISSIONS_REQUEST_CODE);
    }
    isShowingNativeDialog.set(true);
  }
1368780
static void requestPermission(Source source, String[] permissions) {
        Intent intent = new Intent(source.getContext(), BridgeActivity.class);
        intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_PERMISSION);
        intent.putExtra(KEY_PERMISSIONS, permissions);
        source.startActivity(intent);
    }
1208161
@RequestMapping(value = "/deletePermission", method = RequestMethod.POST)
    public void deletePermission(
            @RequestParam("principal") String principal,
            @RequestParam("owner") String owner,
            @RequestParam("activity") String activity,
            @RequestParam("target") String target,
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {

        // ensure the current user is authorized to update and view permissions
        final IPerson currentUser = personManager.getPerson((HttpServletRequest) request);

        if (!permissionAdministrationHelper.canEditPermission(currentUser, target)
                || !permissionAdministrationHelper.canViewPermission(currentUser, target)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        JsonEntityBean bean = groupListHelper.getEntityForPrincipal(principal);

        if (bean != null) {

            IAuthorizationPrincipal p = groupListHelper.getPrincipalForEntity(bean);

            IPermission[] directPermissions =
                    permissionStore.select(owner, p.getPrincipalString(), activity, target, null);
            this.authorizationService.removePermissions(directPermissions);

        } else {
            log.warn(
                    "Unable to resolve the following principal (will "
                            + "be omitted from the list of assignments):  "
                            + principal);
        }

        response.setStatus(HttpServletResponse.SC_OK);
        return;
    }
1251857
@Override
    public void deleteSystemDestination(JsDestinationAddress destAddress)
                    throws SINotPossibleInCurrentConfigurationException,
                    SIException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "deleteSystemDestination", destAddress);

        // See if this connection has been closed
        checkNotClosed();

        if (!destAddress.getDestinationName().startsWith(SIMPConstants.SYSTEM_DESTINATION_PREFIX))
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(tc, "deleteSystemDestination", "SIIncorrectCallException");
            throw new SIIncorrectCallException(
                            nls.getFormattedMessage(
                                                    "SYSTEM_DESTINATION_USAGE_ERROR_CWSIP0024",
                                                    new Object[] { destAddress.getDestinationName(),
                                                                  _messageProcessor.getMessagingEngineName() },
                                                    null));
        }

        _destinationManager.deleteSystemDestination(destAddress);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "deleteSystemDestination");
    }
702173
public static void toSchema(StringBuilder sb, Group grp) {
        // Don't output the default roles because user cannot change them.
        if (grp.getTypeName().equalsIgnoreCase("ADMINISTRATOR") || grp.getTypeName().equalsIgnoreCase("USER")) {
            return;
        }

        final EnumSet<Permission> permissions = Permission.getPermissionSetForGroup(grp);
        sb.append("CREATE ROLE ").append(grp.getTypeName());

        String delimiter = " WITH ";
        for (Permission permission : permissions) {
            sb.append(delimiter).append(permission.name());
            delimiter = ", ";
        }

        sb.append(";\n");
    }
307885
@Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                         @NonNull int[] grantResults) {
    if (requestCode == REQUEST_READ_CONTACTS) {
      if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        populateAutoComplete();
      }
    }
  }