cancel
Showing results for 
Search instead for 
Did you mean: 

add parent/chld example please

arusellcampion
Champ in-the-making
Champ in-the-making
Dear experts
I'm trying in vain to code up a class that will create a node and a child ie parentFolder->childFolder in one pass using Alfresco Webservices. I've posted here earlier (see "creatng parent->child folders via API " http://forums.alfresco.com/en/viewtopic.php?f=27&t=35369) but am still looking for help as to how to go about it. I imagine I'd do a CMLCreate followed by a CMLAddChild but I'm struggling without further guidance.

I'm using Alfresco Community 3.3.

Thanks,

Andrew
6 REPLIES 6

rwetherall
Confirmed Champ
Confirmed Champ
Hi Andrew,

I'll try and outline what I think your CML should look like (in JSON Style).  You should be able to take this and construct the relevant CML object to pass to the update web service method.

"cml" :
[
      "create" :
      {
          "id" : "myparent",
          "parent" : <parent reference to the node we want the parent>,
          "associationType" : <name of the association type>,
          "childName" : <name of the association>,
          "type" : <folder type>
      },
     "create" :
     {
          "id" : "mychild",
          "parent_id" : "myparent",
          "associationType" : <name of the association type>,
          "childName" : <name of the association>,
          "type" : <child type>
     }
]

Hopefully you will be able to see that it is the use of the "parent_id" element in the create CML object that enables us to create a new node as a child of a node previously created in the same CML statement.

We can use the same "parent_id" reference when applying aspects, etc to nodes created in the same CML object.

Hope this helps,
Roy

arusellcampion
Champ in-the-making
Champ in-the-making
Dear Roy
Thanks for getting back. I think I'm getting closer but still not quite there. Here's my class


package uk.ac.sheffield.cics.extensions.addContent;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.alfresco.repo.webservice.types.CMLAddChild;
import org.alfresco.repo.webservice.types.Predicate;
import org.alfresco.webservice.repository.UpdateResult;
import org.alfresco.webservice.types.CML;
import org.alfresco.webservice.types.CMLCreate;
import org.alfresco.webservice.types.NamedValue;
import org.alfresco.webservice.types.ParentReference;
import org.alfresco.webservice.types.Store;
import org.alfresco.webservice.util.AuthenticationUtils;
import org.alfresco.webservice.util.Constants;
import org.alfresco.webservice.util.Utils;
import org.alfresco.webservice.util.WebServiceFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import uk.ac.sheffield.cics.extensions.utils.Attributes;

@SuppressWarnings("serial")
public class CreateContentServlet extends HttpServlet{
   private String folder = "";   
   private static Log log = LogFactory.getLog(CreateContentServlet.class);
   
   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
      System.out.println("doGet called");
      folder = request.getParameter("folder");   
      System.out.println("doGet: Calling createContent with " + Attributes.PARENT_FOLDER + " as parent");
      createContent(request, response,  Attributes.PARENT_FOLDER, folder);                  
   }
   

   @Override
   protected void service(HttpServletRequest req, HttpServletResponse resp)
         throws ServletException, IOException {
      System.out.println("service called");
      super.service(req, resp);
   }
   
   private void createContent(HttpServletRequest request, HttpServletResponse response, String parent, String folder) throws IOException
   {
      
      // Start the session
      AuthenticationUtils.startSession(Attributes.USERNAME, Attributes.PASSWORD);         
      try {
         // Make your web service call in here
         createFolder(parent, folder, request, response);
      }
      catch (Throwable e) {
         log.error("createContent erorr: " + e.toString());
         e.printStackTrace();
      }
      finally {
         // End the session
         AuthenticationUtils.endSession();
      }    
    }
   
   protected static void createFolder(String parent, String folder, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
      final Store STORE = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
      // The default workspace store is SpacesStore
       //Store storeReference = new Store(Constants.WORKSPACE_STORE, "SpacesStore");

       // We want to create a new folder or workspace called child in the parent folder under company home
       // Create parent reference to the parent space in company home
       //ParentReference parentReference = new ParentReference(STORE, null, "/app:company_home/cm:parent",
      ParentReference parentReference = new ParentReference(
                    STORE,
                    null,
                    "/app:company_home/cm:" + parent,
                    Constants.ASSOC_CONTAINS,
                    Constants.createQNameString(Constants.NAMESPACE_CONTENT_MODEL, "sample_folder"));
                      
       // Create the child folder
       NamedValue[] properties = new NamedValue[] { Utils.createNamedValue(Constants.PROP_NAME, folder) };
       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);
      
       CMLCreate createChild = new CMLCreate(
             "2",
             parentReference,
             "1",
             Constants.ASSOC_CONTAINS,
             Attributes.EMAIL_FOLDER,
             Constants.TYPE_FOLDER, properties);      
      
       cml.setCreate(new CMLCreate[] { createChild });
       UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cml);
      
       }                                    
   
}

