cancel
Showing results for 
Search instead for 
Did you mean: 

How to create group and add users to group using WebService?

madhurao
Champ in-the-making
Champ in-the-making
Hi Friends,
I am new Alfresco.I am using Web Service(WS) api for my development. Using WS api I can create space, create a user, upload file, create file and assign role to the user. But i could not able to find out any methods to create Group and add users to groups. If you have snippet of code, please share which helps to me understand very quickly.its very urgent .

Regards,
Madhu
19 REPLIES 19

dynamolalit
Champ on-the-rise
Champ on-the-rise
No.Still i am searching for same.Have you got anything?

prateekgoyal
Champ in-the-making
Champ in-the-making
Hello Evereyone,
I have a way to assign role to the user like


ACE [] ace = new ACE[4];
ace[0]=new ACE("testUser","Editor",status);
ace[1]=new ACE("testUser","Collaborator",status);
ace[2]=new ACE("testUser","Contributor",status);
ace[3]=new ACE("testUser","Coordinator",status);
accessService.addACEs(predicateacl, ace);

status is "acepted"
But i'm searching a way to assign role to the Group, but did'nt get it.
Did anyone know this.

openpj
Elite Collaborator
Elite Collaborator
Try to specify for the authority the group prefix "GROUP_", in this way:

ace[0]=new ACE("GROUP_"+youGroupName,"Editor",status);
Hope this helps.

prateekgoyal
Champ in-the-making
Champ in-the-making
Hey thanks for the reply, it worked   Smiley Happy

ivan_a
Champ in-the-making
Champ in-the-making
Here's the code .NET (C#) to create groups and add users using WebService
I hope you find it useful


private static bool CreateGroup(string nombreGrupo, bool variosgrupos, string[] nombresGrupos)
        {
            String GROUP_AUTHORITY_TYPE = "GROUP";
            if (!variosgrupos)
            {
                try
                {
                    //Crea prefijo y nombre de grupo
                    String CONTENT_PROVIDER_GROUPNAME = nombreGrupo;

                    //Añade propiedades a NewAuthority
                    NewAuthority cpGrpAuth = new NewAuthority();
                    cpGrpAuth.authorityType = GROUP_AUTHORITY_TYPE;
                    cpGrpAuth.name = CONTENT_PROVIDER_GROUPNAME;
                    //Crea nuevo array de NewAuthority y le agrega el grupo a crear
                    NewAuthority[] newAuthorities = new NewAuthority[1];
                    newAuthorities[0] = cpGrpAuth;
                    //Hace la llamada al metodo para crear el o los grupos
                    String[] result = accessService.createAuthorities(null, newAuthorities);
                }
                catch
                {
                    return false;
                }
            }
            else
            {
                try
                {
                    NewAuthority[] newAuthorities = new NewAuthority[nombresGrupos.Length];
                    for (int i = 0; i < nombresGrupos.Length; i++)
                    {
                        //Crea prefijo y nombre de grupo
                       
                        String CONTENT_PROVIDER_GROUPNAME = nombresGrupos[i];

                        //Añade propiedades a NewAuthority
                        NewAuthority cpGrpAuth = new NewAuthority();
                        cpGrpAuth.authorityType = GROUP_AUTHORITY_TYPE;
                        cpGrpAuth.name = CONTENT_PROVIDER_GROUPNAME;
                        //Crea nuevo array de NewAuthority y le agrega el grupo a crear
                        newAuthorities[i] = cpGrpAuth;
                    }
                    //Hace la llamada al metodo para crear el o los grupos
                    String[] result = accessService.createAuthorities(null, newAuthorities);
                }
                catch
                {
                    return false;
                }
               
            }
            return true;
        }

        private static bool AddUsertoGroup(string usuario, string grupo, bool variosUsuarios, string[] usuarios)
        {
            String GROUP_AUTHORITY_TYPE = "GROUP";
            String CONTENT_PROVIDER_GROUPNAME = grupo;
            String parentAuthority = GROUP_AUTHORITY_TYPE + "_" + CONTENT_PROVIDER_GROUPNAME;
            if (!variosUsuarios)
            {
                try
                {                   
                    String CP01_USERNAME = usuario;
                    String[] cpUsers = { CP01_USERNAME };
                    String[] result2 = accessService.addChildAuthorities(parentAuthority, cpUsers);
                }
                catch
                {
                    return false;
                }
            }
            else
            {
                try
                {
                                      
                    String[] result2 = accessService.addChildAuthorities(parentAuthority, usuarios);                  
                   
                }
                catch
                {
                    return false;
                }

            }
            return true;
          
        }

        private static bool deleteGroup(string nombreGrupo, bool variosGrupos, string[] nombresGrupos)
        {
            String GROUP_AUTHORITY_TYPE = "GROUP";
            if (!variosGrupos)
            {
                try
                {
                    string[] temp = new string[1];
                    temp[0] = GROUP_AUTHORITY_TYPE + "_" + nombreGrupo;
                    accessService.deleteAuthorities(temp);
                }
                catch
                {
                    return false;
                }
            }
            else
            {
                try
                {
                    accessService.deleteAuthorities(nombresGrupos);

                }
                catch
                {
                    return false;
                }

            }
            return true;

        }

        private static bool RemoveUserfromGroup(string usuario, string grupo, bool variosUsuarios, string[] usuarios)
        {
            String GROUP_AUTHORITY_TYPE = "GROUP";
            String CONTENT_PROVIDER_GROUPNAME = grupo;
            String parentAuthority = GROUP_AUTHORITY_TYPE + "_" + CONTENT_PROVIDER_GROUPNAME;
            if (!variosUsuarios)
            {
                try
                {
                    String CP01_USERNAME = usuario;
                    String[] cpUsers = { CP01_USERNAME };
                    accessService.removeChildAuthorities(parentAuthority, cpUsers);
                }
                catch
                {
                    return false;
                }
            }
            else
            {
                try
                {

                    accessService.removeChildAuthorities(parentAuthority, usuarios);

                }
                catch
                {
                    return false;
                }

            }
            return true;

        }

