예제 #1
0
 private String getUPN(DbUser user) {
   String retVal = user.getLoginName();
   if (!retVal.contains("@")) {
     retVal = retVal + "@" + user.getDomain();
   }
   return retVal;
 }
예제 #2
0
  private boolean runQuery(HttpServletResponse response, String sessionID) {
    boolean returnValue = false;

    log.debug("Calling ValidateSession query");

    VdcQueryReturnValue queryReturnValue =
        backend.runInternalQuery(
            VdcQueryType.ValidateSession, new VdcQueryParametersBase(sessionID));

    if (queryReturnValue != null) {
      returnValue = queryReturnValue.getSucceeded();

      if (returnValue) {
        DbUser user = queryReturnValue.getReturnValue();

        // We get the user name only in case the validation succeeded, and the user is an
        // administrator
        if (user.isAdmin()) {
          log.debug("Getting user name");
          printUPNToResponse(response, getUPN(user));
        } else {
          log.error("User '{}' is not authorized to perform operation", user.getLoginName());
          returnValue = false;
        }
      }
    } else {
      log.error("Got NULL from backend.RunQuery");
    }

    return returnValue;
  }
예제 #3
0
  public void remove() {
    if (getWindow() != null) {
      return;
    }

    ConfirmationModel model = new ConfirmationModel();
    setWindow(model);
    model.setTitle(ConstantsManager.getInstance().getConstants().removeUsersTitle());
    model.setHelpTag(HelpTag.remove_user);
    model.setHashName("remove_user"); // $NON-NLS-1$

    ArrayList<String> list = new ArrayList<String>();
    for (DbUser item : Linq.<DbUser>cast(getSelectedItems())) {
      list.add(item.getFirstName());
    }
    model.setItems(list);

    UICommand tempVar = new UICommand("OnRemove", this); // $NON-NLS-1$
    tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
    tempVar.setIsDefault(true);
    model.getCommands().add(tempVar);
    UICommand tempVar2 = new UICommand("Cancel", this); // $NON-NLS-1$
    tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel());
    tempVar2.setIsCancel(true);
    model.getCommands().add(tempVar2);
  }
예제 #4
0
  public void postOnAssignTags(Map<Guid, Boolean> attachedTags) {
    TagListModel model = (TagListModel) getWindow();
    ArrayList<Guid> userIds = new ArrayList<Guid>();
    ArrayList<Guid> grpIds = new ArrayList<Guid>();

    for (Object item : getSelectedItems()) {
      DbUser user = (DbUser) item;
      if (user.isGroup()) {
        grpIds.add(user.getId());
      } else {
        userIds.add(user.getId());
      }
    }

    // prepare attach/detach lists
    ArrayList<Guid> tagsToAttach = new ArrayList<Guid>();
    ArrayList<Guid> tagsToDetach = new ArrayList<Guid>();

    if (model.getItems() != null && ((ArrayList<TagModel>) model.getItems()).size() > 0) {
      ArrayList<TagModel> tags = (ArrayList<TagModel>) model.getItems();
      TagModel rootTag = tags.get(0);
      TagModel.recursiveEditAttachDetachLists(rootTag, attachedTags, tagsToAttach, tagsToDetach);
    }

    ArrayList<VdcActionParametersBase> usersToAttach = new ArrayList<VdcActionParametersBase>();
    ArrayList<VdcActionParametersBase> grpsToAttach = new ArrayList<VdcActionParametersBase>();
    for (Guid tag_id : tagsToAttach) {
      if (userIds.size() > 0) {
        usersToAttach.add(new AttachEntityToTagParameters(tag_id, userIds));
      }
      if (grpIds.size() > 0) {
        grpsToAttach.add(new AttachEntityToTagParameters(tag_id, grpIds));
      }
    }
    if (usersToAttach.size() > 0) {
      Frontend.getInstance().runMultipleAction(VdcActionType.AttachUserToTag, usersToAttach);
    }
    if (grpsToAttach.size() > 0) {
      Frontend.getInstance().runMultipleAction(VdcActionType.AttachUserGroupToTag, grpsToAttach);
    }

    ArrayList<VdcActionParametersBase> usersToDetach = new ArrayList<VdcActionParametersBase>();
    ArrayList<VdcActionParametersBase> grpsToDetach = new ArrayList<VdcActionParametersBase>();
    for (Guid tag_id : tagsToDetach) {
      if (userIds.size() > 0) {
        usersToDetach.add(new AttachEntityToTagParameters(tag_id, userIds));
      }
      if (grpIds.size() > 0) {
        grpsToDetach.add(new AttachEntityToTagParameters(tag_id, grpIds));
      }
    }
    if (usersToDetach.size() > 0) {
      Frontend.getInstance().runMultipleAction(VdcActionType.DetachUserFromTag, usersToDetach);
    }
    if (grpsToDetach.size() > 0) {
      Frontend.getInstance().runMultipleAction(VdcActionType.DetachUserGroupFromTag, grpsToDetach);
    }

    cancel();
  }
  private boolean detachUsers() {
    // check if this is a VM from a VM pool
    if (getVm().getVmPoolId() == null) {
      return false;
    }

    List<DbUser> users = getDbUserDAO().getAllForVm(getVmId());
    // check if this VM is attached to a user
    if (users == null || users.isEmpty()) {
      return false;
    }

    VmPool pool = getVmPoolDAO().get(getVm().getVmPoolId());
    if (pool != null && pool.getVmPoolType() == VmPoolType.Automatic) {
      // should be only one user in the collection
      for (DbUser dbUser : users) {
        runInternalActionWithTasksContext(
            VdcActionType.DetachUserFromVmFromPool,
            new VmPoolSimpleUserParameters(getVm().getVmPoolId(), dbUser.getId(), getVmId()),
            getLock());
      }

      return true;
    }

    return false;
  }
