cancel
Showing results for 
Search instead for 
Did you mean: 

Get the content from a specific node

surajit
Champ in-the-making
Champ in-the-making
Hi ,

  I am new to the Alfreso. I need to develop a code with would get the content from Alfresco directory ( Say MyHome->Project->Drafts->FileName) . I am planning to use webService for the same. Could you please guide me how I could browse to that directory and download the data and also get the metadata of that file

Thanks in advance

regads
Surajit
10 REPLIES 10

lalli
Champ in-the-making
Champ in-the-making
Hope this sample will help you.
====================

public static String webService(String dir, String fileName) throws Exception
    {
   String downloadURL = null;
      
        try
        {
      // Let us say you know the directory and filename For Eg:   

       //String dir = "/app:company_home/cmSmiley TongueCMCOE/cm:COE1/";
            //String fileName = "Stake";
       System.out.println("dir ::" + dir);
            System.out.println("fileName ::" + fileName);
           
           
           // Start the session
            AuthenticationUtils.startSession("admin", "admin");
            String ticket = AuthenticationUtils.getCurrentTicket();
          
           
             // Create a reference to the parent where we want to create content
            Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
          
           

            //Reference reference = new Reference(storeRef, null, "/app:company_home/cmSmiley TongueCMCOE/cm:COE1/*[@cm:name=\"" + "eProfilerPPT" + "\"]");
//       Create a new Reference to the node you want (variable path here).
            String path = dir+"*[@cm:name=\"" + fileName + "\"]";
            Reference reference = new Reference(storeRef, null, path);
            ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
                       
            // Read the content from the respository
            Content[] readResult = contentService.read(
                                                new Predicate(new Reference[]{reference}, storeRef, null),
                                                Constants.PROP_CONTENT);
            Content contentRef = readResult[0];
                                   
// Get the ticket URL as above and the downloadURL here points to the url where the content is present.
            System.out.println("contentRef.getUrl() : " + contentRef.getUrl());
            String ticketURL = "?ticket=" + ticket;
            downloadURL = contentRef.getUrl() + ticketURL;
            System.out.println("downloadURL in webService(): " + downloadURL);
        }
        catch(Throwable e)
        {
            System.out.println(e.toString());
        }
        finally
        {
            // End the session
            //AuthenticationUtils.endSession();           
        }
       return downloadURL;
    }

pankaj_dell
Champ in-the-making
Champ in-the-making
Hi I am accessing the alfresco repository via RMI in doing the same all ftl and js files come along with the documents.Now i want to access the content of a specific folder of Alfresco Share. I have used following code for RMI access.

—–RepositoryAccess.java—-

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import org.alfresco.repo.remote.ClientTicketHolderGlobal;
import org.alfresco.service.cmr.remote.RepoRemote;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.util.Pair;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class RepositoryAccess {
   
   private static void processChildren(RepoRemote repoRemote, NodeRef nodeRef,int i) {
      //if(nodeRef.toString().equals("workspace://SpacesStore/bc85728e-fb19-4a42-b020-2bbf1c18756b"))
         //xyz(repoRemote,nodeRef);
      for (int j = 0; j < i; j++) {
         System.out.print("\t");
         
      }
      if(nodeRef!=null){
      Map<String, Pair<NodeRef, Boolean>> children = repoRemote.getListing(nodeRef);
      for (String key : children.keySet()) {
         Pair<NodeRef, Boolean> pair = children.get(key);
         System.out.println(key+":=="+pair.getFirst().toString()+" —–"+pair.getSecond());
         if(!pair.getSecond())
         xyz(repoRemote,pair.getFirst(),key);
         processChildren(repoRemote,pair.getFirst(),i+1);
      }
      }
   }
public static void main(String[] args) {
      ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ctl-context.xml");
      AuthenticationService authService = (AuthenticationService) context.getBean("authenticationService");
      authService.authenticate("admin", "admin".toCharArray());
      ClientTicketHolderGlobal ticketHolder = (ClientTicketHolderGlobal) context.getBean("clientTicketHolder");
      ticketHolder.setTicket(authService.getCurrentTicket());
      RepoRemote repoRemote = (RepoRemote) context.getBean("repoRemote");
      NodeRef nodeRef = repoRemote.getRoot();
      System.out.println(nodeRef.toString());
      processChildren(repoRemote, nodeRef,0);
      }
public static void   xyz(RepoRemote repoRemote,NodeRef nodeRef,String name){
   
   System.out.println("___________________________________________________________________________________________________________________");
         try {
             InputStream fis =  repoRemote.readFile(nodeRef)   ;
            OutputStream out = new FileOutputStream("C:/Users/pankaj_shukla1/Desktop/AlfrescoRepo/"+name);
               try {
                   byte[] buffer = new byte[1024];
                   int len = 0;
                   while ((len = fis.read(buffer)) > 0) {
                      out.write(buffer, 0, len);
                      System.out.println("WRITING");
                   }
               } finally {
                   fis.close();
               }
           } catch (FileNotFoundException e) {
               System.err.println(e);
           } catch (IOException e) {
               System.err.println("Cannot read file: "
                       + e);
           }
          System.out.println("___________________________________________________________________________________________________________________");
    }


}

