/**
   * Update the calculated person data. This method and updateCalculatedPersonOnDeleteOfSor need to
   * be generalized to handle recalculations.
   *
   * @param toPerson
   * @param fromPerson
   * @param sorPerson Adjust calculated roles... Point prc_role to prc_person receiving role Add the
   *     role to the set of roles in receiving prc_person Remove role from prc person losing role
   */
  protected void updateCalculatedPersonsOnMoveOfSor(
      final Person toPerson, final Person fromPerson, final SorPerson sorPerson) {
    Assert.notNull(toPerson, "toPerson cannot be null");
    Assert.notNull(fromPerson, "fromPerson cannot be null");
    logger.info("UpdateCalculated: recalculating person data for move.");

    final List<Role> rolesToDelete = new ArrayList<Role>();

    final List<SorRole> sorRoles = new ArrayList<SorRole>(sorPerson.getRoles());
    for (final SorRole sorRole : sorRoles) {
      for (final Role role : fromPerson.getRoles()) {
        if (sorRole.getId().equals(role.getSorRoleId())) {
          sorRoleElector.addSorRole(sorRole, toPerson);
          rolesToDelete.add(role);
        }
      }
    }
    for (final Role role : rolesToDelete) {
      sorRoleElector.removeCalculatedRole(
          fromPerson, role, this.personRepository.getSoRRecordsForPerson(fromPerson));
      fromPerson.getRoles().remove(role);
    }

    // TODO recalculate names for person receiving role? Anything else?
    // TODO recalculate names for person losing role? Anything else?
    //        this.personRepository.savePerson(fromPerson);
    //        this.personRepository.savePerson(toPerson);
  }
Esempio n. 2
0
  private HashMap<String, Role> initializeRoles(String[] rolesProperty, Properties props) {
    Map<String, Role> availableRoles = new HashMap<String, Role>();
    availableRoles.put("trader", new TraderRole("trader"));
    availableRoles.put("manipulator", new ManipulatorRole());
    availableRoles.put("judge", new JudgeRole());

    HashMap<String, Role> rolesMap = new HashMap<String, Role>();
    for (int i = 0; i < rolesProperty.length; i++) {
      String role = rolesProperty[i];

      if (rolesMap.get(role) == null) {
        Role subjectType = availableRoles.get(role);
        if (subjectType == null) {
          subjectType = new TraderRole(role);
          subjectType.initializeFromProps(props);
          rolesMap.put(role, subjectType);
        } else {
          subjectType.initializeFromProps(props);
          rolesMap.put(role, subjectType);
        }
      }
    }

    if (rolesMap.get("judge") == null) {
      String judgeWarning = "Judge role required if manipulators are used.";
      appendToErrorMessage(judgeWarning);
    }

    return rolesMap;
  }
Esempio n. 3
0
 public Map<String, String> getRoleIdentifiers() {
   Map<String, String> idMap = new Hashtable<String, String>();
   for (Role r : getRoles()) {
     idMap.put(r.getID(), r.getName());
   }
   return idMap;
 }
