cancel
Showing results for 
Search instead for 
Did you mean: 

Trouble creating a folder via web script

mikew
Champ in-the-making
Champ in-the-making
I’m attempting to write a very simple proof of concept stand-alone java program that communicates directly with a remote Alfresco server (3.0b) via web scripts. The program will, hopefully, recreate a local directory structure and upload local files into it. I am running into problems, specifically with http POST requests.

I am having no problems getting Alfresco tickets using login web script and no problem performing GET requests to:
GET /alfresco/service/api/path/{store_type}/{store_id}/{id}/descendants
to list the directory contents.

However, I am receiving a 400 response when I change the method to POST (either in code or via a form in an html page.)… with the message "Posting of media resource not supported"
POST /alfresco/service/api/path/{store_type}/{store_id}/{id}/descendants

I have been looking for guidance and inspiration here:
/alfresco/service/script/org/alfresco/repository/store/descendants.post

There are two js files listed:
File: org/alfresco/repository/store/descendants.post.atom.js
File: org/alfresco/repository/store/descendants.post.js

I'm guessing I'm hitting the latter (It issues a 400 response with the previously mentioned message) rather than the previous, which actually does the directory creation.

I'm also guessing I'm either taking the wrong approach entirely, or not constructing the POST request correctly (GET to the same URL returns a list of documents in the specified location).

My first question is: is this possible? If so, how would a POST request be constructed? I figure there must be some content in the POST (parameters: title or name, alf_ticket, typeId???)

Sorry if I'm missing something obvious, but any help or guidance would be appreciated.
17 REPLIES 17

lakshya
Champ in-the-making
Champ in-the-making
Hello Mike,
I am facing the exactly same problem. I am stuck from a long time.
I am using local server. Can you please send the solution if you got.

Your help will be highly appreciated.

Thanks in advance.

mikew
Champ in-the-making
Champ in-the-making
Hi Lakshya,
I did not solve this, instead had to take an entirely different tack. Instead of using webscripts, we ended up using the alfresco ftp mechanism, which seemed to work… (user with admin privileges needs to run the alfresco process for ftp to work, though…)

lakshya
Champ in-the-making
Champ in-the-making
Thanks Mike,
I got the solution… Smiley Happy
Actually we need to pass the details through xml.

Here is the code snippet:
URL = "http://localhost:8081/alfresco/service/api/path/workspace/SpacesStore/Company%20Home/children";
PostMethod method = new PostMethod(URL);
String filePath = "testDoc.xml";
String contentType = "application/atom+xml;type=entry";

File upload = new File(filePath);
method.setRequestHeader("name", upload.getName());
method.setRequestHeader("Content-type", contentType);

method.setRequestBody(new FileInputStream(upload));
client.executeMethod(method);
System.out.println(method.getResponseBodyAsString());


testDoc.xml
<?xml version='1.0' encoding='utf-8'?>
        <entry xmlns='http://www.w3.org/2005/Atom' xmlns:cmis='http://www.cmis.org/2008/05'>
         <title>My Picts</title>
         <summary>My Picts – Summary</summary>
          <content type="text/html">${CONTENT}</content>
         <cmisSmiley Surprisedbject>
          <cmisSmiley Tongueroperties>
           <cmisSmiley TongueropertyString cmis:name='ObjectTypeId'><cmis:value>document</cmis:value></cmisSmiley TongueropertyString>
          
          </cmisSmiley Tongueroperties>
         </cmisSmiley Surprisedbject>
       </entry>


Now I am checking that how I could pass the details in xml through Java.

Thanks for your reply….
Regards

cytrix
Champ in-the-making
Champ in-the-making
Thanks for your example Smiley Happy .

But it seems it doesn't create a space but a file. How create a space in Alfresco v3 ?

lakshya
Champ in-the-making
Champ in-the-making
Hello Cytrix,
For creating folder just change
<cmisSmiley TongueropertyString cmis:name='ObjectTypeId'><cmis:value>document</cmis:value></cmisSmiley TongueropertyString>
to
<cmisSmiley TongueropertyString cmis:name='ObjectTypeId'><cmis:value>folder</cmis:value></cmisSmiley TongueropertyString>

yino
Champ in-the-making
Champ in-the-making
Thanks, but it only works with text files. How can I pass a PDF through the XML? I tried using Base64 but I don't know how to tell the server the file that way, any ideas?

lakshya
Champ in-the-making
Champ in-the-making
Sorry…
I also faced the same problem Smiley Sad
If you get the solution please do send a post with solution..