—–ctl-context.xml——-

<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE beans PUBLIC '-//SPRING//DTD BEAN//EN' 'http://www.springframework.org/dtd/spring-beans.dtd'>



<beans>

    <!– Client Ticket Holder –>

    <bean id="clientTicketHolder" class="org.alfresco.repo.remote.ClientTicketHolderGlobal"/>



    <!– Remote AVM interface –>

    <bean id="avmRemote" class="org.alfresco.repo.remote.AVMRemoteImpl">

        <property name="avmRemoteTransport">

            <ref bean="avmRemoteTransport"/>

        </property>

        <property name="clientTicketHolder">

            <ref bean="clientTicketHolder"/>

        </property>

    </bean>



    <bean id="avmRemoteTransport" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">

        <property name="serviceUrl">

            <value>rmi://localhost:50500/avm</value>

        </property>

        <property name="serviceInterface">

            <value>org.alfresco.service.cmr.remote.AVMRemoteTransport</value>

        </property>

        <property name="refreshStubOnConnectFailure">

            <value>true</value>

        </property>

    </bean>



   <bean id="avmSyncService" class="org.alfresco.repo.remote.AVMSyncServiceRemote">

       <property name="avmSyncServiceTransport">

          <ref bean="avmSyncServiceTransport"/>

       </property>

       <property name="clientTicketHolder">

           <ref bean="clientTicketHolder"/>

       </property>

   </bean>



    <bean id="avmSyncServiceTransport" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">

        <property name="serviceUrl">

            <value>rmi://localhost:50500/avmsync</value>

        </property>

        <property name="serviceInterface">

            <value>org.alfresco.service.cmr.remote.AVMSyncServiceTransport</value>

        </property>

        <property name="refreshStubOnConnectFailure">

            <value>true</value>

        </property>

    </bean>   



    <bean id="authenticationService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">

        <property name="serviceUrl">

            <value>rmi://localhost:50500/authentication</value>

        </property>

        <property name="serviceInterface">

            <value>org.alfresco.service.cmr.security.AuthenticationService</value>

        </property>

        <property name="refreshStubOnConnectFailure">

            <value>true</value>

        </property>

    </bean>



    <bean id="repoRemoteTransport" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">

        <property name="serviceUrl">

            <value>rmi://localhost:50500/repo</value>

        </property>

        <property name="serviceInterface">

            <value>org.alfresco.service.cmr.remote.RepoRemoteTransport</value>

        </property>

        <property name="refreshStubOnConnectFailure">

            <value>true</value>

        </property>

    </bean>



    <bean id="repoRemote" class="org.alfresco.repo.remote.RepoRemoteImpl">

        <property name="repoRemoteTransport">

            <ref bean="repoRemoteTransport"/>

        </property>

        <property name="clientTicketHolder">

            <ref bean="clientTicketHolder"/>

        </property>

    </bean>

</beans>


Please give me any suggestion asap.


Thanks in advance

fergunet
Champ in-the-making
Champ in-the-making
Is that line ok?:

String path = dir+"*[@cm:name=\"" + fileName + "\"]";

'Cause I've the following exception:

<ns1:message>Error executing xpath:
   xpath: myfolder*[@cm:name=&quot;myfile.txt&quot;]</ns1:message>


That's &quot; shuoldn't be there, I guess.

