cancel
Showing results for 
Search instead for 
Did you mean: 

Problem downloading file using Alfresco Webservice

radheya
Champ in-the-making
Champ in-the-making
Hi,
I'm developing a demo project on using Alfresco webservice to upload and download a file.
Now facing one peculiar problem while downloading. i.e. i can download a file which is uploaded into alfresco repository using Alfresco Web Client, but i'm unable to download when it is uploaded through my code(where i'm using Alfresco webservice).

I'd really appreciate a lot if anybody could look at this problem.

Following are the 2 servlets where i'm uploading and downloading a file respectively.


UploadFileAction.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  String msg="";
  try
  {
      String fileName="";
      String title=request.getParameter("title").trim();
      String description=request.getParameter("description").trim();
      String path = request.getParameter("file");
     
      path = path.replaceAll("\\\\", "/");
      fileName = path.substring(path.lastIndexOf('/')+1,path.length());
     
    String ext= fileName.substring(fileName.lastIndexOf('.')+1,fileName.length());
    String contType="";
   
    if(ext.equals("txt"))
      contType = "text/plain";
    else if (ext.equals("xls"))
      contType = "application/vnd.ms-excel";
    else if (ext.equals("doc"))
      contType = "application/msword";
    else if (ext.equals("html") || ext.equals("htm"))
      contType = "text/html";
    else if (ext.equals("jpg") || ext.equals("jpeg"))
      contType = "image/jpeg";
    else if (ext.equals("bmp"))
      contType = "image/bmp";
    else if (ext.equals("pdf"))
      contType = "application/pdf";
    else if (ext.equals("ppt"))
      contType = "application/vnd.ms-powerpoint";
    else if(ext.equals("xml"))
      contType = "text/xml";
    else if (ext.equals("zip"))
      contType = "application/vnd.ms-zip";
   
    if(contType.equals(""))
    {
      msg="Unknown file format. File not uploded.";
    }
    else
    {
        WebServiceFactory.setEndpointAddress("http://172.19.148.42:8080/alfresco/api");
        AuthenticationUtils.startSession("admin", "admin");
       
          // Create a reference to the parent where we want to create content
          Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
          ParentReference companyHomeParent = new ParentReference(storeRef, null, "/app:company_home/cm:bneps", Constants.ASSOC_CONTAINS, null);

          RepositoryServiceSoapBindingStub repositoryService =WebServiceFactory.getRepositoryService();
          ContentServiceSoapBindingStub contentService =WebServiceFactory.getContentService();
          NamedValue[] contentProps = new NamedValue[1];
          NamedValue[] titledProps = new NamedValue[2];

        // Assign name
          companyHomeParent.setChildName("cm:" + fileName);

          contentProps[0] = Utils.createNamedValue(Constants.PROP_NAME, fileName);
          //Construct CML statement to add titled aspect
          titledProps[0] = Utils.createNamedValue(Constants.PROP_TITLE, title);
          titledProps[1] = Utils.createNamedValue(Constants.PROP_DESCRIPTION, description);

          CMLAddAspect addAspect = new CMLAddAspect(Constants.ASPECT_TITLED, titledProps, null, "1");

          //create content
          // Construct CML statement to create content node
          // Note: Assign "1" as a local id, so we can refer to it in subsequent
          // CML statements within the same CML block
          CMLCreate create = new CMLCreate("1", companyHomeParent, companyHomeParent.getUuid(), Constants.ASSOC_CONTAINS, null, Constants.PROP_CONTENT, contentProps);
          // Construct CML Block
          CML cml = new CML();
          cml.setCreate(new CMLCreate[] {create});
          cml.setAddAspect(new CMLAddAspect[] {addAspect});
          // Issue CML statement via Repository Web Service and retrieve result
          // Note: Batching of multiple statements into a single web call
          UpdateResult[] result = repositoryService.update(cml);
          Reference content = result[0].getDestination();
          // Write some content
          FileInputStream is = new FileInputStream(path);
          byte[] bytes = ContentUtils.convertToByteArray(is);

          ContentFormat format = new ContentFormat(contType, "UTF-8");
          // Write the content
          contentService.write(content, Constants.PROP_CONTENT, bytes, format);
          msg="File Uploaded Successfully";
    }    
  }
  catch(Exception e)
  {
    msg="Error uploading file";
    System.out.println("Error uploading file : "+e);
    System.out.println(e.toString());
  }
  finally
  {
      // End the session
      AuthenticationUtils.endSession();
  }
  request.setAttribute("msg",msg);
  RequestDispatcher rd=request.getRequestDispatcher("StatusMessage.jsp");
  rd.forward(request,response);
}