When I hit the url thus

http://localhost:8080/alfresco/app/addContent?folder=parentFolder
'>
http://localhost:8080/alfresco/ap...


I get an exception

service called
doGet called
doGet: Calling createContent with TopLevel as parent
16:51:30,484 User:admin ERROR [extensions.addContent.CreateContentServlet] createContent erorr:
AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.generalException
faultSubcode:
faultString:
faultActor:
faultNode:
faultDetail:
   {http://www.alfresco.org/ws/service/repository/1.0}RepositoryFault:<ns1:errorCode>0</ns1:errorCode><ns1:message>org.alfresco.service.cmr.repository.DuplicateChildNodeNameException: Duplicate child name not allowed: parentFolder</ns1:message>
   {http://xml.apache.org/axis/}exceptionName:org.alfresco.repo.webservice.repository.RepositoryFault
   {http://xml.apache.org/axis/}stackTrace:
   at org.alfresco.repo.webservice.repository.RepositoryWebService.update(RepositoryWebService.java:335)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
   at java.lang.reflect.Method.invoke(Method.java:597)
   at org.apache.axis.providers.java.RPCProvider.invokeMethod(RPCProvider.java:397)
   at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:186)
   at org.apache.axis.providers.java.JavaProvider.invoke(JavaProvider.java:323)
   at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
   at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
   at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
   at org.apache.axis.handlers.soap.SOAPService.invoke(SOAPService.java:454)
   at org.apache.axis.server.AxisServer.invoke(AxisServer.java:281)
   at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:699)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
   at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
   at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
   at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
   at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
   at java.lang.Thread.run(Thread.java:619)

   {http://xml.apache.org/axis/}hostname:AndrewRussell


   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
   at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
   at java.lang.Class.newInstance0(Class.java:355)
   at java.lang.Class.newInstance(Class.java:308)
   at org.apache.axis.encoding.ser.BeanDeserializer.<init>(BeanDeserializer.java:104)
   at org.apache.axis.encoding.ser.BeanDeserializer.<init>(BeanDeserializer.java:90)
   at org.alfresco.webservice.repository.RepositoryFault.getDeserializer(RepositoryFault.java:146)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
   at java.lang.reflect.Method.invoke(Method.java:597)
   at org.apache.axis.encoding.ser.BaseDeserializerFactory.getSpecialized(BaseDeserializerFactory.java:154)
   at org.apache.axis.encoding.ser.BaseDeserializerFactory.getDeserializerAs(BaseDeserializerFactory.java:84)
   at org.apache.axis.encoding.DeserializationContext.getDeserializer(DeserializationContext.java:464)
   at org.apache.axis.encoding.DeserializationContext.getDeserializerForType(DeserializationContext.java:547)
   at org.apache.axis.message.SOAPFaultDetailsBuilder.onStartChild(SOAPFaultDetailsBuilder.java:157)
   at org.apache.axis.encoding.DeserializationContext.startElement(DeserializationContext.java:1035)
   at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
   at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
   at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
   at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
   at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
   at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
   at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
   at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
   at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
   at org.apache.xerces.jaxp.SAXParserImpl.parse(Unknown Source)
   at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
   at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
   at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
   at org.apache.axis.handlers.soap.MustUnderstandChecker.invoke(MustUnderstandChecker.java:62)
   at org.apache.axis.client.AxisClient.invoke(AxisClient.java:206)
   at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
   at org.apache.axis.client.Call.invoke(Call.java:2767)
   at org.apache.axis.client.Call.invoke(Call.java:2443)
   at org.apache.axis.client.Call.invoke(Call.java:2366)
   at org.apache.axis.client.Call.invoke(Call.java:1812)
   at org.alfresco.webservice.repository.RepositoryServiceSoapBindingStub.update(RepositoryServiceSoapBindingStub.java:986)
   at uk.ac.sheffield.cics.extensions.addContent.CreateContentServlet.createFolder(CreateContentServlet.java:106)
   at uk.ac.sheffield.cics.extensions.addContent.CreateContentServlet.createContent(CreateContentServlet.java:56)
   at uk.ac.sheffield.cics.extensions.addContent.CreateContentServlet.doGet(CreateContentServlet.java:38)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
   at uk.ac.sheffield.cics.extensions.addContent.CreateContentServlet.service(CreateContentServlet.java:46)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
   at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
   at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
   at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
   at java.lang.Thread.run(Thread.java:619)
Where am I going wrong?

Regards,
Andrew

rwetherall
Confirmed Champ
Confirmed Champ
Hi Andrew,

You can not have two folders or documents with the same name in the same parent folder, hence the duplicate name exception you are seeing.

Perhaps you should clear out your data and re-run?  Is it possible running this twice will create two folders of the same name in the same folder (hence the error)?

Cheers,
Roy

arusellcampion
Champ in-the-making
Champ in-the-making
Hi
I don' think it's a data issue as I clear out before each attempt; I tried this time with a different folder name:


http://localhost:8080/alfresco/app/addContent?folder=parentFolder2
'>
http://localhost:8080/alfresco/a...

and got the same error

{http://www.alfresco.org/ws/service/repository/1.0}RepositoryFault:<ns1:errorCode>0</ns1:errorCode><ns1:message>org.alfresco.service.cmr.repository.DuplicateChildNodeNameException: Duplicate child name not allowed: parentFolder2</ns1:message>

Must be something in the

CMLCreate createChild = new CMLCreate(
definition?

rwetherall
Confirmed Champ
Confirmed Champ
Hi Andrew,

I think the second definition should look like this …


  CMLCreate createChild = new CMLCreate(
             "2",
             null,
             "1",
             Constants.ASSOC_CONTAINS,
             Attributes.EMAIL_FOLDER,
             Constants.TYPE_FOLDER, properties); 

… ie you don't need to specify the parent reference since you want it to be created as a child of the previously created node.

Cheers,
Roy

arusellcampion
Champ in-the-making
Champ in-the-making
Hello
this tutorial

http://wiki.alfresco.com/wiki/IngresTutorial_Alfresco_Web_Service_API_for_Java#Create_a_space_inside...



was really useful. Using the helper methods provided I am now able to do this:

private void createContent(HttpServletRequest request, HttpServletResponse response, String parent, String folder) throws IOException
   {
      String[] folders = {"Academic Progress","Accommodation","Admissions","Assessment","Careers and PDP","Finance","Formal Procedures","General Correspondence","Health, Wellbeing and Disability","Placements","Registration","Studentship"};
      // Start the session
      AuthenticationUtils.startSession(Attributes.USERNAME, Attributes.PASSWORD);         
      try {
         // Make your web service call in here         
         Reference r = SpaceUtil.createSpace("TestParent");
         for(int i=0; i<folders.length;i++){
            SpaceUtil.createSpace(r,folders[i]);
         }         
      }
      catch (Throwable e) {
         log.error("createContent erorr: " + e.toString());
         e.printStackTrace();
      }
      finally {
         // End the session
         AuthenticationUtils.endSession();
      }    
    }             
And the util class is

public class SpaceUtil {
   private final static Store STORE = new Store(Constants.WORKSPACE_STORE, "SpacesStore");

   

   private static RepositoryServiceSoapBindingStub getRepositoryService()
   {
         return WebServiceFactory.getRepositoryService();   
   }
      
   private static ContentServiceSoapBindingStub getContentService()
   {
         return WebServiceFactory.getContentService();
   }

   private static ParentReference ReferenceToParent(Reference spaceref)
   {
         ParentReference parent = new ParentReference();
         
         parent.setStore(STORE);
         parent.setPath(spaceref.getPath());
         parent.setUuid(spaceref.getUuid());
         parent.setAssociationType(Constants.ASSOC_CONTAINS);
         
         return parent;
   }
      
      //Blanks are allowed in space names but not in paths. Because the path should depend on the name.
      //we need a version of the name which contains no blanks
      
   private static String normalisedNodeName(String name)
   {
         return name.replace(" ","_");   
   }
   
   private static ParentReference getCompanyHome()
   {   
           ParentReference companyHomeParent = new ParentReference(STORE, null, "/app:company_home", Constants.ASSOC_CONTAINS, null);
           return companyHomeParent;
   }

   public static Reference createSpace(String spacename) throws Exception{
         Reference space = null;
            
         // Create the space if it doea not already exist
         try {                     
            System.out.println("Entering space " + spacename);
                  
            space = new Reference(STORE, null, getCompanyHome().getPath() + "/cm:" + normalisedNodeName(spacename));
            getRepositoryService().get(new Predicate(new Reference[]{space}, STORE, null));
         }
         catch (Exception e1)
         {
            System.out.println("The space named " + spacename + " does not exist. Creating it.");
            
            ParentReference companyHome = getCompanyHome();
            
            // Set Company Home as the parent space
            companyHome.setChildName(Constants.createQNameString(Constants.NAMESPACE_CONTENT_MODEL, normalisedNodeName(spacename)));
            
            //Set the space's property name
            NamedValue[] properties = new NamedValue[]{Utils.createNamedValue(Constants.PROP_NAME,spacename)};              
            // Create the space using CML (Content Manipulation Language)
            CMLCreate create = new CMLCreate("1", companyHome, null, null, null, Constants.TYPE_FOLDER, properties);
               CML cml = new CML();
               cml.setCreate(new CMLCreate[]{create});
              
               //Execute the CML create statement
               try {
               getRepositoryService().update(cml);
            } catch (Exception e2) {
               
               System.err.println("Can not create the space.");
               throw e2;
            }                            
         }      
      return space;
   }

   public static Reference createSpace(Reference parentref, String spacename) throws Exception{         
         Reference space = null;
         ParentReference parent = ReferenceToParent(parentref);
         try {
            
            System.out.println("Entering space " + spacename);
            space = new Reference(STORE, null, parent.getPath() + "/cm:" + normalisedNodeName(spacename));
            WebServiceFactory.getRepositoryService().get(new Predicate(new Reference[]{space}, STORE, null));
         }
         catch (Exception e1)
         {
            System.out.println("The space named " + spacename + " does not exist. Creating it.");
            
            parent.setChildName(Constants.createQNameString(Constants.NAMESPACE_CONTENT_MODEL, normalisedNodeName(spacename)));
            
            //Set the space's property name
            NamedValue[] properties = new NamedValue[]{Utils.createNamedValue(Constants.PROP_NAME, spacename)};
              
      
            // Create the space using CML (Content Manipulation Language)
            CMLCreate create = new CMLCreate("1", parent, null, null, null, Constants.TYPE_FOLDER, properties);
               CML cml = new CML();
               cml.setCreate(new CMLCreate[]{create});
              
               //Execute the CML create statement
               try {
               getRepositoryService().update(cml);
            } catch (Exception e2) {
               
               System.err.println("Can not create the space.");
               throw e2;
            }             
         }
         return space;
   }
}
Getting started

Tags


Find what you came for

We want to make your experience in Hyland Connect as valuable as possible, so we put together some helpful links.