Esempio n. 4
0
 public Set<Participant> resolveParticipantsFromResourceName(String anyName) {
   Set<Participant> pSet = new HashSet<Participant>();
   Participant p = getParticipantFromUserID(anyName);
   if (p != null) {
     pSet.add(p);
     return pSet;
   }
   Role r = getRoleByName(anyName);
   if (r != null) {
     pSet.addAll(getRoleParticipants(r.getID()));
     return pSet;
   }
   Position pos = getPositionByLabel(anyName);
   if (pos != null) {
     pSet.addAll(getPositionParticipants(pos.getID()));
     return pSet;
   }
   OrgGroup o = getOrgGroupByLabel(anyName);
   if (o != null) {
     pSet.addAll(getOrgGroupParticipants(o.getID()));
     return pSet;
   }
   Capability c = getCapabilityByLabel(anyName);
   if (c != null) {
     pSet.addAll(getCapabilityParticipants(c.getID()));
   }
   return pSet;
 }
  public ServiceExecutionResult<SorRole> updateSorRole(
      final SorPerson sorPerson, final SorRole sorRole) {
    Assert.notNull(sorPerson, "sorPerson cannot be null.");
    Assert.notNull(sorRole, "sorRole cannot be null.");

    final Set validationErrors = this.validator.validate(sorRole);

    if (!validationErrors.isEmpty()) {
      // since because of existing design we cannot raise exception, we can only rollback the
      // transaction through code
      // OR-384
      if (TransactionAspectSupport.currentTransactionStatus() != null) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }

      return new GeneralServiceExecutionResult<SorRole>(validationErrors);
    }

    final SorRole savedSorRole = this.personRepository.saveSorRole(sorRole);

    final Person person = this.personRepository.findByInternalId(sorPerson.getPersonId());
    final Role role = person.findRoleBySoRRoleId(savedSorRole.getId());
    if (role != null) {
      // update calculated role only if that role was previously converted to calculated one by
      // sorRoleElector
      role.recalculate(savedSorRole);
      this.personRepository.savePerson(person);
    }
    // else //do nothing i.e. don't update the calculated role if SorRoleElector Previously decided
    // not to convert this sor role to calculated role

    return new GeneralServiceExecutionResult<SorRole>(savedSorRole);
  }
  public void finalizeDomain(boolean checkForMissingExternals) {
    // go through each of the relations and add their slots to the
    // corresponding classes...
    for (DomainRelation rel : relations.values()) {
      List<Role> roles = rel.getRoles();
      int numRoles = roles.size();
      if (numRoles != 2) {
        if (numRoles > 2) {
          throw new RuntimeException("Can't handle with more than two roles yet!");
        }
      }

      Role r0 = roles.get(0);
      Role r1 = roles.get(1);
      r0.getType().addRoleSlot(r1);
      r1.getType().addRoleSlot(r0);
    }

    checkForRepeatedSlots();

    registerAnnotatedSlots();

    if (checkForMissingExternals) {
      for (String externalName : external.keySet()) {
        if (!isBuiltinEntity(externalName) && !classes.containsKey(externalName)) {
          throw new RuntimeException(
              externalName
                  + " was defined as an external entity but there is no concrete definition of it!");
        }
      }
    }
    finalized = true;
  }
  protected void checkForRepeatedSlots() {
    for (DomainClass domClass : classes.values()) {
      DomainEntity superDomClass = domClass.getSuperclass();
      if (superDomClass != null) {
        for (Slot slot : domClass.getSlotsList()) {
          if (superDomClass.findSlot(slot.getName()) != null) {
            System.err.printf(
                "WARNING: Slot named '%s' in class '%s' already exists in a superclass\n",
                slot.getName(), domClass.getName());
          }
          if (superDomClass.findRoleSlot(slot.getName()) != null) {
            System.err.printf(
                "WARNING: Slot named '%s' in class '%s' already exists in a superclass as role slot\n",
                slot.getName(), domClass.getName());
          }
        }

        for (Role role : domClass.getRoleSlotsList()) {
          if (superDomClass.findSlot(role.getName()) != null) {
            System.err.printf(
                "WARNING: Role slot named '%s' in class '%s' already exists in a superclass as a slot\n",
                role.getName(), domClass.getName());
          }

          if (superDomClass.findRoleSlot(role.getName()) != null) {
            System.err.printf(
                "WARNING: Role slot named '%s' in class '%s' already exists in a superclass as role slot\n",
                role.getName(), domClass.getName());
          }
        }
      }
    }
  }