예제 #6
0
 @Override
 protected void updateDetailsAvailability() {
   if (getSelectedItem() != null) {
     DbUser adUser = (DbUser) getSelectedItem();
     userGroupListModel.setIsAvailable(!adUser.isGroup());
     userEventNotifierListModel.setIsAvailable(!adUser.isGroup());
   }
 }
예제 #7
0
 String getConsoleUserName() {
   DbUser user = getCurrentUser();
   String domain = user.getDomain();
   String name = user.getLoginName();
   if (StringUtils.isEmpty(name)) {
     return null;
   }
   if (name.contains("@") || StringUtils.isEmpty(domain)) {
     return name;
   }
   return name + "@" + domain;
 }
예제 #8
0
 /**
  * Run the following test case.
  *
  * <ol>
  *   <li>Attempt to log-off
  *   <li>Have the log-off succeed
  *   <li>Make sure the onSuccess handler is called
  *   <li>Make sure the onLogout handler is called
  * </ol>
  */
 @Test
 public void testLogoffAsync_success() {
   Object model = new Object();
   when(mockAsyncQuery.getModel()).thenReturn(model);
   DbUser testUser = new DbUser();
   testUser.setLoginName("testUser"); // $NON-NLS-1$
   frontend.logoffAsync(testUser, mockAsyncQuery);
   verify(mockService).logOff(eq(testUser), callbackAction.capture());
   VdcReturnValueBase returnValue = new VdcReturnValueBase();
   callbackAction.getValue().onSuccess(returnValue);
   verify(mockAsyncCallback).onSuccess(model, returnValue);
   verify(mockLoginHandler).onLogout();
 }
예제 #9
0
 /**
  * Run the following test case.
  *
  * <ol>
  *   <li>Attempt to log-off
  *   <li>Have the log-off fail with a status code of 0, which is an ignored failure
  *   <li>Check to make sure the callback is not called
  *   <li>Check to make sure the events handler is never called
  *   <li>Make sure the onSuccess handler is never called
  * </ol>
  */
 @Test
 public void testLogoffAsync_ignored_failure() {
   Object model = new Object();
   when(mockAsyncQuery.getModel()).thenReturn(model);
   DbUser testUser = new DbUser();
   testUser.setLoginName("testUser"); // $NON-NLS-1$
   frontend.logoffAsync(testUser, mockAsyncQuery);
   verify(mockService).logOff(eq(testUser), callbackAction.capture());
   StatusCodeException exception = new StatusCodeException(0, "0 status code"); // $NON-NLS-1$
   callbackAction.getValue().onFailure(exception);
   verify(mockFrontendFailureEvent, never()).raise(eq(Frontend.class), (EventArgs) any());
   verify(mockEventsHandler, never()).runQueryFailed(null);
   verify(mockAsyncCallback, never()).onSuccess(model, null);
 }
 @Override
 protected void addUsersToModel(VdcQueryReturnValue returnValue, Set<String> excludeUsers) {
   Iterable<DbUser> filteredUsers =
       Linq.where(
           (ArrayList<DbUser>) returnValue.getReturnValue(),
           new Linq.DbUserPredicate(getTargetDbUser()));
   for (DbUser dbUser : filteredUsers) {
     if (!excludeUsers.contains(dbUser.getExternalId())) {
       EntityModel tempVar2 = new EntityModel();
       tempVar2.setEntity(dbUser);
       getusers().add(tempVar2);
     }
   }
 }
