AnsweredAssumed Answered

[EXAMPLE] Create folder structure (JSON format)

Question asked by sufo on Feb 5, 2011
Latest reply on May 17, 2012 by sufo
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>

Outcomes