Esempio n. 8
0
 @CacheNameRemove(name = AppConstants.DEFAULT_CACHENAME)
 @Before({AdminValidator.PermSaveValidator.class, Tx.class})
 public void permSave() {
   Permission permission = getModel(Permission.class);
   Permission parent = null;
   if (permission.getParentId() == 0) {
     parent =
         Permission.dao.findFirstBy("`permission`.pid=0 ORDER BY `permission`.right_code DESC");
   } else parent = Permission.dao.findById(permission.getParentId());
   boolean result = false;
   if (!ValidateUtils.me().isNullOrEmpty(parent)) {
     Permission.dao.updateBy(
         "`permission`.left_code=`permission`.left_code+2",
         "`permission`.left_code>=" + parent.get("right_code"));
     Permission.dao.updateBy(
         "`permission`.right_code=`permission`.right_code+2",
         "`permission`.right_code>=" + parent.get("right_code"));
     permission.set("left_code", parent.getLong("right_code"));
     permission.set("right_code", parent.getLong("right_code") + 1);
     permission.set("created_at", new Date());
     if (ValidateUtils.me().isNullOrEmpty(permission.get("id"))) {
       permission.remove("id");
     }
     result = permission.save();
   }
   if (result) {
     Role admin = Role.dao.findFirstBy("`role`.pid=0");
     admin.addPermission(permission);
     setAttr("state", "success");
   } else {
     setAttr("state", "failure");
   }
   dynaRender("/view/admin/role.ftl");
 }
Esempio n. 9
0
  @CacheNameRemove(name = AppConstants.DEFAULT_CACHENAME)
  @Before({AdminValidator.RoleDeleteValidator.class, Tx.class})
  public void roleDrop() {

    Integer id = getParaToInt("role.id");
    Role role = Role.dao.findById(id);
    boolean result = false;
    if (!ValidateUtils.me().isNullOrEmpty(role)) {
      Role.dao.updateBy(
          "`role`.left_code=`role`.left_code-2", "`role`.left_code>=" + role.get("left_code"));
      Role.dao.updateBy(
          "`role`.right_code=`role`.right_code-2", "`role`.right_code>=" + role.get("right_code"));

      result = role.delete();
      if (result) {
        RolePermission.dao.dropBy("role_id=" + role.get("id"));
      }
    }

    if (result) {
      setAttr("state", "success");
    } else {
      setAttr("state", "failure");
    }
    dynaRender("/view/admin/role.ftl");
  }
Esempio n. 10
0
  /* set Role access level */
  public static boolean deleteAccessLevel(Role role, String aclId) throws DBException {

    /* role specified? */
    if (role == null) {
      return false; // quietly ignore
    }
    String acctId = role.getAccountID();
    String roleId = role.getRoleID();

    /* acl-id specified? */
    if (StringTools.isBlank(aclId)) {
      return false; // quietly ignore
    }

    /* already deleted? */
    boolean aclExists = RoleAcl.exists(acctId, roleId, aclId);
    if (!aclExists) {
      return false;
    }

    /* delete */
    RoleAcl.Key aclKey = new RoleAcl.Key(acctId, roleId, aclId);
    aclKey.delete(true); // also delete dependencies
    return true;
  }
Esempio n. 11
0
  public void testAddUserRole() throws Exception {
    User user = dao.get(2L);
    assertEquals(6, user.getRoles().size());

    Role role = rdao.getRoleByName("ROLE_EXTERNAL");
    assertEquals((Long) 4L, (Long) role.getId());
    user.addRole(role);
    user = dao.saveUser(user);
    // flush();

    user = dao.get(2L);
    assertEquals(7, user.getRoles().size());

    // add the same role twice - should result in no additional role
    user.addRole(role);
    dao.saveUser(user);
    // flush();

    user = dao.get(2L);
    assertEquals("more than 7 roles", 7, user.getRoles().size());

    user.getRoles().remove(role);
    dao.saveUser(user);
    // flush();

    user = dao.get(2L);
    assertEquals(6, user.getRoles().size());
  }
Esempio n. 12
0
 public List<Right> getAllRights() {
   final List<Right> result = new ArrayList<Right>();
   for (final Role role : getAllRoles()) {
     result.addAll(role.getRights());
   }
   return result;
 }
  public void removeEveryOneFromRole(String SearchPath) throws RemoteException {

    if ((this.cmService != null) && (banonymous == false)) {
      BaseClass admins[] = new BaseClass[] {};
      BaseClass[] existingMembers;
      ArrayList<BaseClass> members = new ArrayList<BaseClass>();
      Role role = null;

      // Retrieve the capability, including policies
      admins =
          this.cmService.query(
              new SearchPathMultipleObject(SearchPath),
              new PropEnum[] {PropEnum.searchPath, PropEnum.members, PropEnum.defaultName},
              new Sort[] {},
              new QueryOptions());
      role = (Role) admins[0];

      // Store existing members
      if (role.getMembers().getValue() != null) {
        existingMembers = role.getMembers().getValue();
        for (BaseClass member : existingMembers)
          if (!member.getSearchPath().getValue().equals("CAMID(\"::Everyone\")"))
            members.add(member);
      }

      if (role != null) {
        // Update the role information in the content store
        role.setMembers(new BaseClassArrayProp());
        role.getMembers().setValue(members.toArray(new BaseClass[members.size()]));
        this.cmService.update(new BaseClass[] {role}, new UpdateOptions());
      }
    }
  }