예제 #11
0
  /**
   * Don't send the ticket to the virtual machine and send a warning indicating that two users are
   * trying to connect to the console of the virtual machine simultaneously.
   */
  private void dontSendTicket() {
    // Send messages to the log explaining the situation:
    final VM vm = getVm();
    final DbUser user = getCurrentUser();
    log.warn(
        "Can't give console of virtual machine '{}' to user '{}', it has probably been taken by another user.",
        vm.getId(),
        user.getId());

    // Set the result messages indicating that the operation failed:
    addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_VM_IN_USE_BY_OTHER_USER);

    // The command failed:
    setSucceeded(false);
  }
  /**
   * Validates the notification method.
   *
   * @param eventNotificationMethod The eventNotificationMethods.
   * @param eventSubscriber The eventSubscriber.
   * @param user The user.
   */
  protected boolean validateNotificationMethod(
      EventNotificationMethod eventNotificationMethod,
      EventSubscriber eventSubscriber,
      DbUser user) {
    boolean retValue = true;
    EventNotificationMethod notificationMethod = eventNotificationMethod;

    switch (notificationMethod) {
      case SMTP:
        String mailAddress =
            StringUtils.isEmpty(eventSubscriber.getMethodAddress())
                ? user.getEmail()
                : eventSubscriber.getMethodAddress();

        if (!isEmailValid(mailAddress)) {
          addValidationMessage(EngineMessage.USER_DOES_NOT_HAVE_A_VALID_EMAIL);
          retValue = false;
        }
        break;
      default:
        addValidationMessage(EngineMessage.EN_UNKNOWN_NOTIFICATION_METHOD);
        retValue = false;
        break;
    }
    return retValue;
  }
예제 #13
0
 private DbUser addUser(DbUser dbUser) {
   // Try to add the user with the external id:
   if (dbUser.getDomain() != null && dbUser.getExternalId() != null) {
     AddUserParameters parameters = new AddUserParameters(dbUser);
     VdcReturnValueBase result =
         runInternalAction(VdcActionType.AddUser, parameters, cloneContextAndDetachFromParent());
     if (result.getCanDoAction()) {
       Guid id = (Guid) result.getActionReturnValue();
       if (id != null) {
         return getDbUserDAO().get(id);
       }
       return null;
     }
   }
   // There is no such user in the directory:
   return null;
 }
예제 #14
0
  @Override
  protected void perform() {
    // Generate the ticket if needed (in some situations the client will not send
    // a ticket):
    if (StringUtils.isEmpty(ticket)) {
      ticket = Ticketing.generateOTP();
    }

    // Update the dynamic information of the virtual machine in memory (we need it
    // to update the database later):
    final VM vm = getVm();
    final DbUser user = getCurrentUser();
    vm.setConsoleUserId(user.getId());
    vm.setConsoleCurrentUserName(getConsoleUserName());

    // If the virtual machine has the allow reconnect flag or the user
    // needed additional permissions to connect to the console then we just
    // have to save the user id to the database, regardless of what was
    // there before and without locking.
    //
    // Note that the fact that the user needed permissions actually means
    // that it has them, otherwise we will not be here, performing the
    // operation.
    //
    // In any other situation we try to save the new user to the database
    // and proceed only if the previous user in the database is null. This
    // is needed to prevent races between different users trying to access
    // the console of the same virtual machine simultaneously.
    final VmDynamicDao dao = DbFacade.getInstance().getVmDynamicDao();
    if (vm.getAllowConsoleReconnect() || neededPermissions) {
      dao.update(vm.getDynamicData());
      sendTicket();
    } else {
      final boolean saved = dao.updateConsoleUserWithOptimisticLocking(vm.getDynamicData());
      if (saved) {
        sendTicket();
      } else {
        dontSendTicket();
      }
    }
  }
