cancel
Showing results for 
Search instead for 
Did you mean: 

[EXAMPLE] Create folder structure (JSON format)

sufo
Star Contributor
Star Contributor
This example creates folder structure under the Company Home or if the path specified under the Company Home/path. Folder structure is  received as JSON from HTTP POST.
It ignores already existing folders so you can run it again and again just adding new items to the JSON structure.

file: folders.post.desc.xml

<webscript>
   <shortname>Create folders</shortname>
   <description><![CDATA[Create folders under the specified path, otherwise directly under the Company Home.<br>Expected JSON structure example:
<pre>{
   "folders":
   [
      {
         "name":"TravelAgency",
         "children":
         [
            {
               "name":"Tours",
               "children":
               [
                  {
                     "name":"Schedules"
                  },
                  {
                     "name":"Images"
                  }
               ]
            },
            {
               "name":"Clients"
            },
            {
               "name":"Agencies"
            }
         ]
      }
   ]
}</pre>
]]></description>
   <url>/ta/folders?path={path?}</url>
    <arg>
        <shortname>path</shortname>
        <description><![CDATA[existing path under the Company Home]]></description>
    </arg>
   <format default="json">argument</format>
   <authentication>user</authentication>
   <transaction>required</transaction>
</webscript>
file: folders.post.json.js

model.folders = createFolders();

function createFolders() {
   try {
      var path = args["path"];
      if(!json.has("folders")) {
            return({"status" : {"code" : 2000, "name" : "Incorrect data error", "description" : "Operation(s) failed - incorrect or no data received."}, "message" : "createFolders - failed (incorrect or no data received)"});
      }
      var folders = json.get("folders");
      if(path == null || path == "") {
         createSubFolders(companyhome, folders);
         return({"status" : {"code" : 1000, "name" : "Success", "description" : "Operation(s) successfully completed."}, "message" : "createFolders in Company Home - successful"});
      } else {
         var folder = companyhome.childByNamePath("/" + path);
         if(folder != null) {
            createSubFolders(folder, folders);
            return({"status" : {"code" : 1000, "name" : "Success", "description" : "Operation(s) successfully completed."}, "message" : "createFolders in Company Home/" + path + " - successful"});
         } else {
            return({"status" : {"code" : 2001, "name" : "Error", "description" : "Operation(s) failed."}, "message" : "createFolders in Company Home/" + path + " - failed (path does not exist)"});
         }
      }
   } catch(e) {
      status.setCode(status.STATUS_INTERNAL_SERVER_ERROR, e.toString());
      return;
   }
}

function createSubFolders(folderNode, folders) {
   for(var i = 0, len = folders.length(); i < len; i++) {
      var folder = folders.getJSONObject(i);
      if(folder.has("name")) {
         var subFolderNode = folderNode.childByNamePath("/" + folder.get("name"));
         if(subFolderNode == null) {
            subFolderNode = folderNode.createFolder(folder.get("name"));
         }
         if(folder.has("children")) {
            createSubFolders(subFolderNode, folder.getJSONArray("children"));
         }
      }
   }
}
file: folders.post.json.ftl
<#escape x as jsonUtils.encodeJSONString(x)>
<#if folders?is_hash && folders.status?has_content>
{"status" : {"code" : ${folders.status.code?c!9998}, "name" : "${folders.status.name!"Unspecified code"}", "description" : "${folders.status.description!""}"}, "message" : "${folders.message!""}"}
<#else>
{"status" : {"code" : 9999, "name" : "Unspecified error", "description" : "WebScript did not return expected response."}, "message" : "WebScript did not return expected response."}
</#if>
</#escape>
Simple test (using dojo.rawXhrPost())
file: create-folders-test.html