DownloadFileAction.java

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
  String fileName=request.getParameter("fileName");

  WebServiceFactory.setEndpointAddress("http://172.19.148.42:8080/alfresco/api");
 
  /**Start the session*/
  AuthenticationUtils.startSession("admin", "admin");
 
  /** Make sure Service Folder has been created,or download files will be failure */
  boolean Success = true;
  Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
  String parentSpace = "/app:company_home/cm:bneps";
  Reference SAMPLE_FOLDER = new Reference(storeRef, null, parentSpace);
   
  try
  {
        WebServiceFactory.getRepositoryService().get(new Predicate(new Reference[]{SAMPLE_FOLDER}, storeRef, null));
  }
  catch (Exception exception)
  {
    System.out.println("Error while getting repository service");
    Success=false;
  }
 
  /**Download files,if exception then "Success = False" */
  try
  {
    if(Success)
    {
      ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
      Reference contentReference = new Reference(storeRef,null,parentSpace+"/cm:"+fileName);
      Content[] readResult = contentService.read(new Predicate(new Reference[]{contentReference}, storeRef, null), Constants.PROP_CONTENT);
      for(Content content: readResult)
      {
        String[] splitedUrl = content.getUrl().split("/");
        if(splitedUrl[splitedUrl.length-1].equals(fileName))
        {
         
            InputStream in=ContentUtils.getContentAsInputStream(content);
         
          response.reset();
          response.setHeader ("Content-Disposition", "attachment;filename=\""+fileName+"\"");
          ServletOutputStream sosStream = response.getOutputStream();

          int ibit = 256;
             while ((ibit) >= 0)
             {
                ibit = in.read();
                sosStream.write(ibit);
             }
            
             sosStream.flush();
             sosStream.close();
             in.close();
        }
      }
    }
  }
  catch(ClientAbortException e)
  {
    System.out.println("File download cancelled by the user");
  }
  catch(Exception e)
  {
    System.out.println("Error downloading file : "+e);
  }
  /** End the session*/
  AuthenticationUtils.endSession();
}


Thanks a lot
Radheya
17 REPLIES 17

mandavasateesh
Champ in-the-making
Champ in-the-making
Hi Radeya and Keerthi,

I am new to alfresco.
can you please give me the uploading , downloading project code to me.
i mean project struture and source code.

Thanks,
Satish.

mandavasateesh
Champ in-the-making
Champ in-the-making
Hi Radheya,

can you share your code. i am facing the problem while uploading the document.
you said that i got the code from forums, can you provide that link for me.

Thanks,
Satish.

jcustovic
Champ in-the-making
Champ in-the-making

mandavasateesh
Champ in-the-making
Champ in-the-making
Hi,

Thank you for your reply..

But, I have this file ContentReadAndWrite.java file.
I need to upload the file through jsp page,  i mean i need to upload the file available in our disk.
I need the code for uploadAction.java and DownloadAction.java files..

Thanks,
Satish.

mandavasateesh
Champ in-the-making
Champ in-the-making
Hi,

Anyone please help me in downloading a file from alfresco.
Please share the code for downloading a  document from alfresco.
jsp page and coprrecsponding action.

Thanks,
Satish.

mandavasateesh
Champ in-the-making
Champ in-the-making
Hi All,

I have tried using the Code given here but still I am facing the problem. Suggestions for fixing the problem will be helpful.

The code snippet I have used for upload is
 /** Admin user name and password used to connect to the repository */
    protected static final String USERNAME = "admin";
    protected static final String PASSWORD = "admin";
   
    /** The store used throughout the samples */
    protected static final Store STORE = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
   
    protected static final Reference SAMPLE_FOLDER = new Reference(STORE, null, "/app:company_home/cm:sample_folder9");
   
    public static void main(String args[]) throws Exception
    {
       WebServiceFactory.setEndpointAddress("http://localhost:8080/alfresco/api");
        AuthenticationUtils.startSession(USERNAME, PASSWORD);
        try
        {
            // Check to see if the sample folder has already been created or not
            WebServiceFactory.getRepositoryService().get(new Predicate(new Reference[]{SAMPLE_FOLDER}, STORE, null));
            ParentReference parentRef = new ParentReference();
            parentRef.setStore(STORE);
            parentRef.setUuid(SAMPLE_FOLDER.getUuid());
            parentRef.setPath(SAMPLE_FOLDER.getPath());
            parentRef.setAssociationType(Constants.ASSOC_CONTAINS);
            parentRef.setChildName(Constants.ASSOC_CONTAINS);
           
            NamedValue[] properties2 = new NamedValue[]{Utils.createNamedValue(Constants.PROP_NAME, "SampleContent1.txt")};
            CMLCreate create2 = new CMLCreate();
            create2.setParent(parentRef);
            create2.setProperty(properties2);
            create2.setType(Constants.TYPE_CONTENT);  

            CML cml2 = new CML();
            cml2.setCreate(new CMLCreate[] {create2});
             
              UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cml2);
             
            Reference contentNode = result[0].getDestination();
            ContentFormat format = new ContentFormat(Constants.MIMETYPE_TEXT_PLAIN, "UTF-8");
            byte[] content = "This is some test content provided by the Alfresco development team!".getBytes();
            Content content1 = WebServiceFactory.getContentService().write(contentNode,
                  Constants.PROP_CONTENT, content, format);

        }
        catch (Exception e){
              e.printStackTrace();
        }
    }
 