예제 #15
0
  public void onRemove() {
    ArrayList<DbUser> items = Linq.<DbUser>cast(getSelectedItems());

    ArrayList<VdcActionParametersBase> userPrms = new ArrayList<VdcActionParametersBase>();
    ArrayList<VdcActionParametersBase> groupPrms = new ArrayList<VdcActionParametersBase>();
    for (DbUser item : items) {
      if (!item.isGroup()) {
        userPrms.add(new IdParameters(item.getId()));
      } else {
        groupPrms.add(new IdParameters(item.getId()));
      }
    }

    if (userPrms.size() > 0) {
      Frontend.getInstance().runMultipleAction(VdcActionType.RemoveUser, userPrms);
    }

    if (groupPrms.size() > 0) {
      Frontend.getInstance().runMultipleAction(VdcActionType.RemoveGroup, groupPrms);
    }

    cancel();
  }
예제 #16
0
  /**
   * Send a previously generated ticket to the virtual machine. If sending the ticket fails the
   * command will be marked as failed.
   */
  private void sendTicket() {
    // Send the ticket to the virtual machine:
    final DbUser user = getCurrentUser();
    final boolean sent =
        runVdsCommand(
                VDSCommandType.SetVmTicket,
                new SetVmTicketVDSCommandParameters(
                    getVdsId(),
                    getVmId(),
                    ticket,
                    getParameters().getValidTime(),
                    user.getLoginName(),
                    user.getId(),
                    getParameters().getGraphicsType(),
                    getVm().getConsoleDisconnectAction()))
            .getSucceeded();

    // Return the ticket only if sending it to the virtual machine succeeded:
    if (sent) {
      setActionReturnValue(ticket);
    }
    setSucceeded(sent);
  }
  @Override
  protected void addGroupsToModel(VdcQueryReturnValue returnValue, Set<String> excludeUsers) {
    Iterable<DbGroup> filteredGroups =
        Linq.where(
            (ArrayList<DbGroup>) returnValue.getReturnValue(),
            new Linq.DbGroupPredicate(getTargetDbGroup()));

    for (DbGroup group : filteredGroups) {
      if (!excludeUsers.contains(group.getId().toString())) {
        DbUser dbUser = new DbUser();
        dbUser.setExternalId(group.getExternalId());
        dbUser.setFirstName(group.getName());
        dbUser.setLastName(""); // $NON-NLS-1$
        dbUser.setLoginName(""); // $NON-NLS-1$
        dbUser.setDomain(group.getDomain());
        dbUser.setNamespace(group.getNamespace());

        EntityModel entity = new EntityModel();
        entity.setEntity(dbUser);
        getgroups().add(entity);
      }
    }
  }
예제 #18
0
  private void onAdd() {
    AdElementListModel model = (AdElementListModel) getWindow();

    if (model.getProgress() != null) {
      return;
    }

    if (!model.getIsEveryoneSelected() && model.getSelectedItems() == null) {
      cancel();
      return;
    }

    ArrayList<DbUser> items = new ArrayList<DbUser>();
    if (model.getIsEveryoneSelected()) {
      DbUser tempVar = new DbUser();
      tempVar.setId(ApplicationGuids.everyone.asGuid());
      items.add(tempVar);
    } else {
      for (Object item : model.getItems()) {
        EntityModel entityModel = (EntityModel) item;
        if (entityModel.getIsSelected()) {
          items.add((DbUser) entityModel.getEntity());
        }
      }
    }

    Role role = (Role) model.getRole().getSelectedItem();
    // adGroup/user

    ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>();
    for (DbUser user : items) {
      Permissions tempVar2 = new Permissions();
      tempVar2.setad_element_id(user.getId());
      tempVar2.setrole_id(role.getId());
      Permissions perm = tempVar2;
      perm.setObjectId(getEntityGuid());
      perm.setObjectType(this.getObjectType());

      if (user.isGroup()) {
        DbGroup group = new DbGroup();
        group.setId(user.getId());
        group.setExternalId(user.getExternalId());
        group.setName(user.getFirstName());
        group.setDomain(user.getDomain());
        group.setNamespace(user.getNamespace());
        PermissionsOperationsParameters tempVar3 = new PermissionsOperationsParameters();
        tempVar3.setPermission(perm);
        tempVar3.setGroup(group);
        list.add(tempVar3);
      } else {
        PermissionsOperationsParameters tempVar4 = new PermissionsOperationsParameters();
        tempVar4.setPermission(perm);
        tempVar4.setUser(user);
        list.add(tempVar4);
      }
    }

    model.startProgress(null);

    Frontend.getInstance()
        .runMultipleAction(
            VdcActionType.AddPermission,
            list,
            new IFrontendMultipleActionAsyncCallback() {
              @Override
              public void executed(FrontendMultipleActionAsyncResult result) {

                AdElementListModel localModel = (AdElementListModel) result.getState();
                localModel.stopProgress();
                cancel();
              }
            },
            model);
  }
 private DbUser getTargetDbUser() {
   DbUser dbUser = new DbUser();
   dbUser.setLoginName(getSearchString());
   dbUser.setDomain((getProfile().getSelectedItem()).getAuthz());
   return dbUser;
 }