Esempio n. 14
0
 @Override
 public void changeRole(String name, int roleID) {
   Role role = findRole(roleID);
   if (role != null) {
     role.setName(name);
   }
 }
Esempio n. 15
0
 public Collection<String> allRoleNames(CruiseConfig cruiseConfig) {
   List<String> roles = new ArrayList<String>();
   for (Role role : allRoles(cruiseConfig)) {
     roles.add(CaseInsensitiveString.str(role.getName()));
   }
   return roles;
 }
Esempio n. 16
0
  /**
   * Saves a role.
   *
   * @param role the role to save
   * @param currentUser the user performing the save operation
   */
  public void saveRole(Role role, User currentUser) throws IOException {
    Assert.notNull(role);
    Assert.notNull(currentUser);

    ILockedRepository repo = null;
    try {
      repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false);

      Map<String, Object> roleMap = new HashMap<String, Object>();
      roleMap.put("name", role.getName()); // $NON-NLS-1$
      Set<String> permissions = Sets.newHashSet();
      for (Permission permission : role.getPermissions()) {
        permissions.add(permission.name());
      }
      roleMap.put("permissions", permissions); // $NON-NLS-1$

      Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
      String json = gson.toJson(roleMap);
      File workingDir = RepositoryUtil.getWorkingDir(repo.r());
      File workingFile = new File(workingDir, role.getName() + ROLE_SUFFIX);
      FileUtils.write(workingFile, json, Charsets.UTF_8);

      Git git = Git.wrap(repo.r());
      git.add().addFilepattern(role.getName() + ROLE_SUFFIX).call();
      PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail());
      git.commit().setAuthor(ident).setCommitter(ident).setMessage(role.getName()).call();
    } catch (GitAPIException e) {
      throw new IOException(e);
    } finally {
      Util.closeQuietly(repo);
    }
  }
Esempio n. 17
0
 void importData(RoleSet original) {
   Role[] originalRoles = original.getRoles();
   for (int i = 0; i < originalRoles.length; i++) {
     Role nextRole = originalRoles[i];
     createRole(nextRole.getName(), nextRole.getID());
   }
 }
Esempio n. 18
0
 /**
  * 获取授予用户组的权利
  *
  * @return
  */
 public List<String> getAuthorities() {
   List<String> result = new ArrayList<>();
   for (Role role : roles) {
     result.addAll(role.getAuthorities());
   }
   return result;
 }
 private void setTimeoutRole(MessageContext context, String args) {
   DiscordApiClient apiClient = context.getApiClient();
   if (args.isEmpty()) {
     apiClient.sendMessage(
         loc.localize("commands.mod.settimeoutrole.response.missing"), context.getChannel());
     return;
   }
   Role role = apiClient.getRole(args, context.getServer());
   if (role == NO_ROLE) {
     apiClient.sendMessage(
         loc.localize("commands.mod.settimeoutrole.response.not_found", args),
         context.getChannel());
     return;
   }
   String serverId = context.getServer().getId();
   TempServerConfig serverConfig = serverStorage.get(serverId);
   if (serverConfig == null) {
     serverConfig = new TempServerConfig(serverId);
     serverStorage.put(serverId, serverConfig);
   }
   ServerTimeoutStorage storage = serverConfig.getServerTimeouts();
   if (storage == null) {
     storage = new ServerTimeoutStorage();
     serverConfig.setServerTimeouts(storage);
   }
   storage.setTimeoutRoleId(role.getId());
   apiClient.sendMessage(
       loc.localize("commands.mod.settimeoutrole.response", role.getName(), role.getId()),
       context.getChannel());
   saveServerConfig(serverConfig);
 }