jtorres
Champ in-the-making
Champ in-the-making
I'm using a class Document to store information about nodes, so ignore this part of code.

Get the children of an specific folder (given its UUID)

   public List<Document> getElements(String Id){
        RepositoryServiceSoapBindingStub repositoryService = WebServiceFactory.getRepositoryService();        
        Reference reference = new Reference(STORE, Id, null);
        List<Document> results = new LinkedList<Document>();
      QueryResult childrenQueryResult;

      try {
         childrenQueryResult = repositoryService.queryChildren(reference);
           ResultSet childrenResultSet = childrenQueryResult.getResultSet();
           ResultSetRow[] rows = childrenResultSet.getRows();

            if (rows != null)
            {
               // Si entramos aquí, es que tiene hijos.
                // Obtenemos la información de cada fila y vamos construyendo la lista.
                for(ResultSetRow row : rows)
                {
                    String nodeId = row.getNode().getId();
                    Document contentResult = new Document(nodeId);
                    this.fillDocument(contentResult, row);
                    results.add(contentResult);
                }
            }

      } catch (RepositoryFault e) {
         System.out.println("Datos no encontrados.");
      } catch (RemoteException e) {
         System.out.println("Error de servicio remoto.");
      }
      return results;
   }


Get  metadata of a file / folder, given its UUID:

   public List<String> getMetadata(String Id){
      List<String> lista = new LinkedList<String>();
      Node nodo = getNode(Id);
      String[] aspects = nodo.getAspects();
      for (int i = 0; i < aspects.length; i++) {
         lista.add(aspects[i]);
      }
      return lista;
   }


Auxiliary function to get a node given its UUID

    protected Node getNode(String uuid){
      RepositoryServiceSoapBindingStub repositoryService = WebServiceFactory.getRepositoryService();

      Node myNode = null;
      Reference reference = new Reference(STORE, uuid, null);
      Predicate predicate = new Predicate(new Reference[]{reference}, null, null);
      Node[] nodes;

      try {
         nodes = repositoryService.get(predicate);
         // Obtenemos el nodo.
         myNode = nodes[0];
      } catch (RepositoryFault e) {
         System.out.println("Datos no encontrados.");
      } catch (RemoteException e) {
         System.out.println("Error de servicio remoto.");
      }
      
      return myNode;
      
   }


Getting the content of a text file (I suposse it works with any file, you obtain the content as a String)

   public String getData(String Id){
       String result = null;
        try {
            // Obtener el servicio adecuado.
            ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();       

            // Construimos la Referencia en base a su UUID.
            Node nodo = this.getNode(Id);
          Reference ref = nodo.getReference();
          
            // Leemos del repositorio el elemento.
         Content[] readResult = contentService.read(
                                             new Predicate(new Reference[]{ref}, STORE, null),
                                             Constants.PROP_CONTENT);
            Content content = readResult[0];
 
            // Obtenemos el contenido a partir de su URL y se muestra.
            System.out.println(ContentUtils.getContentAsString(content));
         result = ContentUtils.getContentAsString(content);
           
      } catch (ContentFault e) {
         System.out.println("No se ha podido leer el fichero.");
      } catch (RemoteException e) {
         System.out.println("Error de servicio.");
      }
         
      return result;
   }


Hope it helps you.

bindiya
Champ in-the-making
Champ in-the-making
Hi

Is it possible to read the text from the content and write it on jsp page?
I need to display html content in a jsp page.

Thanks,
Bindiya

fhomasp
Champ in-the-making
Champ in-the-making
//String dir = "/app:company_home/cmSmiley TongueCMCOE/cm:COE1/";
            String path = dir+"*[@cm:name="" + fileName + ""]";
            Reference reference = new Reference(storeRef, null, path);
            ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();