예제 #20
0
  public void onAdd() {
    AdElementListModel model = (AdElementListModel) getWindow();

    if (model.getProgress() != null) {
      return;
    }

    if (model.getSelectedItems() == null) {
      cancel();
      return;
    }

    ArrayList<DbUser> items = new ArrayList<DbUser>();
    for (Object item : model.getItems()) {
      EntityModel entityModel = (EntityModel) item;
      if (entityModel.getIsSelected()) {
        items.add((DbUser) entityModel.getEntity());
      }
    }

    ArrayList<VdcActionType> actionsList = new ArrayList<VdcActionType>(items.size());
    ArrayList<VdcActionParametersBase> parametersList =
        new ArrayList<VdcActionParametersBase>(items.size());
    VdcActionParametersBase parameters = null;
    for (DbUser item : items) {
      if (item.isGroup()) {
        actionsList.add(VdcActionType.AddGroup);
        DbGroup grp = new DbGroup();
        grp.setExternalId(item.getExternalId());
        grp.setName(item.getFirstName());
        grp.setNamespace(item.getNamespace());
        grp.setId(item.getId());
        grp.setDomain(item.getDomain());
        grp.setActive(item.isActive());
        parameters = new AddGroupParameters(grp);
      } else {
        actionsList.add(VdcActionType.AddUser);
        parameters = new AddUserParameters(item);
      }
      parametersList.add(parameters);
    }

    model.startProgress(null);

    IFrontendActionAsyncCallback nopCallback =
        new IFrontendActionAsyncCallback() {
          @Override
          public void executed(FrontendActionAsyncResult result) {
            // Nothing.
          }
        };

    IFrontendActionAsyncCallback lastCallback =
        new IFrontendActionAsyncCallback() {
          @Override
          public void executed(FrontendActionAsyncResult result) {
            AdElementListModel localModel = (AdElementListModel) result.getState();
            localModel.stopProgress();
            cancel();
          }
        };

    ArrayList<IFrontendActionAsyncCallback> callbacksList =
        new ArrayList<IFrontendActionAsyncCallback>(items.size());
    for (int i = 1; i < items.size(); i++) {
      callbacksList.add(nopCallback);
    }
    callbacksList.add(lastCallback);

    Frontend.getInstance()
        .runMultipleActions(actionsList, parametersList, callbacksList, lastCallback, model);
  }
