public Membership findMembership(String id) throws Exception {
    if (log.isTraceEnabled()) {
      Tools.logMethodIn(log, LogLevel.TRACE, "findMembership", new Object[] {"id", id});
    }

    orgService.flush();

    Membership m = new MembershipImpl(id);

    String plGroupName = getPLIDMGroupName(getGroupNameFromId(m.getGroupId()));

    String groupId =
        getIdentitySession()
            .getPersistenceManager()
            .createGroupKey(plGroupName, getGroupTypeFromId(m.getGroupId()));

    try {
      if (isCreateMembership(m.getMembershipType(), m.getGroupId())
          && getIdentitySession()
              .getRoleManager()
              .hasRole(m.getUserName(), groupId, m.getMembershipType())) {
        if (log.isTraceEnabled()) {
          Tools.logMethodOut(log, LogLevel.TRACE, "findMembership", m);
        }
        return m;
      }
    } catch (Exception e) {
      // TODO:
      handleException("Identity operation error: ", e);
    }

    try {
      if (isAssociationMapped()
          && getAssociationMapping().equals(m.getMembershipType())
          && getIdentitySession()
              .getRelationshipManager()
              .isAssociatedByKeys(groupId, m.getUserName())) {
        if (log.isTraceEnabled()) {
          Tools.logMethodOut(log, LogLevel.TRACE, "findMembership", m);
        }

        return m;
      }
    } catch (Exception e) {
      // TODO:
      handleException("Identity operation error: ", e);
    }

    if (log.isTraceEnabled()) {
      Tools.logMethodOut(log, LogLevel.TRACE, "findMembership", null);
    }

    return null;
  }
Example #2
0
  /** {@inheritDoc} */
  public void createMembership(Membership m, boolean broadcast) throws Exception {
    if (orgService.getMembershipTypeHandler().findMembershipType(m.getMembershipType()) == null) {
      throw new InvalidNameException(
          "Can not create membership record "
              + m.getId()
              + ", because membership"
              + "type "
              + m.getMembershipType()
              + " does not exist.");
    }

    if (orgService.getGroupHandler().findGroupById(m.getGroupId()) == null) {
      throw new InvalidNameException(
          "Can not create membership record "
              + m.getId()
              + ", because group "
              + m.getGroupId()
              + " does not exist.");
    }

    if (orgService.getUserHandler().findUserByName(m.getUserName()) == null) {
      throw new InvalidNameException(
          "Can not create membership record "
              + m.getId()
              + ", because user "
              + m.getGroupId()
              + " does not exist.");
    }

    // check if we already have membership record
    if (findMembershipByUserGroupAndType(m.getUserName(), m.getGroupId(), m.getMembershipType())
        != null) {
      return;
    }

    if (broadcast) {
      preSave(m, true);
    }

    Session session = service_.openSession();
    session.save(m);
    session.flush();

    if (broadcast) {
      postSave(m, true);
    }
  }
 private MembershipUser toMembershipUser(Membership membership) throws Exception {
   OrganizationService service = getApplicationComponent(OrganizationService.class);
   String userName = membership.getUserName();
   UserHandler handler = service.getUserHandler();
   User user = handler.findUserByName(userName);
   if (user == null) return null;
   return new MembershipUser(user, membership.getMembershipType(), membership.getId());
 }