Is this still valid for Alfresco 2.9B ?  I can't seem to get it right.
I keep getting a ServerException saying:
{http://www.alfresco.org/ws/service/repository/1.0}RepositoryFault:<ns1:errorCode>0</ns1:errorCode><ns1:message>java.lang.IllegalArgumentException: A uuid or a path must be supplied to resolve to a NodeRef</ns1:message>

And in another class it tells me the x-path is incorrect or no available node is referencable.

evilsephiroth
Champ in-the-making
Champ in-the-making
I'm using a class Document to store information about nodes, so ignore this part of code.

Get the children of an specific folder (given its UUID)

   public List<Document> getElements(String Id){
        RepositoryServiceSoapBindingStub repositoryService = WebServiceFactory.getRepositoryService();        
        Reference reference = new Reference(STORE, Id, null);
        List<Document> results = new LinkedList<Document>();
      QueryResult childrenQueryResult;

      try {
         childrenQueryResult = repositoryService.queryChildren(reference);
           ResultSet childrenResultSet = childrenQueryResult.getResultSet();
           ResultSetRow[] rows = childrenResultSet.getRows();

            if (rows != null)
            {
               // Si entramos aquí, es que tiene hijos.
                // Obtenemos la información de cada fila y vamos construyendo la lista.
                for(ResultSetRow row : rows)
                {
                    String nodeId = row.getNode().getId();
                    Document contentResult = new Document(nodeId);
                    this.fillDocument(contentResult, row);
                    results.add(contentResult);
                }
            }

      } catch (RepositoryFault e) {
         System.out.println("Datos no encontrados.");
      } catch (RemoteException e) {
         System.out.println("Error de servicio remoto.");
      }
      return results;
   }


Get  metadata of a file / folder, given its UUID:

   public List<String> getMetadata(String Id){
      List<String> lista = new LinkedList<String>();
      Node nodo = getNode(Id);
      String[] aspects = nodo.getAspects();
      for (int i = 0; i < aspects.length; i++) {
         lista.add(aspects[i]);
      }
      return lista;
   }


Auxiliary function to get a node given its UUID

    protected Node getNode(String uuid){
      RepositoryServiceSoapBindingStub repositoryService = WebServiceFactory.getRepositoryService();

      Node myNode = null;
      Reference reference = new Reference(STORE, uuid, null);
      Predicate predicate = new Predicate(new Reference[]{reference}, null, null);
      Node[] nodes;

      try {
         nodes = repositoryService.get(predicate);
         // Obtenemos el nodo.
         myNode = nodes[0];
      } catch (RepositoryFault e) {
         System.out.println("Datos no encontrados.");
      } catch (RemoteException e) {
         System.out.println("Error de servicio remoto.");
      }
      
      return myNode;
      
   }


Getting the content of a text file (I suposse it works with any file, you obtain the content as a String)

   public String getData(String Id){
       String result = null;
        try {
            // Obtener el servicio adecuado.
            ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();       

            // Construimos la Referencia en base a su UUID.
            Node nodo = this.getNode(Id);
          Reference ref = nodo.getReference();
          
            // Leemos del repositorio el elemento.
         Content[] readResult = contentService.read(
                                             new Predicate(new Reference[]{ref}, STORE, null),
                                             Constants.PROP_CONTENT);
            Content content = readResult[0];
 
            // Obtenemos el contenido a partir de su URL y se muestra.
            System.out.println(ContentUtils.getContentAsString(content));
         result = ContentUtils.getContentAsString(content);
           
      } catch (ContentFault e) {
         System.out.println("No se ha podido leer el fichero.");
      } catch (RemoteException e) {
         System.out.println("Error de servicio.");
      }
         
      return result;
   }


Hope it helps you.

Thanks for your help. I've done all i need with your scripts Smiley Very Happy

kikinsama
Champ in-the-making
Champ in-the-making
Hi all:

I'm using the following method to get the URL from a content (file) saved in the repository.

Content[] readResult = contentService.read(
new Predicate(new Reference[]{reference}, storeRef, null),
Constants.PROP_CONTENT);
Content contentRef = readResult[0];

// Get the ticket URL as above and the downloadURL here points to the url where the content is present.
System.out.println("contentRef.getUrl() : " + contentRef.getUrl());
String ticketURL = "?ticket=" + ticket;
downloadURL = contentRef.getUrl() + ticketURL;

However, when the file contains blank spaces, those are replaced with "+" characters in the URL. I'm  wondering if there is another method to get the content URL. Or maybe someone could explain why this webservice has this behaviour.

Thanks in advance.

kikinsama
Champ in-the-making
Champ in-the-making
Ok, to answer my own question. The problem was that the content URL was encoded. The solution was to decode the URL, like this:

downloadURL = URLDecoder.decode(contentRef.getUrl(),"UTF-8") + ticketURL; 

Maybe this is useful to someone.