예제 #21
0
  @Override
  protected void executeCommand() {
    // Get the parameters:
    T parameters = getParameters();

    // The user or group given in the parameters may haven't been added to the database yet, if this
    // is the case
    // then they need to be added to the database now, before the permission:
    DbUser user = parameters.getUser();
    if (user != null) {
      Guid id = user.getId();
      String directory = user.getDomain();
      String externalId = user.getExternalId();
      DbUser existing = getDbUserDAO().getByIdOrExternalId(id, directory, externalId);
      if (existing != null) {
        user = existing;
      } else {
        user = addUser(user);
        if (user == null) {
          setSucceeded(false);
          return;
        }
      }
    }
    DbGroup group = parameters.getGroup();
    if (group != null) {
      Guid id = group.getId();
      String directory = group.getDomain();
      String externalId = group.getExternalId();
      DbGroup existing = getAdGroupDAO().getByIdOrExternalId(id, directory, externalId);
      if (existing != null) {
        group = existing;
      } else {
        group = addGroup(group);
        if (group == null) {
          setSucceeded(false);
          return;
        }
      }
    }

    // The identifier of the principal of the permission can come from the parameters directly or
    // from the
    // user/group objects:
    Guid principalId;
    if (user != null) {
      principalId = user.getId();
    } else if (group != null) {
      principalId = group.getId();
    } else {
      principalId = parameters.getPermission().getad_element_id();
    }

    final Permissions paramPermission = parameters.getPermission();

    Permissions permission =
        getPermissionDAO()
            .getForRoleAndAdElementAndObject(
                paramPermission.getrole_id(), principalId, paramPermission.getObjectId());

    if (permission == null) {
      paramPermission.setId(Guid.newGuid());
      paramPermission.setad_element_id(principalId);

      TransactionSupport.executeInNewTransaction(
          new TransactionMethod<Void>() {
            @Override
            public Void runInTransaction() {
              getPermissionDAO().save(paramPermission);
              getCompensationContext().snapshotNewEntity(paramPermission);
              getCompensationContext().stateChanged();
              return null;
            }
          });
      permission = paramPermission;
    }

    getReturnValue().setActionReturnValue(permission.getId());

    if (user != null) {
      updateAdminStatus(permission);
    }
    setSucceeded(true);
  }
  private void onAttach() {
    AdElementListModel model = (AdElementListModel) getWindow();

    if (model.getProgress() != null) {
      return;
    }

    if (model.getSelectedItems() == null) {
      cancel();
      return;
    }

    ArrayList<DbUser> items = new ArrayList<DbUser>();
    for (Object item : model.getItems()) {
      EntityModel entityModel = (EntityModel) item;
      if (entityModel.getIsSelected()) {
        items.add((DbUser) entityModel.getEntity());
      }
    }

    Role role = model.getRole().getSelectedItem();

    ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>();
    for (DbUser user : items) {
      Permission perm = new Permission(user.getId(), role.getId(), null, null);

      if (user.isGroup()) {
        DbGroup group = new DbGroup();
        group.setId(user.getId());
        group.setName(user.getFirstName());
        group.setDomain(user.getDomain());
        group.setExternalId(user.getExternalId());
        group.setNamespace(user.getNamespace());
        PermissionsOperationsParameters tempVar2 = new PermissionsOperationsParameters();
        tempVar2.setPermission(perm);
        tempVar2.setGroup(group);
        list.add(tempVar2);
      } else {
        PermissionsOperationsParameters tempVar3 = new PermissionsOperationsParameters();
        tempVar3.setPermission(perm);
        tempVar3.setUser(user);
        list.add(tempVar3);
      }
    }

    model.startProgress(null);

    Frontend.getInstance()
        .runMultipleAction(
            VdcActionType.AddSystemPermission,
            list,
            new IFrontendMultipleActionAsyncCallback() {
              @Override
              public void executed(FrontendMultipleActionAsyncResult result) {

                AdElementListModel localModel = (AdElementListModel) result.getState();
                localModel.stopProgress();
                cancel();
              }
            },
            model);
  }
예제 #23
0
 protected Guid getUserID() {
   if (user == null) {
     return null;
   }
   return user.getId();
 }