For Download is

  
    /** Admin user name and password used to connect to the repository */
    protected static final String USERNAME = "admin";
    protected static final String PASSWORD = "admin";
   
    /** The store used throughout the samples */
    protected static final Store STORE = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
    static String parentSpace = "/app:company_home/cm:sample_folder6";
    protected static final Reference SAMPLE_FOLDER = new Reference(STORE, null, parentSpace);
   
    static String fileName= "SampleContext.txt";
    static boolean success = true;
   
    protected static void downloadContent() throws Exception
    {
        try
        {
            // Check to see if the sample folder has already been created or not
            WebServiceFactory.getRepositoryService().get(new Predicate(new Reference[]{SAMPLE_FOLDER}, STORE, null));
        }
        catch (Exception exception)
        {
           System.out.println("Error while getting repository service");
           exception.printStackTrace();
           success=false;

        }
    }
   
    public static void main(String args[])   {
       try{
          
          AuthenticationUtils.startSession("admin", "admin");
          downloadContent();
          System.out.println("Success Value is "+success);
          if(success){
                ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
System.out.println("ISO9075.encode(fileName)"+ISO9075.encode(fileName));
                Reference contentReference = new Reference(STORE,null,parentSpace+"/cm:"+fileName);// Reference contentReference = new Reference(STORE,null,parentSpace);
System.out.println("UUID IS …….."+contentReference.getPath());
System.out.println("3"+fileName);                
                Content[] readResult = contentService.read(new Predicate(new Reference[]{contentReference}, STORE, null), Constants.PROP_CONTENT);
                System.out.println("Before for……."+readResult.length);
                System.out.println("URL is "+readResult[0].getUrl());
                System.out.println("Node is "+readResult[0].getNode().getUuid());

                for(Content content: readResult) {
                   String[] splitedUrl = content.getUrl().split("/");
                   
                   if(splitedUrl[splitedUrl.length-1].equals(fileName)){
System.out.println("Inside If");
                      InputStream in=ContentUtils.getContentAsInputStream(content);
//                      response.reset();
//                      response.setHeader ("Content-Disposition", "attachment;filename=\""+fileName+"\"");
//                      ServletOutputStream sosStream = response.getOutputStream();

                      int ibit = 256;
                      while ((ibit) >= 0)   {
                         ibit = in.read();
//                         sosStream.write(ibit);
                      }
//                      sosStream.flush();
//                      sosStream.close();
                      in.close();
                   }
                }
          }
       }catch (Exception e){
          e.printStackTrace();
       }
    }

The error message is as follows

Success Value is true
ISO9075.encode(fileName)SampleContext.txt
UUID IS ……../app:company_home/cm:sample_folder6/cmSmiley FrustratedampleContext.txt
3SampleContext.txt
AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.generalException
faultSubcode:
faultString:
faultActor:
faultNode:
faultDetail:
   {http://www.alfresco.org/ws/service/content/1.0}ContentFault:<ns1:errorCode>0</ns1:errorCode><ns1:message>Failed to resolve to a single NodeRef with parameters (store=workspaceSmiley FrustratedpacesStore uuid=null path=/app:company_home/cm:sample_folder6/cmSmiley FrustratedampleContext.txt), found 0 nodes.</ns1:message>
   {http://xml.apache.org/axis/}exceptionNameSmiley Surprisedrg.alfresco.repo.webservice.content.ContentFault
   {http://xml.apache.org/axis/}stackTrace:
   at org.alfresco.repo.webservice.content.ContentWebService.read(ContentWebService.java:100)
   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:852)
   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:user-88


   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
   at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
   at java.lang.reflect.Constructor.newInstance(Unknown Source)
   at java.lang.Class.newInstance0(Unknown Source)
   at java.lang.Class.newInstance(Unknown Source)
   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.content.ContentFault.getDeserializer(ContentFault.java:146)
   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.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.content.ContentServiceSoapBindingStub.read(ContentServiceSoapBindingStub.java:467)
   at org.alfresco.sample.webservice.DownloadContent.main(DownloadContent.java:85)

shikha
Champ in-the-making
Champ in-the-making
hi,
i also require a code for uploading a file from jsp to alfresco repository. could you provide me that.
i am facing problem while compiling the java file which is provided in this discussion.
could anybody help me in sharing class file through which i can upload file to alfresco repository.

thanks in advance.

mandavasateesh
Champ in-the-making
Champ in-the-making
hi all

i have been facing a problem with downloading a file from alfresco server.
the error is in AxisFault, which says the NodeRef is zero with Server.generalException.

can anybody provide the solution for it.

thanx in advance
mandava