Esempio n. 20
0
 private void getPositions(HttpServletRequest request, Role item) {
   String[] pos = request.getParameterValues("positions");
   item.clearPositions();
   for (int i = 0; i < pos.length; i++) {
     item.addPosition(Long.parseLong(pos[i]));
   }
 }
Esempio n. 21
0
 public String getModuleCommandStr() {
   StringBuilder ids = new StringBuilder();
   for (Role role : roles) {
     ids.append(role.getModuleCommandStr());
   }
   return ids.toString();
 }
Esempio n. 22
0
 private void getPermissions(HttpServletRequest request, Role item) {
   String[] per = request.getParameterValues("permissions");
   item.clearPermissions();
   for (int i = 0; i < per.length; i++) {
     item.addPermission(Long.parseLong(per[i]));
   }
 }
Esempio n. 23
0
  /* set Role access level */
  public static void setAccessLevel(Role role, String aclId, AccessLevel level) throws DBException {

    /* role specified? */
    if (role == null) {
      throw new DBException("Role not specified.");
    }
    String acctId = role.getAccountID();
    String roleId = role.getRoleID();

    /* acl-id specified? */
    if (StringTools.isBlank(aclId)) {
      throw new DBException("Acl-ID not specified.");
    }

    /* get/create role */
    RoleAcl roleAcl = null;
    RoleAcl.Key aclKey = new RoleAcl.Key(acctId, roleId, aclId);
    if (aclKey.exists()) { // may throw DBException
      roleAcl = RoleAcl.getRoleAcl(role, aclId); // may throw DBException
    } else {
      roleAcl = aclKey.getDBRecord();
      roleAcl.setRole(role);
    }

    /* set access level */
    int levelInt = (level != null) ? level.getIntValue() : AccessLevel.NONE.getIntValue();
    roleAcl.setAccessLevel(levelInt);

    /* save */
    roleAcl.save(); // may throw DBException
  }
Esempio n. 24
0
 public String getRolesAsString() {
   StringBuilder sb = new StringBuilder();
   for (Role r : roles) {
     if (sb.length() > 0) sb.append(", ");
     sb.append(r.getName());
   }
   return sb.toString();
 }
Esempio n. 25
0
 public boolean hasPermission(String permName) {
   if (permName != null) {
     for (Role r : roles) {
       if (r.hasPermission(permName)) return true;
     }
   }
   return false;
 }
Esempio n. 26
0
 /*
  * (non-Javadoc)
  *
  * @see
  * org.springframework.security.userdetails.UserDetails#getAuthorities()
  */
 @Override
 public Collection<GrantedAuthority> getAuthorities() {
   Collection<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();
   for (Role role : roles) {
     grantedAuthorities.add(new GrantedAuthorityImpl(role.getName()));
   }
   return grantedAuthorities;
 }
Esempio n. 27
0
 @JsonIgnore
 public List<String> getRoleIdList() {
   List<String> roleIdList = Lists.newArrayList();
   for (Role role : roleList) {
     roleIdList.add(role.getId());
   }
   return roleIdList;
 }
Esempio n. 28
0
 @Override
 public Collection<? extends GrantedAuthority> getAuthorities() {
   Set<SimpleGrantedAuthority> authorities = new HashSet<>();
   for (Role r : roles) {
     authorities.add(new SimpleGrantedAuthority(r.getName().toString()));
   }
   return Lists.newArrayList(new SimpleGrantedAuthority("ROLE_ADMIN"));
 }
Esempio n. 29
0
 public void setRoleIdList(List<String> roleIdList) {
   roleList = Lists.newArrayList();
   for (String roleId : roleIdList) {
     Role role = new Role();
     role.setId(roleId);
     roleList.add(role);
   }
 }
Esempio n. 30
0
 public static Role fromPersistentValue(String role) {
   for (Role r : values()) {
     if (r.getPersistentValue().equals(role)) {
       return r;
     }
   }
   return Role.UNDEFINED;
 }