예제 #24
0
  public static List<DbUser> sync(List<DbUser> dbUsers) {
    List<DbUser> usersToUpdate = new ArrayList<>();
    Map<String, Map<String, Set<String>>> authzToNamespaceToUserIds = new HashMap<>();
    Map<String, List<DbUser>> dbUsersPerAuthz = new HashMap<>();

    // Initialize the entries based on authz in the map
    for (DbUser dbUser : dbUsers) {
      MultiValueMapUtils.addToMap(dbUser.getDomain(), dbUser, dbUsersPerAuthz);
      if (!authzToNamespaceToUserIds.containsKey(dbUser.getDomain())) {
        authzToNamespaceToUserIds.put(dbUser.getDomain(), new HashMap<String, Set<String>>());
      }
      MultiValueMapUtils.addToMapOfSets(
          dbUser.getNamespace(),
          dbUser.getExternalId(),
          authzToNamespaceToUserIds.get(dbUser.getDomain()));
    }

    for (Entry<String, Map<String, Set<String>>> entry : authzToNamespaceToUserIds.entrySet()) {
      Map<String, DbUser> activeUsers = new HashMap<>();
      String authz = entry.getKey();
      try {
        ExtensionProxy authzExtension =
            EngineExtensionsManager.getInstance().getExtensionByName(authz);
        for (Entry<String, Set<String>> userIdsPerNamespace : entry.getValue().entrySet()) {
          for (ExtMap principal :
              AuthzUtils.fetchPrincipalsByIdsRecursively(
                  authzExtension, userIdsPerNamespace.getKey(), userIdsPerNamespace.getValue())) {
            DirectoryUtils.flatGroups(principal);
            DbUser dbUser = DirectoryUtils.mapPrincipalRecordToDbUser(authz, principal);
            dbUser.setGroupIds(DirectoryUtils.getGroupIdsFromPrincipal(authz, principal));
            activeUsers.put(dbUser.getExternalId(), dbUser);
          }
        }

        for (DbUser dbUser : dbUsersPerAuthz.get(authz)) {
          DbUser activeUser = activeUsers.get(dbUser.getExternalId());
          if (activeUser != null) {
            if (!activeUser.equals(dbUser)) {
              activeUser.setId(dbUser.getId());
              activeUser.setAdmin(dbUser.isAdmin());
              log.infoFormat(
                  "Principal {0}::{1} synchronized",
                  activeUser.getLoginName(), activeUser.getDomain());
              usersToUpdate.add(activeUser);
            }
          } else {
            log.infoFormat(
                "Deactivating non existing principal {0}::{1}",
                dbUser.getLoginName(), dbUser.getDomain());
            dbUser.setActive(false);
            usersToUpdate.add(dbUser);
          }
        }
      } catch (Exception ex) {
        log.errorFormat(
            "Error during user synchronization of extension {0}. Exception message is {1}",
            authz, ex.getMessage());
        log.debug("", ex);
      }
    }
    return usersToUpdate;
  }
예제 #25
0
  private void getAttachedTagsToSelectedUsers(TagListModel model) {
    ArrayList<Guid> userIds = new ArrayList<Guid>();
    ArrayList<Guid> grpIds = new ArrayList<Guid>();

    attachedTagsToEntities = new HashMap<Guid, Boolean>();
    allAttachedTags = new ArrayList<Tags>();
    selectedItemsCounter = 0;

    for (Object item : getSelectedItems()) {
      DbUser user = (DbUser) item;
      if (!user.isGroup()) {
        userIds.add(user.getId());
      } else {
        grpIds.add(user.getId());
      }
    }

    for (Guid userId : userIds) {
      AsyncDataProvider.getInstance()
          .getAttachedTagsToUser(
              new AsyncQuery(
                  new Object[] {this, model},
                  new INewAsyncCallback() {
                    @Override
                    public void onSuccess(Object target, Object returnValue) {

                      Object[] array = (Object[]) target;
                      UserListModel userListModel = (UserListModel) array[0];
                      TagListModel tagListModel = (TagListModel) array[1];
                      userListModel.allAttachedTags.addAll((ArrayList<Tags>) returnValue);
                      userListModel.selectedItemsCounter++;
                      if (userListModel.selectedItemsCounter
                          == userListModel.getSelectedItems().size()) {
                        postGetAttachedTags(userListModel, tagListModel);
                      }
                    }
                  }),
              userId);
    }
    for (Guid grpId : grpIds) {
      AsyncDataProvider.getInstance()
          .getAttachedTagsToUserGroup(
              new AsyncQuery(
                  new Object[] {this, model},
                  new INewAsyncCallback() {
                    @Override
                    public void onSuccess(Object target, Object returnValue) {

                      Object[] array = (Object[]) target;
                      UserListModel userListModel = (UserListModel) array[0];
                      TagListModel tagListModel = (TagListModel) array[1];
                      userListModel.allAttachedTags.addAll((ArrayList<Tags>) returnValue);
                      userListModel.selectedItemsCounter++;
                      if (userListModel.selectedItemsCounter
                          == userListModel.getSelectedItems().size()) {
                        postGetAttachedTags(userListModel, tagListModel);
                      }
                    }
                  }),
              grpId);
    }
  }