avastation
Champ in-the-making
Champ in-the-making
Hi , i am using alfresco 3.3.0 on fedora core 13 , i have installed it, and read all the documentation about it, now i need to create a web script to bulk users under alfresco i did find a tool to do that but it was adding that user by user, and i need to add a block of users for example : 100 users at time, so if any one can help me please i will be grateful , i am working on alfresco with web script , waiting for your response ,

prateekgoyal
Champ in-the-making
Champ in-the-making
Hi,
I have used web service api to create user in alfresco.In this i have created a java program which reads the user information from an xml file and creates the user in alfresco.
But using web scripts, i have'nt done that.

Thanks,

avastation
Champ in-the-making
Champ in-the-making
hi , thanks for your reponse, can you send me your application? this is my email sanfourtdi@gmail.com, if you may , and thank you very much, i have use another java programme to do it, but it doesnt work, so if you can help me, thank again for your help

prateekgoyal
Champ in-the-making
Champ in-the-making
Hi,
Here is the code for creating the user, grups and adding that user to the group.
private static void createGroup(HashMap<String, String> ACLInfoMap, int s ) throws AccessControlFault, RemoteException {
      AccessControlServiceSoapBindingStub accessControlService = WebServiceFactory.getAccessControlService();
      ProcessError errorobj = new ProcessError();
      String GROUPNAME = ACLInfoMap.get("GroupName_"+(s+1));

      AuthorityFilter authorityFilter = new AuthorityFilter();
      authorityFilter.setAuthorityType(GROUP_AUTHORITY_TYPE);

      String[] allAuthorities = accessControlService
      .getAllAuthorities(authorityFilter);

      Boolean existGroup = ArrayUtils.contains(allAuthorities,
            Constants.GROUP_PREFIX + GROUPNAME);
      if (!existGroup) {
         NewAuthority cpGrpAuth = new NewAuthority(GROUP_AUTHORITY_TYPE, GROUPNAME);
         NewAuthority[] newAuthorities = {cpGrpAuth};
         String result[] = accessControlService.createAuthorities(null, newAuthorities);
         errorobj.writeToLog("Groups" +(s+1)+"created");
      }
      else{
         System.out.println("Group"+(s+1)+"Already Exists");
         errorobj.writeToLog("Group"+(s+1)+"Already Exists");
      }
      ACLInfoMap.clear();

   }

   private static void createUser( HashMap<String, String> ACLInfoMap, int i) throws RepositoryFault, RemoteException  {

      String userLogin = ACLInfoMap.get("userLogin_"+(i+1));
      String userPassword = ACLInfoMap.get("userPassword_"+(i+1));
      String userFirstName = ACLInfoMap.get("firstName_"+(i+1));
      String userMiddlename = ACLInfoMap.get("middleName_"+(i+1));
      String userSurname = ACLInfoMap.get("lastName_"+(i+1));
      String userMail = ACLInfoMap.get("userMail_"+(i+1));
      String userOrg = ACLInfoMap.get("userOrg_"+(i+1));

      RepositoryServiceSoapBindingStub repositoryService = WebServiceFactory.getRepositoryService();
      //ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
      AdministrationServiceSoapBindingStub administrationService = WebServiceFactory.getAdministrationService();
      ProcessError errorobj = new ProcessError();
      int batchSize = 5;
      QueryConfiguration queryCfg = new QueryConfiguration();
      queryCfg.setFetchSize(batchSize);
      WebServiceFactory.getAdministrationService().setHeader(
            new RepositoryServiceLocator().getServiceName().getNamespaceURI(), "QueryHeader", queryCfg);

      // check the user
      /*boolean existUser=false;     
      try {
         // test before the user
         administrationService.getUser(userLogin);
         existUser=true;
         errorobj.writeToLog("user already exist");
      } catch (Exception e){
         existUser=false;
         errorobj.writeToLog("creating user");
      }*/

      /*if (existUser) {
         try {
            throw new Exception("User " + userLogin + " Already exists.");
         } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }*/

      Store store = new Store(Constants.WORKSPACE_STORE,"SpacesStore");
      Reference folderReference = new Reference(store,null,"/app:company_home/app:user_homes/cm:"+userLogin);
      Node[] nodes=null;

      // try to create the folder
      try{
         nodes = repositoryService.get(new Predicate(new Reference[]{folderReference},store,null));
         errorobj.writeToLog("creating user folder");
      }
      catch (Exception e) {
         // Create parent reference to company home
         ParentReference parentReference = new ParentReference(
               store,
               null,
               "/app:company_home/app:user_homes",
               Constants.ASSOC_CONTAINS,
               Constants.createQNameString(Constants.NAMESPACE_CONTENT_MODEL, userLogin));

         // Create folder
         NamedValue[] properties = new NamedValue[]{Utils.createNamedValue(Constants.PROP_NAME, userLogin)};
         CMLCreate create = new CMLCreate("1", parentReference, null, null, null, Constants.TYPE_FOLDER, properties);
         CML cml = new CML();
         cml.setCreate(new CMLCreate[]{create});
         UpdateResult[] results = WebServiceFactory.getRepositoryService().update(cml);  

         // Create parent reference to sample folder
         Reference userFolder = results[0].getDestination();
         ParentReference parentReference2 = new ParentReference(
               store,
               userFolder.getUuid(),
               null,
               Constants.ASSOC_CONTAINS,
               Constants.createQNameString(Constants.NAMESPACE_CONTENT_MODEL, userLogin));
      }

      // get the reference for the folder
      Reference userFolder =null;
      try {
         nodes = repositoryService.get(new Predicate(new Reference[]{folderReference},store,null));
         if (nodes.length == 1) {
            userFolder = nodes[0].getReference();
            errorobj.writeToLog("User Folder created");
         }
      } catch (Exception e) {
         e.printStackTrace();
         try {
            throw new Exception("Unable to create the new folder for user "+userLogin+".");
         } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            errorobj.writeToLog(e1, "Unable to create the new folder for user "+userLogin+".");
         }                     
      }

      try {
         String homeFolder = store.getScheme() + "://" + store.getAddress() + "/" + userFolder.getUuid();
         
         boolean existUser=false;     
           try {
               // test before the user
              administrationService.getUser(userLogin);
              existUser=true;
              System.out.println("User Already Exist");
          } catch (Exception e){
             existUser=false;         
         // Create the new users
         NewUserDetails[] newUsers = new NewUserDetails[1] ;
         NewUserDetails newUser = new NewUserDetails(
               userLogin, userPassword,
               createPersonProperties(homeFolder,
                     userFirstName, userMiddlename, userSurname,
                     userMail, userOrg));

         UserDetails[] userDetails = administrationService.createUsers(new NewUserDetails[]{newUser});
         errorobj.writeToLog(userLogin + " User created "  );
         System.out.println(userLogin + " User created " );
          }
      }
      catch ( Exception e) {
         e.printStackTrace();
         try {
            throw new Exception("Unable to create the new user.");
         } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            errorobj.writeToLog(e1, "Unable to create the new user.");
         }
      }

      //System.out.println("the user "+userLogin+" has been created and folder too.");
      addUsersToGroup(ACLInfoMap,i);
      ACLInfoMap.clear();
   }



   /*
    * create the property's
    */   
   private static NamedValue[] createPersonProperties(
         String homeFolder,
         String firstName,
         String middleName,
         String lastName,
         String email,
         String orgId)
   {
      // Create the new user objects
      return new NamedValue[] {
            new NamedValue(Constants.PROP_USER_HOMEFOLDER, false, homeFolder, null),
            new NamedValue(Constants.PROP_USER_FIRSTNAME,  false, firstName, null),
            new NamedValue(Constants.PROP_USER_MIDDLENAME, false, middleName, null),
            new NamedValue(Constants.PROP_USER_LASTNAME,   false, lastName, null),
            new NamedValue(Constants.PROP_USER_EMAIL,      false, email, null),
            new NamedValue(Constants.PROP_USER_ORGID,      false, orgId, null)};
   }


   private static void addUsersToGroup(HashMap<String, String> ACLInfoMap, int i) throws AccessControlFault, RemoteException {

      ProcessError errorobj = new ProcessError();
      String[] userName = {ACLInfoMap.get("userLogin_"+(i+1))};
      String userGrpName = ACLInfoMap.get("userGroupName_"+(i+1));
      int tokenNumber = 0;
      StringTokenizer strToken = new StringTokenizer(userGrpName,",");
      tokenNumber= strToken.countTokens();
      for(int t=0;t<tokenNumber;t++){

         String GROUPNAME = strToken.nextToken();
         String parentAuthority  = GROUP_AUTHORITY_TYPE + "_" + GROUPNAME;
         AccessControlServiceSoapBindingStub accessControlService = WebServiceFactory.getAccessControlService();
         
          // test if exist group name
            AuthorityFilter authorityFilter = new AuthorityFilter();
            authorityFilter.setAuthorityType(GROUP_AUTHORITY_TYPE);

            String[] allAuthorities = accessControlService
                  .getAllAuthorities(authorityFilter);
           
            Boolean existGroup = ArrayUtils.contains(allAuthorities,
                  parentAuthority);

            if (existGroup){
               String[] result = accessControlService.addChildAuthorities(parentAuthority, userName);
             errorobj.writeToLog("user "+ ACLInfoMap.get("userLogin_"+(i+1)) + " added to the group"+userGrpName);
            }
            else{
               System.out.println("The group to which user"+ACLInfoMap.get("userLogin_"+(i+1))+" to be added does not exist");
            }
         
         
         

      }


   }

avastation
Champ in-the-making
Champ in-the-making
Thanks you very much for your help i am going to try it , if something doesnt work i will tell you thanks again