schan
Champ in-the-making
Champ in-the-making
Here is a working source for reference.  Special thanks for all related articles in this forum.  Smiley Very Happy


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class CreateFolder {

   public static void main(String[] args) throws Exception {
      long start = System.currentTimeMillis();
      
      String host = "192.168.1.1";
      int port = 8080;
      String username = "admin";
      String password = "admin";
      String parentFolder = "Company Home";
      String folderName = "sales3";
      String description = "sales space3";
      String url = "http://" + host + ":" + port + "/alfresco/service/api/path/workspace/SpacesStore/" + parentFolder + "/children";
      String contentType = "application/atom+xml;type=entry";
      
      String xml =
         "<?xml version='1.0' encoding='utf-8'?>\n" +
         "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:cmis='http://www.cmis.org/2008/05'>\n" +
         "<title>" + folderName + "</title>\n" +
         "<summary>" + description + "</summary>\n" +
         "<cmis:object>\n"+
         "<cmis:properties>\n" +
         "<cmis:propertyString cmis:name='ObjectTypeId'>\n" +
         "<cmis:value>folder</cmis:value>\n" +
         "</cmis:propertyString>\n" +
         "</cmis:properties>\n" +
         "</cmis:object>\n" +
         "</entry>\n";
      
      DefaultHttpClient httpclient = new DefaultHttpClient();

      httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(host, port),
            new UsernamePasswordCredentials(username, password));
      
      HttpPost httppost = new HttpPost(url);
      httppost.setHeader("Content-type", contentType);
      
      StringEntity requestEntity = new StringEntity(xml, "UTF-8");
      httppost.setEntity(requestEntity);

      
      System.out.println("executing request" + httppost.getRequestLine());
      HttpResponse response = httpclient.execute(httppost);
      HttpEntity entity = response.getEntity();

      System.out.println("—————————————-");
      System.out.println(response.getStatusLine());
      if (entity != null) {
         System.out.println("Response content type: " + entity.getContentType());
         long contentLength = entity.getContentLength();
         System.out.println("Response content length: "
               + entity.getContentLength());
         
         if (contentLength > 0) {
            byte [] b = new byte[(int) contentLength];
            entity.getContent().read(b);
            System.out.println("Response content: " + new String(b));
         }
         
         entity.writeTo(System.out);
      }

      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpclient.getConnectionManager().shutdown();
      long end = System.currentTimeMillis();
      System.out.println("Time spend: " + (end-start) + "ms");
   }
}

schan
Champ in-the-making
Champ in-the-making
Here is another working sample to upload files.  Tested for pfd and word.  Again, special thanks for all related articles in this forum.  Smiley Very Happy


import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Collection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import sun.misc.BASE64Encoder;
import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil;
import eu.medsea.mimeutil.MimeUtil2;

/**
* A simple example that uses HttpClient to execute an HTTP request against a
* target site that requires user authentication.
*/
public class UploadDocument {

   public static void main(String[] args) throws Exception {
      long start = System.currentTimeMillis();
      
      String host = "192.168.21.111";
      int port = 8080;
      String username = "admin";
      String password = "admin";
      String parentFolder = "Company Home";
      String filePath = "test.pdf";
      String description = "PDF upload test";
      String author = "admin";
      String url = "http://" + host + ":" + port + "/alfresco/service/api/path/workspace/SpacesStore/" + parentFolder + "/children";
      String contentType = "application/atom+xml;type=entry";

      BASE64Encoder encoder = new BASE64Encoder();
      
      File file = new File(filePath);
       FileInputStream fis = new FileInputStream(file);
       DataInputStream dis = new DataInputStream(fis);
       // Create the byte array to hold the data
       byte[] bytes = new byte[(int) file.length()];
       dis.readFully(bytes);
      
       Collection<MimeType> mimeTypes = MimeUtil.getMimeTypes(file);
       MimeType mimeType = MimeUtil.getMostSpecificMimeType(mimeTypes);
       if(mimeType == null) mimeType = MimeUtil2.UNKNOWN_MIME_TYPE;      
      
      String xml =
         "<?xml version='1.0' encoding='utf-8'?>\n" +
         "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:cmis='http://www.cmis.org/2008/05'>\n" +
         "<title>" + file.getName() + "</title>\n" +
         "<summary>" + description + "</summary>\n" +
         "<author>" + author + "</author>\n" +
         "<content type='" + mimeType.toString() + "'>" + encoder.encode(bytes) + "</content>\n" +
         "<cmis:object>\n"+
         "<cmis:properties>\n" +
         "<cmis:propertyString cmis:name='ObjectTypeId'>\n" +
         "<cmis:value>document</cmis:value>\n" +
         "</cmis:propertyString>\n" +
         "</cmis:properties>\n" +
         "</cmis:object>\n" +
         "</entry>\n";
            
      DefaultHttpClient httpclient = new DefaultHttpClient();

      httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(host, port),
            new UsernamePasswordCredentials(username, password));
      
      HttpPost httppost = new HttpPost(url);
      httppost.setHeader("Content-type", contentType);
      
      StringEntity requestEntity = new StringEntity(xml, "UTF-8");
      httppost.setEntity(requestEntity);

      System.out.println("executing request" + httppost.getRequestLine());
      HttpResponse response = httpclient.execute(httppost);
      HttpEntity entity = response.getEntity();

      System.out.println("—————————————-");
      System.out.println(response.getStatusLine());
      if (entity != null) {
         System.out.println("Response content type: " + entity.getContentType());
         long contentLength = entity.getContentLength();
         System.out.println("Response content length: "
               + entity.getContentLength());
         
         if (contentLength > 0) {
            byte [] b = new byte[(int) contentLength];
            entity.getContent().read(b);
            System.out.println("Response content: " + new String(b));
         }
         
         entity.writeTo(System.out);
      }

      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpclient.getConnectionManager().shutdown();
      long end = System.currentTimeMillis();
      System.out.println("Time spend: " + (end-start) + "ms");
   }
}