Example #4
0
  public void postSave(Membership m, boolean isNew) throws Exception {

    String username = m.getUserName();
    String groupId = m.getGroupId();
    cservice_.addUserContactInAddressBook(username, groupId);
    DataStorage storage_ = new JCRDataStorage(nodeHierarchyCreator_, reposervice_);
    SessionProvider systemSession = SessionProvider.createSystemProvider();
    try {
      String usersPath = nodeHierarchyCreator_.getJcrPath(DataStorage.USERS_PATH);
      Contact contact = cservice_.getPublicContact(username);
      QueryManager qm = getSession(systemSession).getWorkspace().getQueryManager();
      Map<String, String> groups = new LinkedHashMap<String, String>();
      for (String group : contact.getAddressBookIds()) groups.put(group, group);
      groups.put(groupId, groupId);
      contact.setAddressBookIds(groups.keySet().toArray(new String[] {}));
      cservice_.saveContact(username, contact, false);
      StringBuffer queryString =
          new StringBuffer(
                  "/jcr:root"
                      + usersPath
                      + "//element(*,exo:contactGroup)[@exo:viewPermissionGroups='")
              .append(groupId + "']");
      Query query = qm.createQuery(queryString.toString(), Query.XPATH);
      QueryResult result = query.execute();
      NodeIterator nodes = result.getNodes();
      List<String> to = Arrays.asList(new String[] {username});
      while (nodes.hasNext()) {
        Node address = nodes.nextNode();
        String from = address.getProperty("exo:sharedUserId").getString();
        String addressBookId = address.getProperty("exo:id").getString();
        storage_.shareAddressBook(from, addressBookId, to);
      }
      queryString =
          new StringBuffer(
                  "/jcr:root" + usersPath + "//element(*,exo:contact)[@exo:viewPermissionGroups='")
              .append(groupId + "']");
      query = qm.createQuery(queryString.toString(), Query.XPATH);
      result = query.execute();
      nodes = result.getNodes();
      while (nodes.hasNext()) {
        Node contactNode = nodes.nextNode();
        String split = "/";
        String temp = contactNode.getPath().split(usersPath)[1];
        String userId = temp.split(split)[1];
        String[] addressBookIds = new String[] {contactNode.getProperty("exo:id").getString()};
        storage_.shareContact(userId, addressBookIds, to);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      systemSession.close();
    }
  }
Example #5
0
 public void write(OutputStream out) throws IOException {
   try {
     XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
     outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
     XMLStreamWriter xsw = outputFactory.createXMLStreamWriter(out);
     xsw.writeStartDocument();
     xsw.writeStartElement("membership");
     xsw.writeDefaultNamespace(XMLContants.EXO_NAMESPACE_URL);
     xsw.writeNamespace(XMLContants.XLINK_PREFIX, XMLContants.XLINK_NAMESPACE_URL);
     xsw.writeAttribute(
         XMLContants.XLINK_NAMESPACE_URL,
         XMLContants.XLINK_HREF,
         baseURI_
             + "/organization/membership/"
             + membership_.getId()
             + "/?output=xml&command=view");
     xsw.writeStartElement("id");
     xsw.writeCharacters(membership_.getId());
     xsw.writeEndElement();
     xsw.writeStartElement("group-id");
     xsw.writeCharacters(membership_.getGroupId());
     xsw.writeEndElement();
     xsw.writeStartElement("user-name");
     xsw.writeCharacters(membership_.getUserName());
     xsw.writeEndElement();
     xsw.writeStartElement("membership-type");
     xsw.writeCharacters(membership_.getMembershipType());
     xsw.writeEndElement();
     xsw.writeEndDocument();
     xsw.flush();
     xsw.close();
   } catch (Exception e) {
     e.printStackTrace();
     throw new IOException(e.getMessage());
   }
 }
Example #6
0
  public void preDelete(Membership m) throws Exception {
    Contact contact = cservice_.getPublicContact(m.getUserName());
    Map<String, String> groupIds = new LinkedHashMap<String, String>();
    for (String group : contact.getAddressBookIds()) groupIds.put(group, group);
    groupIds.remove(m.getGroupId());
    contact.setAddressBookIds(groupIds.keySet().toArray(new String[] {}));
    SessionProvider systemSession = SessionProvider.createSystemProvider();
    try {
      cservice_.saveContact(m.getUserName(), contact, false);
      DataStorage storage_ = new JCRDataStorage(nodeHierarchyCreator_, reposervice_);
      String usersPath = nodeHierarchyCreator_.getJcrPath(DataStorage.USERS_PATH);
      QueryManager qm = getSession(systemSession).getWorkspace().getQueryManager();
      StringBuffer queryString =
          new StringBuffer(
                  "/jcr:root"
                      + usersPath
                      + "//element(*,exo:contactGroup)[@exo:viewPermissionGroups='")
              .append(m.getGroupId() + "']");
      Query query = qm.createQuery(queryString.toString(), Query.XPATH);
      QueryResult result = query.execute();
      NodeIterator nodes = result.getNodes();
      while (nodes.hasNext()) {
        Node address = nodes.nextNode();
        storage_.unshareAddressBook(
            address.getProperty("exo:sharedUserId").getString(),
            address.getProperty("exo:id").getString(),
            m.getUserName());
        for (Value groupShared : address.getProperty("exo:viewPermissionGroups").getValues()) {
          if (groupIds.keySet().contains(groupShared.getString())) {
            List<String> reciever = new ArrayList<String>();
            reciever.add(m.getUserName());
            storage_.shareAddressBook(
                address.getProperty("exo:sharedUserId").getString(),
                address.getProperty("exo:id").getString(),
                reciever);
          }
        }
      }
      queryString =
          new StringBuffer(
                  "/jcr:root" + usersPath + "//element(*,exo:contact)[@exo:viewPermissionGroups='")
              .append(m.getGroupId() + "']");
      query = qm.createQuery(queryString.toString(), Query.XPATH);
      result = query.execute();
      nodes = result.getNodes();
      while (nodes.hasNext()) {
        Node contactNode = nodes.nextNode();
        String split = "/";
        String temp = contactNode.getPath().split(usersPath)[1];
        String userId = temp.split(split)[1];
        storage_.removeUserShareContact(
            userId, contactNode.getProperty("exo:id").getString(), m.getUserName());
        for (Value groupShared : contactNode.getProperty("exo:viewPermissionGroups").getValues()) {
          if (groupIds.keySet().contains(groupShared.getString())) {
            List<String> reciever = new ArrayList<String>();
            reciever.add(m.getUserName());
            storage_.shareContact(
                userId, new String[] {contactNode.getProperty("exo:id").getString()}, reciever);
          }
        }
      }
    } catch (ReferentialIntegrityException e) {

    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      systemSession.close();
    }
  }
  public Membership removeMembership(String id, boolean broadcast) throws Exception {
    if (log.isTraceEnabled()) {
      Tools.logMethodIn(
          log, LogLevel.TRACE, "removeMembership", new Object[] {"id", id, "broadcast", broadcast});
    }

    orgService.flush();

    Membership m = null;
    try {
      m = new MembershipImpl(id);
    } catch (ArrayIndexOutOfBoundsException e) {
      // If MembershipID is not valid with format 'membershipType:username:groupId'
      // It is seemed as membership not exist
      return null;
    }

    String plGroupName = getPLIDMGroupName(getGroupNameFromId(m.getGroupId()));

    String groupId =
        getIdentitySession()
            .getPersistenceManager()
            .createGroupKey(plGroupName, getGroupTypeFromId(m.getGroupId()));

    boolean hasRole = false;

    try {
      hasRole =
          getIdentitySession()
              .getRoleManager()
              .hasRole(m.getUserName(), groupId, m.getMembershipType());
    } catch (Exception e) {
      // TODO:
      handleException("Identity operation error: ", e);
    }

    boolean associated = false;

    try {
      associated =
          getIdentitySession()
              .getRelationshipManager()
              .isAssociatedByKeys(groupId, m.getUserName());
    } catch (Exception e) {
      // TODO:
      handleException("Identity operation error: ", e);
    }

    if (!hasRole
        && !(isAssociationMapped()
            && getAssociationMapping().equals(m.getMembershipType())
            && associated)) {
      // As test case expect, if meembership does not exist
      // This method should return null
      return null;
      // return m;
    }

    if (broadcast) {
      preDelete(m);
    }

    if (isCreateMembership(m.getMembershipType(), m.getGroupId())) {

      try {
        getIdentitySession()
            .getRoleManager()
            .removeRole(m.getMembershipType(), m.getUserName(), groupId);
      } catch (Exception e) {
        // TODO:
        handleException("Identity operation error: ", e);
      }
    }

    if (isAssociationMapped()
        && getAssociationMapping().equals(m.getMembershipType())
        && associated) {
      Set<String> keys = new HashSet<String>();
      keys.add(m.getUserName());
      try {
        getIdentitySession().getRelationshipManager().disassociateUsersByKeys(groupId, keys);
      } catch (Exception e) {
        // TODO:
        handleException("Identity operation error: ", e);
      }
    }

    if (broadcast) {
      postDelete(m);
    }
    return m;
  }
  public void saveMembership(Membership m, boolean broadcast) throws Exception {
    if (log.isTraceEnabled()) {
      Tools.logMethodIn(
          log,
          LogLevel.TRACE,
          "saveMembership",
          new Object[] {"membership", m, "broadcast", broadcast});
    }

    orgService.flush();

    String plGroupName = getPLIDMGroupName(getGroupNameFromId(m.getGroupId()));

    String groupId =
        getIdentitySession()
            .getPersistenceManager()
            .createGroupKey(plGroupName, getGroupTypeFromId(m.getGroupId()));

    boolean hasRole = false;

    try {
      hasRole =
          getIdentitySession()
              .getRoleManager()
              .hasRole(m.getUserName(), groupId, m.getMembershipType());
    } catch (Exception e) {
      // TODO:
      handleException("Identity operation error: ", e);
    }

    if (hasRole) {
      return;
    }

    if (broadcast) {
      preSave(m, false);
    }

    if (isCreateMembership(m.getMembershipType(), m.getGroupId())) {

      try {
        getIdentitySession()
            .getRoleManager()
            .createRole(m.getMembershipType(), m.getUserName(), groupId);
      } catch (Exception e) {
        // TODO:
        handleException("Identity operation error: ", e);
      }
    }
    if (isAssociationMapped() && getAssociationMapping().equals(m.getMembershipType())) {
      try {
        getIdentitySession().getRelationshipManager().associateUserByKeys(groupId, m.getUserName());
      } catch (Exception e) {
        // TODO:
        handleException("Identity operation error: ", e);
      }
    }

    if (broadcast) {
      postSave(m, false);
    }
  }