<html>
<head><title>Create folders test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js" djConfig="parseOnLoad: true"></script>
</head>
<body>
<div>Folder structure to create (JSON structure to send to WebScript):</div>
<textarea id="folderStructure" cols="80" rows="30">
{
   "folders":
   [
      {
         "name":"TravelAgency",
         "children":
         [
            {
               "name":"Tours",
               "children":
               [
                  {
                     "name":"Schedules"
                  },
                  {
                     "name":"Images"
                  }
               ]
            },
            {
               "name":"Clients"
            },
            {
               "name":"Agencies"
            }
         ]
      }
   ]
}
</textarea>
<div><input type="button" value="Create folders" onClick="createFolders()"></div>
<div>Result (JSON structure received from WebScript):</div>
<pre id="result"></pre>
</body>
<script>
function createFolders() {
   var resultPre = document.getElementById("result");
   var folderStructure = document.getElementById("folderStructure").value;
   resultPre.innerHTML = "";
   dojo.rawXhrPost({
            postData: folderStructure,
                url: "http://localhost:8080/alfresco/service/ta/folders?path=User%20Homes",
            headers: {"Content-Type": "application/json;charset=UTF-8"},
                handleAs: "json",
            load: function(result) { document.getElementById("result").innerHTML = JSON.stringify(result); },
            error: function(error) { console.debug(error); }
         });
}
</script>
</html>
6 REPLIES 6

mrogers
Star Contributor
Star Contributor
Please add this to the wiki so more people will find it.

sufo
Star Contributor
Star Contributor
Sorry, I am completely lost, I have never contributed to the wiki. I have registered to the Alfresco wiki, but do not know how to create new article or category or how it is called.
I am working on a new project and plan to build full sort of various web scripts using JSON format to be used by a browser application using either Dojo or jQuery (not decided yet).
I have no problem to share my work, but it would help me if you have some link with explanation on how to create new article or category (and rules to be followed if there are any imposed by Alfresco).
I imagine something like: Web Scripts examples - JSON format

tapan_d_thakkar
Champ in-the-making
Champ in-the-making
hi,

can you tell me in your *.post.desc.xml you have used tag like..
<format default="json">argument</format>
why here we need to put "argument" .. ?

cant we put it like <format default="json"></format> . ?

thanks.

suryabadami
Champ in-the-making
Champ in-the-making
I have added this Webscript successfully , but not able to invoke them.
Can you please provide me with the examples of URL's which can be used to invoke this WebScript.

davidez
Champ in-the-making
Champ in-the-making
Hi! I have tried your example but I have a problem: when I click on "Create folders"  button I receive a null response.
In the log I have this exception:

11:39:15,547  ERROR [extensions.webscripts.AbstractRuntime] Exception from executeScript - redirecting to status template error: 03260014 Script url /ta/folders does not support the method OPTIONS
org.springframework.extensions.webscripts.WebScriptException: 03260014 Script url /ta/folders does not support the method OPTIONS
   at org.springframework.extensions.webscripts.AbstractRuntime.executeScript(AbstractRuntime.java:159)
   at org.springframework.extensions.webscripts.servlet.WebScriptServlet.service(WebScriptServlet.java:118)
   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.alfresco.web.app.servlet.GlobalLocalizationFilter.doFilter(GlobalLocalizationFilter.java:58)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
   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.Http11AprProcessor.process(Http11AprProcessor.java:859)
   at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
   at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1555)
   at java.lang.Thread.run(Thread.java:619)

what do you think about?

sufo
Star Contributor
Star Contributor
To: SuryaBadami
You have to create the file (create-folders-test.html) and edit it to change the address to your alfresco server (url parameter for the dojo.rawXhrPost).
Then put it somewhere in your server. For Tomcat, just put it in [alfrescodir]/tomcat/webapps/ROOT and then open it like http://yourserver:8080/create-folders-test.html .

To: davidez
The html file which calls the webscript has to be on the same server as Alfresco (same domain to be exact) to avoid issues with cross-domain AJAX.
Check these links for more info: http://stackoverflow.com/questions/6516232/dojo-xhrget-only-returning-null http://stackoverflow.com/questions/4107576/dojo-ajax-request-asking-for-options