cancel
Showing results for 
Search instead for 
Did you mean: 

Creating Users using JAVA API

yvinodh
Champ in-the-making
Champ in-the-making
Hi all,

         I am using Alfresco 2.9.In my application i need to create users using JAVA API. Can anyone help me in this.
         Thanks in Advance

Regards,
Yvinodh.
41 REPLIES 41

pmonks
Star Contributor
Star Contributor
The Alfresco API Javadocs are available at http://dev.alfresco.com/resource/docs/java/repository/.  I believe the services you'll need for this are the PersonService (http://dev.alfresco.com/resource/docs/java/repository/org/alfresco/service/cmr/security/PersonServic...) and possibly also the AuthenticationService (http://dev.alfresco.com/resource/docs/java/repository/org/alfresco/service/cmr/security/Authenticati...).

Probably the best way to be certain of how to create users correctly is to look at Alfresco's own code that does this - this functionality is provided by the Administration Console component of the JSF Web Client.

Cheers,
Peter

yvinodh
Champ in-the-making
Champ in-the-making
hi pmonks,

    Thank you for your reply.Your post was helpful for me. Smiley Very Happy I created user and groups using JAVA API. I implemented the code in SDK using eclipse .  but i need to apply this code in my own application. Can you please help me in this.

Thanks and Regards,
yvinodh

pmonks
Star Contributor
Star Contributor
Web Scripts (http://wiki.alfresco.com/wiki/Web_Scripts) are the best way to remotely interact with an Alfresco repository.  In this case you'd develop a "create user" Web Script (that calls those underlying APIs) and call that Web Script remotely from your application.

Cheers,
Peter

rivetlogic
Champ on-the-rise
Champ on-the-rise
There is an open source project called RAAR (CMA) that can be used to communicate with alfresco easily.
The Remote Alfresco API is a Java based API for developing content enabled applications, websites and plugins on top of one or more Alfresco repositories.

You can include RAAR as a jar file in your project and then the API's provided by it can be used to perform actions like create user and create group etc. You also need to inject an amp into alfresco.

for more information about RAAR: http://forge.alfresco.com/projects/cma/ . Also please go through the readme file.

- Praveen C Elineni

yvinodh
Champ in-the-making
Champ in-the-making
Hi Praveen,

I have injected CMA-AMP in my alfresco.war, i am trying to create the new user and add tat new user into the group. Can u give some links where i can find the sample codes to implement the same. In tat CMA-API.jar, there is method called authenticate which takes the repositoryUri  as its one of the parametres. can u tell wat value i should pass for this..


Thanks in Advance,
Vinodh.

rivetlogic
Champ on-the-rise
Champ on-the-rise
Hi Vinodh,

I created a Java Application that uses RAAR- 1.7.1 (aka CMA) and Alfresco 2.2 Enterprise.  I used Maven to create the project and include jar file dependencies.

Here is what the program does:

1. Authenticate to alfresco using RAAR
2. Search for a file given a name
3. Open the file and write content into it
4. Close the file
5. Open the file and read its contents
6. Dump the content on the console
7. Close the file
8. Create user group
9. Create user
10. Add user to created group
11. Logout from Alfresco

You can login to Alfresco WebClient and check the file manually to see if the content has been written into it. Also you can check the user and group creation.

I was not able to attach the zip file to this forum, but feel free to email me if you want the zip file. Here is how you do it by hand.

Instructions to run the project in eclipse:

Create the following structure on disk:


   ProjectName
      src/main/java/
         MainClass.java   
      src/
         main/
            java/
            resources/
            core/
               cma-core-context.xml
      pom.xml

Here is the MainClass.java:



import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.namespace.QName;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.rivetlogic.core.cma.api.SearchService;
import com.rivetlogic.core.cma.api.SecurityService;
import com.rivetlogic.core.cma.exception.AuthenticationFailure;
import com.rivetlogic.core.cma.exception.AuthorityExistsException;
import com.rivetlogic.core.cma.exception.CmaRuntimeException;
import com.rivetlogic.core.cma.exception.InvalidTicketException;
import com.rivetlogic.core.cma.impl.AuthenticationServiceImpl;
import com.rivetlogic.core.cma.impl.ContentServiceImpl;
import com.rivetlogic.core.cma.impl.PeopleServiceImpl;
import com.rivetlogic.core.cma.impl.SearchServiceImpl;
import com.rivetlogic.core.cma.repo.Node;
import com.rivetlogic.core.cma.repo.SortDefinition;
import com.rivetlogic.core.cma.repo.Ticket;

/**
*
* @author Praveen C Elineni
* @Rivet
*
*/
public class mainClass {

   private static final String APPLICATION_CONTEXT = "classpath*:core/cma-core-context.xml";

   public static void main(String[] args) {
      ConfigurableApplicationContext configurationApplicationContext = null;
      AuthenticationServiceImpl authenticationService = null;
      SearchServiceImpl searchService = null;
      ContentServiceImpl contentService = null;
      PeopleServiceImpl peopleService = null;
      Ticket ticket = null;

      QName name = QName.createQName("{http://www.alfresco.org/model/content/1.0}name");
      QName created = QName.createQName("{http://www.alfresco.org/model/content/1.0}created");

      List<QName> properties = new Vector<QName>();
      properties.add(name);
      properties.add(created);

      List<String> requiredPermissions = new ArrayList<String>(4);
      requiredPermissions.add(SecurityService.READ_CONTENT);
      requiredPermissions.add(SecurityService.WRITE_CONTENT);
      requiredPermissions.add(SecurityService.WRITE_PROPERTIES);
      requiredPermissions.add(SecurityService.DELETE);

      QName nodeTypeQName = QName.createQName("{http://www.alfresco.org/model/content/1.0}content");

      String spacesStore = "workspace://SpacesStore";
      String repositoryUri = "http://localhost:8080/alfresco/service";
      String password = "admin";
      String userid= "admin";
      String fileName = "/tmp/rivetlogic.txt";
      String data;
      
      // variables for user / group creation
      String groupName = "RivetGroup";
      String userName = "rivet";
      String passwd = "rivet";
      String firstName = "Rivet";
      String lastName = "Logic";

      QName firstNameQName = QName.createQName("{http://www.alfresco.org/model/content/1.0}firstName");
       QName lastNameQName = QName.createQName("{http://www.alfresco.org/model/content/1.0}lastName");

      Map<QName, Serializable> props = null;
       props = new HashMap<QName, Serializable>(4);
       // homeFolder value must be a nodeRef
       props.put(firstNameQName, firstName);
       props.put(lastNameQName, lastName);

      configurationApplicationContext = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT);

      authenticationService = (AuthenticationServiceImpl) configurationApplicationContext.getBean("authenticationService");
      searchService = (SearchServiceImpl) configurationApplicationContext.getBean("searchService");
      contentService = (ContentServiceImpl) configurationApplicationContext.getBean("contentService");
      peopleService = (PeopleServiceImpl) configurationApplicationContext.getBean("peopleService");

      List<SortDefinition> sortDefinitions = new Vector<SortDefinition>();
      sortDefinitions.add(new SortDefinition(SortDefinition.SortType.FIELD, "@{http://www.alfresco.org/model/content/1.0}name", false));

      try {
         // Validate userid and password
         ticket = authenticationService.authenticate(repositoryUri, userid, password.toCharArray());

         /*      old search - deprecated in new release
          *
          *       List<Node> nodes = searchService.query(ticket, new StoreRef(spacesStore),
          *         SearchService.QueryLanguage.lucene, "@cm\\:name:\"javaapi\"", true, true, true, true, true, 1, 100, sortDefinitions);
          *
         */

         // search for file with name "rivetlogic"
         List<Node> nodes = searchService.query(ticket, new StoreRef(spacesStore), SearchService.QueryLanguage.lucene, "@cm\\:name:\"rivetlogic\"",
                                 properties, true, true, true, true, requiredPermissions, 100, sortDefinitions);

         if (nodes != null) {
            // file found
            for (Node node: nodes) {
               System.out.println("node: " + node);
               NodeRef nodeRef = node.getNodeRef();

               // get data from user
               System.out.println("Enter content to put in the file: ");
               BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                 data = br.readLine();
                 br.close();

               // write content to the file
               InputStream input = new ByteArrayInputStream(data.getBytes("UTF-8"));
               contentService.writeContentFromStream(ticket, nodeRef, nodeTypeQName, input);
               input.close();
               System.out.println("Data has been written into the file /CompanyHome/rivetlogic.txt");

               // open file and read data and dump it into fileName file. - "/tmp/javaapi.txt"
               FileOutputStream output = new FileOutputStream(fileName);
               contentService.readContentIntoStream(ticket, nodeRef, nodeTypeQName, output);
               output.close();
               System.out.println("Reading data from the file");
               
               // dump data on screen
               InputStream file = new FileInputStream(fileName);
               br = new BufferedReader(new InputStreamReader(file));
               String str;
               System.out.println("Content of file (/CompanyHome/rivetlogic.txt) is: ");
               while ((str = br.readLine()) != null) {
                  System.out.println(str);
               }
               br.close();
               file.close();
            }
         }

         // create user group in alfresco
         
         System.out.println("Creating the group called RivetGroup");
         NodeRef userGroup = peopleService.createGroup(ticket, groupName);
         
         System.out.println("Creating the user called Rivet Logic");
         NodeRef userRef = peopleService.createPerson(ticket, userName, passwd.toCharArray(), props);

         // add user to the group created
         System.out.println("Adding RivetLogic to RivetGroup");
         peopleService.addAuthority(ticket, userGroup, userRef);

         // logout - invalidate ticket
         System.out.println("logging out. invalidating session.");
         authenticationService.invalidateTicket(ticket);

      } catch (AuthenticationFailure e) {
         e.printStackTrace();
      } catch (InvalidTicketException e) {
         e.printStackTrace();
      } catch (CmaRuntimeException e) {
         e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (AuthorityExistsException e) {
         e.printStackTrace();
      }      
   }
}



Here is the pom.xml:


<?xml version="1.0" encoding="UTF-8"?><project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.rivetlogic</groupId>
  <artifactId>raar-demo</artifactId>
  <packaging>jar</packaging>
  <name>RAAR Demo</name>
  <version>0.0.1</version>
  <url>http://www.rivetlogic.com</url>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.5</source>
          <target>1.5</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
  <repositories>
    <repository>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>Rivet Logic</id>
      <url>http://mvn.rivetlogic.com/artifactory/repo</url>
    </repository>
  </repositories>
  <dependencies>
      <dependency>
         <groupId>com.rivetlogic</groupId>
         <artifactId>cma-api</artifactId>
         <version>1.7.1</version>
      </dependency>
      <dependency>
         <groupId>com.rivetlogic</groupId>
         <artifactId>cma-impl</artifactId>
         <version>1.7.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring</artifactId>
      <version>2.0.2</version>
    </dependency>
  </dependencies>
</project>


Here is the cma-core-context.xml file:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<!–
/*
* Copyright (C) 2008 Rivet Logic Corporation.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
–>
<beans>
   <bean id="cmaUnmarshaller"
      class="com.rivetlogic.core.cma.mapping.impl.CmaCastorUnmarshaller" />

   <bean id="cmaMappingService"
      class="com.rivetlogic.core.cma.mapping.impl.CmaMappingServiceImpl"
      init-method="init">
      <property name="mappingFile"><value>castor/mapping/mappingservice.mapping.xml</value></property>
      <property name="mappingConfiguration"><value>castor/mapping/mappingservice.configuration.xml</value></property>
      <property name="cmaUnmarshaller" ref="cmaUnmarshaller" />
   </bean>

   <bean id="restExecuter"
      class="com.rivetlogic.core.cma.rest.impl.RestExecuterImpl"
      init-method="init">
      <property name="cmaUnmarshaller" ref="cmaUnmarshaller" />
   </bean>

   <bean id="actionService"
      class="com.rivetlogic.core.cma.impl.ActionServiceImpl">
      <property name="serviceUri"><value>/cma/actionservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>

   <bean id="authenticationService"
      class="com.rivetlogic.core.cma.impl.AuthenticationServiceImpl">
      <property name="serviceUri"><value>/cma/authenticationservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>

   <bean id="classificationService"
      class="com.rivetlogic.core.cma.impl.ClassificationServiceImpl">
      <property name="serviceUri"><value>/cma/classificationservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>

   <bean id="contentService"
      class="com.rivetlogic.core.cma.impl.ContentServiceImpl">
      <property name="serviceUri"><value>/cma/contentservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>

   <bean id="dictionaryService"
      class="com.rivetlogic.core.cma.impl.DictionaryServiceImpl">
      <property name="serviceUri"><value>/cma/dictionaryservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>

   <bean id="nodeService"
      class="com.rivetlogic.core.cma.impl.NodeServiceImpl">
      <property name="serviceUri"><value>/cma/nodeservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>

   <bean id="libraryService"
      class="com.rivetlogic.core.cma.impl.LibraryServiceImpl">
      <property name="serviceUri"><value>/cma/libraryservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>

   <bean id="mimetypeService"
      class="com.rivetlogic.core.cma.impl.MimetypeServiceImpl">
      <property name="serviceUri"><value>/cma/mimetypeservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>
   
   <bean id="peopleService"
      class="com.rivetlogic.core.cma.impl.PeopleServiceImpl">
      <property name="serviceUri"><value>/cma/peopleservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>

   <bean id="searchService"
      class="com.rivetlogic.core.cma.impl.SearchServiceImpl">
      <property name="serviceUri"><value>/cma/searchservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>

   <bean id="securityService"
      class="com.rivetlogic.core.cma.impl.SecurityServiceImpl">
      <property name="serviceUri"><value>/cma/securityservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>

   <bean id="transformationService"
      class="com.rivetlogic.core.cma.impl.TransformationServiceImpl">
      <property name="serviceUri"><value>/cma/transformationservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>

   <bean id="versionService"
      class="com.rivetlogic.core.cma.impl.VersionServiceImpl">
      <property name="serviceUri"><value>/cma/versionservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>
   
   <bean id="workflowService"
      class="com.rivetlogic.core.cma.impl.WorkflowServiceImpl">
      <property name="serviceUri"><value>/cma/workflowservice</value></property>
      <property name="restExecuter" ref="restExecuter" />
      <property name="cmaMappingService" ref="cmaMappingService" />
   </bean>

</beans>



On command line:

mvn package
mvn eclipse:eclipse

The above command will create an eclipse project that you need to import into eclipse. (File - Import - Existing projects into workspace - browse to this project - finish).

Download the plugin for maven and right click on the project and enable maven for the project.

On Command line: mvn clean package

Then Run the project as a java application to see the output.


To summarize the post,

Here is how you authenticate:


   authenticationService.authenticate(repositoryUri, userid, password.toCharArray());


Here is how you create the user:


   peopleService.createPerson(ticket, userName, passwd.toCharArray(), props);

Here is how you can create a group:


   peopleService.createGroup(ticket, groupName);

Let me know if you have any questions.

Praveen C Elineni.

yvinodh
Champ in-the-making
Champ in-the-making
Hi Praveen,

you have used pom.xml, wat is the use of it. I am not using maven in my application.

when i tried to execute the code which u have given i am getting this error:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cmaMappingService' defined in URL [file:/D:/Satyam.com/Satyam.com/WEB-INF/classes/satyam/cma-core-context.xml]: Invocation of init method failed; nested exception is java.lang.ClassCastException: com.rivetlogic.core.cma.alfresco.webscripts.mapping.CmaMapping
Caused by: java.lang.ClassCastException: com.rivetlogic.core.cma.alfresco.webscripts.mapping.CmaMapping
   at com.rivetlogic.core.cma.mapping.impl.CmaMappingServiceImpl.init(CmaMappingServiceImpl.java:113)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
   at java.lang.reflect.Method.invoke(Unknown Source)
   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1160)
   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1122)
   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1085)
   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:429)
   at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:250)
   at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:141)
   at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:247)
   at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:161)
   at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:273)
   at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:346)
   at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:92)
   at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:77)
   at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:68)
   at org.satyam.common.CmaCreation.main(CmaCreation.java:90)

Do we have to change the cmaMappingService bean values..

My Email ID is Vinodhkumar_Shyamsundar@satyam.com. can me mail your zip file to this Email Id.


Thanks in Advance,
Vinodh

rivetlogic
Champ on-the-rise
Champ on-the-rise
Vinodh,

pom.xml is used to add the project dependencies (libraries used in the project) and contains information about the project and configuration details used by Maven to build the project.



Caused by: java.lang.ClassCastException: com.rivetlogic.core.cma.alfresco.webscripts.mapping.CmaMapping


Looks like there are multiple instances of CmaMapping class file trying to be loaded.

Please make sure the only additional jar files needed to run RAAR are: cma-api.jar and cma-impl.jar. Also the spring configuration file should be loaded only once.

There is no need to change cmaMappingService bean values.

I am attaching the zip file for you in an email.

- Praveen C Elineni.

charlesbronson
Champ in-the-making
Champ in-the-making
Hi, is there any possibility to send me also the zip file?

guido.giosa@gmail.com

Thanks in advance,

Guido.