Sending content to java webscript via POST method

Yesterday I stucked on problem of getting data from WebScriptRequest, which were sent by POST method. There is some bug in Apache Tomcat, so there is a simple workaround described for example here. My task was to create webscript, which tries to find a file in repository (or create it, if it doesn't exist) and to write content inside – data of POST request.

Yesterday I stucked on problem of getting data from WebScriptRequest, which were sent by POST method. There is some bug in Apache Tomcat, so there is a simple workaround described for example here. My task was to create webscript, which tries to find a file in repository (or create it, if it doesn’t exist) and to write content inside – data of POST request.

My webscript is Java backed, so only description in WEB-INF/classes/alfresco/templates/client/webscripts/org/alfresco/archivace is needed:

<webscript>
<shortname>SaveModif file</shortname>
<description>Ulozi dorucena data do *.modif.xml</description>
<url>/archivace/savemodif?nodeRef={noderef}</url>
<authentication>user</authentication>
<transaction>required</transaction>
</webscript>

Also definition in web-scripts-application-context.xml:

<bean id=“webscript.org.alfresco.archivace.savemodif.post“ class=“cz.shmoula.webscripts.SaveModif“ parent=“webscript“>
<property name=“authenticationComponent“ ref=“AuthenticationComponent“/>
<property name=“nodeService“ ref=“NodeService“/>
<property name=“searchService“ ref=“SearchService“/>
<property name=“fileFolderService“ ref=“FileFolderService“/>
<property name=“contentService“ ref=“ContentService“/>
</bean>

Now let’s get Node object itself:

// try to get DescriptionNode
Node xmlNode = getDescriptionNode(nodeRef);

// if DescriptionNode doesn’t exist, create one
if (xmlNode == null) {
String path = noda.getName();
String filename = path.substring(0, path.lastIndexOf(„.“)) + „.modif.xml“;
NodeRef spaceRef = nodeService.getPrimaryParent(noda.getNodeRef()).getParentRef();
xmlNode = createDescriptionNode(spaceRef, filename);
}

At this time in xmlNode is Node object – either existing one, or created one, so let’s write that request content inside:

ContentWriter writer = contentService.getWriter(xmlNode.getNodeRef(), ContentModel.PROP_CONTENT, true);
writer.putContent(req.getContent().getInputStream());

Simple, but sometimes it doesnt work. Why? Due to that bug mentioned in perex. So how are data sent through POST method? Let’s try it with wget:

wget –post-data=’pokus‘ –http-user=admin –http-password=admin http://localhost:8080/alfresco/service/archivace/savemodif?nodeRef=workspace://SpacesStore/91919928-3709-4e2e-a829-b0be46976e42

Captured request looks like this

Image and video hosting by TinyPic

As you can see, everything looks ok. But getContent() in our webscript is empty. Why? there is no content – there are just parameters, due to application/x-www-form-urlencoded content type. So req.getParameterNames() returns String[] array in which are in our case two parameters: {{nodeRef}, {pokus}}. This is not what we want, because length ot these parameter names may be limited (2M?). So let’s use mentioned advice – change content-type:

wget –post-data=’pokus‘ –header=’Content-Type: text/xml‘ –http-user=admin –http-password=admin http://localhost:8080/alfresco/service/archivace/savemodif?nodeRef=workspace://SpacesStore/91919928-3709-4e2e-a829-b0be46976e42

And now it works! 🙂 Sniffed request looks like before, just content-type header line had changed:

Image and video hosting by TinyPic

Now is possible to send inputStream of content to Writer:

writer.putContent(req.getContent().getInputStream());

At this time req.getParameterNames() has just one parameter – {{nodeRef}} and content is really saved in data field.

Delete dialog workaround

Write this one, or not to write this blogpost? That is the question :-). But I would like to simply remember for some things i did, so let's do it! In my DMS I have some multimedia content saved and this content has attached description in xml file. Also I have my own space view (more info here), so I show just that multimedia content. In case of deletion that content I want to delete that xml too, so how to do that?

Write this one, or not to write this blogpost? That is the question :-). But I would like to simply remember for some things i did, so let's do it! In my DMS I have some multimedia content saved and this content has attached description in xml file. Also I have my own space view (more info here), so I show just that multimedia content. In case of deletion that content I want to delete that xml too, so how to do that?

First we need to create an action (it's just a copy of original action ;-)) specification in web-client-config and name it – in my case "delete_doc_shm":

<action id="delete_doc_shm">
    <permissions>
        <permission allow="true">Delete</permission>
    </permissions>
    <evaluator>org.alfresco.web.action.evaluator.DeleteDocEvaluator</evaluator>
    <label-id>delete</label-id>
    <image>/images/icons/delete.gif</image>
    <action-listener>#{BrowseSessionBean.deleteFile}</action-listener>
    <params>
        <param name="id">#{actionContext.id}</param>
        <param name="ref">#{actionContext.nodeRef}</param>
    </params>
</action>

It's pretty simple, just a definition of action with Evaluator and wanted permissions. I wrote a blogpost about this a year about :-). Now I have an action, so I need to add it into some group, or view link directly. Action groups are defined in web-client-config too:

<action-group id="session_browse">
    <show-link>false</show-link>
    <style-class>inlineAction</style-class>
    .  .  .
     <action idref="delete_doc_shm" />
</action-group>

And view of this group is realised by actions component (r variable is variable defined by richListComponent, library prefix r is Alfresco's repo taglib):

.  .  .
<r:actions id="actions_menu_1" value="session_browse" context="#{r}" showLink="false" styleClass="inlineAction" />
.  .  .  

The result's like this (there's no difference in original view of that actions menu and this, but functionality – see below ;-)):

Image and video hosting by TinyPic

Now some application logic: In case of pressing our delete butto, BrowseSessionBean.deleteFile() method is called. This method just do same things that original BrowseBean.deleteFile() does, but redirects to my own dialog:

public void deleteFile(ActionEvent event) {
    .  .  .  some foo – bar stuff  .  .  .
    FacesContext fc = FacesContext.getCurrentInstance();
    NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
    navigationHandler.handleNavigation(fc, null, "dialog:deleteVcfFile");
}

This dialog is defined in web-client-config like

<dialog
    name="deleteVcfFile"
    page="/jsp/dialog/delete.jsp"
    managed-bean="DeleteVcfContentDialog"
    icon="/images/icons/delete_large.gif"
    title-id="delete_file"
    description-id="delete_file_info" />

and points to DeleteVcfContentDialog bean:

<managed-bean>
    <description>The bean that backs up the Delete Content Dialog</description>
    <managed-bean-name>DeleteVcfContentDialog</managed-bean-name>
    <managed-bean-class>cz.shmoula.dialog.DeleteVcfContentDialog</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    <managed-property>
        <property-name>navigator</property-name>
        <value>#{NavigationBean}</value>
    </managed-property>
    .  .  .  more properties  .  .  .
</managed-bean>

Class managing this bean extends DeleteContentDialog and has only one method – finishImpl. See following source, it's commented:

public class DeleteVcfContentDialog extends org.alfresco.web.bean.content.DeleteContentDialog {

    @Override
    protected String finishImpl(FacesContext context, String outcome)throws Exception {
        // get the content to delete
        VcfNode node = new VcfNode(this.browseBean.getDocument());
        if (node != null) {
            if (ContentModel.TYPE_MULTILINGUAL_CONTAINER.equals(node.getType())) {
                // delete the mlContainer and its translations
                getMultilingualContentService().deleteTranslationContainer(node.getNodeRef());
            } else {
                // getting attached xml node
                Node descriptionXml = node.getXmlNode();
                // and if xml exists, delete it!
                if(descriptionXml != null)
                    this.getNodeService().deleteNode(descriptionXml.getNodeRef());
                
                // delete the node
                this.getNodeService().deleteNode(node.getNodeRef());
            }
        }
        return outcome;
    }
}

As I can see, it'll be much better to implement some transactions inside this method to 'do some atomicity' 8-). VcfNode is my Node extension, I'll try to describe it in next blogpost.

So, it's pretty easy to workaround system dialogs thanks to Alfresco source code. But sometimes you can find things, which looks like there is no source in sdk 🙁 but google always helps!

Customizing Simple Search

Some time ago I made customized advanced search results view – no two boxes like in standard Alfresco, but three boxes – the third one for viewing special content type. Now I wanted to add this results screen as a default result of searching via the simple search box.

Some time ago I made customized advanced search results view – no two boxes like in standard Alfresco, but three boxes – the third one for viewing special content type. Now I wanted to add this results screen as a default result of searching via the simple search box.

When I firstly saw r:simpleSearch component and no documentation, I wasn't happy. But after while I realized that it's very simple, thanks to actionListener parameter on that component:

 <r:simpleSearch id="search" actionListener="#{BrowseSessionBean.search}" />

This component creates that very known search box

Image Hosted by ImageShack.us

That action listener, search, is defined in BrowseBean, but I did my own (I copied and edited it :-)). All what this listener does is just setting Search Context and then redirects to results page – returns adequate outcome string to faces navigator.

 public void search(ActionEvent event){
        UISimpleSearch search = (UISimpleSearch)event.getComponent();
        this.navigator.setSearchContext(search.getSearchContext());
        
        FacesContext context = FacesContext.getCurrentInstance();
        context.getApplication().getNavigationHandler().handleNavigation(context, null, "browseSearchResults");
    }

 Navigation rule in faces config navigates in this case from everywhere to my own search results page thanks to this rule:

<navigation-rule>
        <from-view-id>/jsp/*</from-view-id>
        <navigation-case>
            <from-outcome>browseSearchResults</from-outcome>
            <to-view-id>/jsp/archivace/view-search-results.jsp</to-view-id>
        </navigation-case>
</navigation-rule>

That's all, view-search-results is up to you 🙂

Playing with titlebar and navigator II

In last blogpost I wrote about titlebar and menu in it. Also I promised some navigator hacking, which is more complex (and crazy has many javascript code) and amazing, so I decided to write whole blogpost on it. Here we are go!

In last blogpost I wrote about titlebar and menu in it. Also I promised some navigator hacking, which is more complex (and crazy has many javascript code) and amazing, so I decided to write whole blogpost on it. Here we are go!

Navigator jsp is pretty simple, but it's not plus for us, because whole navigator is a component – r:navigator. That should not be a problem, but this component has no documentation and what is much worse, this component's aim is just to view that simple menu with Guest home, Alfresco home, My home and Company home. Nothing less, nothing more, no editings.So what to do with that crap? Let's do some hacking! You can see my result at following picture, I added one more link:

 

Image and video hosting by TinyPic    Image and video hosting by TinyPic

 

Navigator.jsp is in /jsp/sidebar/ and at start there is just that component:

 <r:navigator id="navigator" activeArea="#{NavigationBean.toolbarLocation}" />

 This component renders ahref links inside divs, like this:

<div id="navigator">
      <div><a href="foo">bar</a></div>
      <div><a href="bar">foo</a></div>
          . . .
</div>

So I need to insert my own container with my link (both styled some way). ActionLink doesn't take 'class' attribute, so I need to inject that attribute with simple javascript:

 <a:booleanEvaluator value="#{BrowseSessionBean.isArchivaceExist}">
    <f:verbatim>
        <div id="navigatorArchivaceBox" class="sidebarButton" style="background-image: url(/alfresco/images/parts/navigator_grey_gradient_bg.gif);">
    </f:verbatim>
    <a:actionLink id="navigatorArchivaceLink" value="Archivace" href="#{BrowseSessionBean.archivaceUrl}"/>
    <f:verbatim>
            <script type="text/javascript">
                   var link = document.getElementById("navigatorArchivaceLink");
                   link.setAttribute("class","sidebarButtonLink");
            </script>
        </div>
    </f:verbatim>
</a:booleanEvaluator>

I personally hate that opening div inside verbatim tag and also that closing div, but what I can do else :-/. So this simple hack added my own link into navigator menu, it's clickable, it's styled, that link works, but that box is not selectable. After deploy this probably look like left picture a few rows higher. All that code is placed inside evaluator, because I need to have destination space accessible, to display this link in menu.

So next thing to do is to deselect all boxes and all links after 'my link' is clicked and also select my box and my link. Sounds simple, but it isn't thanks to 'My Alfresco' link. I'm doing all this stuff only when I'm at the right place (my Archivace space), so I need evaluator:

<a:booleanEvaluator value="#{BrowseSessionBean.isInsideArchivace}">
<f:verbatim>

Inside this evaluator I have simple javascript, which goes through elemnts under navigator container – links and divs – and for each set 'unselected' style:

<script type="text/javascript">
    // disabling 'selected' style at all links
    var links = document.getElementById("navigator").getElementsByTagName('a');
    for(var i=0; i<links.length; i++){
        links[i].setAttribute("class","sidebarButtonLink");
    }

    // disabling 'selected' style at all boxes
    var links = document.getElementById("navigator").getElementsByTagName('div');
    for(var i=0; i<links.length; i++){
        links[i].setAttribute("class","sidebarButton");
        links[i].setAttribute("style","background-image: url(/alfresco/images/parts/navigator_grey_gradient_bg.gif)");
    }

Now it's time to set 'selected' style just for my (selected) link. I know its ids, so I can access them directly through getElementById:

document.getElementById("navigatorArchivaceBox").setAttribute("style","background-image: url(/alfresco/images/parts/navigator_blue_gradient_bg.gif)");
document.getElementById("navigatorArchivaceLink").setAttribute("class","sidebarButtonSelectedLink");

And now all I have to do is 'just' to create evaluator – isInsideArchivace. That is not so hard – just getting current node and asking, if it has wanted aspect ;-).

public boolean getIsInsideArchivace(){
    if(this.getCurrentLocation()==null)return false;
    return this.navigator.getCurrentNode().hasAspect(cz.shmoula.ArchivaceModel.archSummary);
}

Now it's all doomed to work, like on first and second image :-). BUT – 'My Alfresco' is not an ordinary space, it's some virtual space or something, so when I left my 'Archivace' space by clicking on 'My Alfresco', My Alfresco screen is opened, but selected option is still 'Archivace'. What to do? Look at breadcrumb, because when there is node, it's ordinary space. But when there's nothing, it's probably 'My Alfresco' space (if not, it doesn't matter, because it is not my 'Archivace' space) and it's neccessarynot to display 'Archivace' as selected node. Soall that is inside that getCurrentLocation, which fragments are stolen somewhere from Alfresco sources:

 public String getCurrentLocation(){
        List<IBreadcrumbHandler> location = this.navigator.getLocation();
        String name = null;
          if (location.size() != 0){
              for (int i=0; i<location.size(); i++){
                 IBreadcrumbHandler element = location.get(i);
                 if (element instanceof IRepoBreadcrumbHandler){
                    NodeRef nodeRef = ((IRepoBreadcrumbHandler)element).getNodeRef();
                    name = Repository.getNameForNode(this.getNodeService(), nodeRef);
                 }
              }
          }
          return name;
    }

At this time it's all and it works! Ugly and hacky solution, but it works (FF3). Maybe it'll be better to write own component (eg. some tree browsing component), but now I wanted some simple and fast (and really ugly). Oh, I almost forget – this thread helped me a lot!

Playing with titlebar and navigator

My next quest was to change content of titlebar and navigator box. Titlebar was really easy, but navigator box is 'hell itself', because it's r:navigator component and i didn't want to create another component just for adding one more line.

My next quest was to change content of titlebar and navigator box. Titlebar was really easy, but navigator box is 'hell itself', because it's r:navigator component and i didn't want to create another component just for adding one more line.

Titlebar editing is very easy. Final result is on following screenshot:

Image and video hosting by TinyPic

That topmenu is created by a styled a:modeList component with some listItems. ModeList has actionListener set and after listItem is clicked, its value is sent to that listener (which is a big switch). So my first task was to bridge that listener. Original code is placed in NavigationBean and that method is named toolbarLocationChanged. I wrote my own eventListener in 'someBean' this way:

public void toolbarLocationChanged(ActionEvent event){
     UIModeList locationList = (UIModeList)event.getComponent();
     String location = locationList.getValue().toString();
     if(location.equals("archivace")){
      . . .
      }else this.navigator.processToolbarLocation(location, true);

In this piece of code is loaded 'location' – value of listItem (ie companyhome, userhome, archivace… see later) and is compared with identificator of my action.If equals, something happens (see next listing ;-)), else original processToolbarLocation routine in NavigationBean is called.

That something piece of code, which happens in that case is creation of breadcrumb and some informations in NavigationBean are changed, follows here:

List<IBreadcrumbHandler> elements = new ArrayList<IBreadcrumbHandler>(1);
Node archivace = new Node(getArchivaceRef());
elements.add(new NavigationBreadcrumbHandler(archivace.getNodeRef(), archivace.getName()));
this.navigator.setLocation(elements);
this.navigator.setCurrentNodeId(archivace.getId());

But that is not all, you have to inform registered beans that the current area has changed:

UIContextService.getInstance(FacesContext.getCurrentInstance()).areaChanged();

And because the current node is not added to the dispatch context automaticaly, it's needed to add it programaticaly (this was very old bug of Alfresco and in some cases still lasts – forum, jira):

 this.navigator.setupDispatchContext(this.navigator.getCurrentNode());

Last thing to do is to force a navigation to refresh the browse screen breadcrumb:

FacesContext context = FacesContext.getCurrentInstance();
 context.getApplication().getNavigationHandler().handleNavigation(context, null, "browse");

 That's all java coding. Now some jsp: you have to edit file titlebar.jsp in /jsp/parts/ and change actionListener in a:modeList and add another a:listItem as seen on next listing (simplified):

<a:modeList . . . actionListener="#{SomeBean.toolbarLocationChanged}">
      <a:listItem value="archivace" label="Archivace" rendered="#{SomeBean.isArchivaceExist}"/>
</a:modeList>

Ah, I see there is evaluator – isArchivaceExist. It's just an evaluator, which returns true/false – if space I want to view exists, so that listItem is viewed just in case of that space exists.

 

As I can see, it'll be better to move navigator hacks to next blogpost.

Mimetype detection in upload component

I posted short topic about my way to uploading files to Alfresco some time before. Now I turned all that code into my own component and added it to Tag Library and also added mimetype detection and some other amazing stuff. I'll try to describe some facts about my implementation in this blogpost, so be encouraged to keep reading ;-).

I posted short topic about my way to uploading files to Alfresco some time before. Now I turned all that code into my own component and added it to Tag Library and also added mimetype detection and some other amazing stuff. I'll try to describe some facts about my implementation in this blogpost, so be encouraged to keep reading ;-).

I'm not going to describe how to build own component, there are many tutorials on web (for example here or here) and it's much simplier than stuff I'm going to write about (many ughly javascript code). So let's begin.Firstly, thanks to component,jsp code is simplified. I compressed whole code into component (form inputs, labels, also js libraries includes), so my code lookslike this (note that javascript part is optional and is there just to disable OK button on page load; also mimetype selector is optional).

<%@ taglib uri="http://www.shmoula.cz/jsf/component/tags" prefix="shmoula" %>

<script type="text/javascript">
function pageLoaded(){
    document.getElementById("dialog:finish-button").disabled = true;
}
window.onload = pageLoaded;
</script>

. . .

    <h:inputHidden id="fileId" value="#{SlowUpload.fileId}" />
    <shmoula:upload label="soubor" />
    <r:mimeTypeSelector id="mime-type" value="#{SlowUpload.mimeType}" />

. . .

FileId parameter does still the same thing – it connects get data with post data – identificator is created and then AJAX call is made, in which goes this id and filename to servelt, which creates a new FileBean and also get mimetype from filename and send it back. You can see this snippet on following listing.

 public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
       PrintWriter out = response.getWriter();
       
       try{
           // creating a new bean for fileinfo storing and also setting some info
           this.fileUploadBean = new FileUploadBean();
           this.uploadId = request.getParameter("uploadid");
           String filename = request.getParameter("filename");

           // fetching mimetypeService from SlowUpload bean; more info follows
           SlowUpload slowUpload = (SlowUpload)request.getSession().getAttribute("SlowUpload");
           MimetypeService mimetypeService = slowUpload.getMimetypeService();
       
           // guessing and returning mimetype
           // if mimetype is not recognized, application/octet-stream is returned

           out.print(mimetypeService.guessMimetype(filename));
           
       }catch(Exception e){
           out.print("FALSE");
       }
}

MimetypeService must be injected into SlowUpload bean, so I need some Setters in my class for that and definition in Faces config:

 <managed-bean>
       <managed-bean-name>SlowUpload</managed-bean-name>
       <managed-bean-class>cz.shmoula.SlowUpload</managed-bean-class>
       <managed-bean-scope>session</managed-bean-scope>
. . .
       <managed-property>
           <property-name>mimetypeService</property-name>
           <value>#{MimetypeService}</value>
       </managed-property>
. . .
   </managed-bean>

 Now onComplete function is called thanks to prototype library AJAX calling. In this function a right option in select box is selected just through a simple loop, as you can see:

function callbackFunction(originalRequest){
    var vystup = new String(originalRequest.responseText);
    
    if(vystup=="FALSE"){
        rollback(1);
        alert("Chyba pri uploadu");
    }else{
        var select = document.getElementById("dialog:dialog-body:mime-type");
        for(i=0;i<select.length;i++){
            var selectVal = new String(select.options[i].value);
            if(selectVal.match(vystup)!=null){
                select.options[i].selected = true;
                select.selectedIndex = i;    
                break;
            }
        }
    }
}

And after all this whole formular is sent to servlet via POST method. All this is described in previous post, so you can check it out there. But there is one change – servlet returns success of operation inside hidden input. So I changed servlet this way:

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(". . .<input type="hidden" id="iframe_status" value=""+this.fileUploadBean.getFileName()+"" />. . .");

On client side is after (un-)successfully file upload called handle_upload() function, which gets value from included iFrame and decides that operation was or was not successfull and call appropriate actions:

function handle_upload(){
    var doc = getIframeDocument();
    var filename = doc.getElementById("iframe_status").value;
   
    if(filename != "FALSE"){
        var fileNameInput = document.getElementById('dialog:dialog-body:fileName');
        if(fileNameInput!=null)
            fileNameInput.value = filename;
        checkButtonState();
    }else{
        rollback(1);
        alert("Chyba pri uploadu!");
    }
}

CheckButtonState function does nothing else, than enable OK button for complete submit all those information (if some other conditions came true) and rollback function sets form target to original target – …/dialog/container.jsp.

That's all folks! Simplified procedure of my component activity. I wish I have not to write these hacks and all those things are accessible by developer in alfresco (they are there, but you can't use them outside specified containers or-how-to-name-that) some simple way. Maybe in future I hope!

Has properties webscript

I did some other java based webscript. From portlet flash application I need to get information about some user's permissions on object specified by nodeRef. So firstly I tried to do this via JavaScript based webservice, but there are no tools to do this.

I did some other java based webscript. From portlet flash application I need to get information about some user's permissions on object specified by nodeRef. So firstly I tried to do this via JavaScript based webservice, but there are no tools to do this.

 First thing is to create description xml for this service:

 <webscript>
  <shortname>hasRights</shortname>
  <description>Returns some amazing info ;-)</description>
  <url>/archivace/hasrights?u={userName}&amp;s={nodeRef}&amp;p={permissionName}</url>
  <format default="xml"/>
  <authentication>user</authentication>
  <transaction>required</transaction>
</webscript>

As you can see, there are three parameters: u, which specifies userName of user, of which we want to get this information. Parameter  s, which specifies nodeRef of node and finally p, which is optional and specifies one of permissions. If not set, WriteContent permission is used.

Space permissions:

  • ReadProperties
  • ReadChildren
  • WriteProperties
  • DeleteNode
  • DeleteChildren
  • CreateCildren

Content permissions:

  • ReadContent
  • WriteContent
  • ReadProperties
  • WriteProperties
  • DeleteNode
  • ExecuteContent
  • SetOwner

You can find a complete list of all permisions in tomcat/webapps/alfresco/WEB-inf/classes/alfresco/model/permissionDefinitions.xml.

 Now let's write some javacode: I created a class HasRights, which extends AbstractWebScript. Let's have a look into that code

 public class HasRights extends AbstractWebScript{
    private AuthenticationComponent authenticationComponent;
    private PermissionService permissionService;

    public void execute(WebScriptRequest req, WebScriptResponse res)throws IOException {
        try{
            HttpServletRequest httpReq = ((WebScriptServletRequest)req).getHttpServletRequest();
            String spaceRef = "workspace://SpacesStore/" +
              (String)httpReq.getParameter("s");
            String userName = (String)httpReq.getParameter("u");
            String permission = (String)httpReq.getParameter("p");
            if(permission==null)
                permission = "WriteContent";

In case of this webScript is called method execute is the first to run (not exactly, setters of this class are called sooner – setAuthenticationComponent() and setPermissionService()) . In this method javax.servlet.http.HttpServletRequest is used for get parameters.

            NodeRef nodeRef = new NodeRef(spaceRef);
            Node noda = new Node(nodeRef);
            this.authenticationComponent.setCurrentUser(userName);

In those steps Node and nodeRef objects are created and currently logged user is setted to wanted user.

res.setContentType("text/xml");
res.getWriter().write("<hasRightsResponse>");
res.getWriter().write("<nodeName>"+noda.getName()+"</nodeName>");
res.getWriter().write("<nodeRef>"+nodeRef.toString()+"</nodeRef>");
res.getWriter().write("<userName>"+this.authenticationComponent.getCurrentUserName()+"</userName>");
res.getWriter().write("<permissionName>"+permission+"</permissionName>");
res.getWriter().write("<hasPermission>"+this.permissionService.hasPermission(nodeRef, permission)+"</hasPermission>");
res.getWriter().write("</hasRightsResponse>");

After all that a response is printed out. Example of output is following:

<hasRightsResponse>
    <nodeName>sezeni001.xml</nodeName>
    <nodeRef>workspace://SpacesStore/da5ad5b0-3bc4-4d4c-88fe-4f9cf4f349f5</nodeRef>
    <userName>pepik1</userName>
    <permissionName>WriteContent</permissionName>
    <hasPermission>DENIED</hasPermission>
</hasRightsResponse>

I forgot to mention the most importatn step – to define a bean with this webscript. So it looks like this (in web-scripts-application-context.xml):

 <bean id="webscript.org.alfresco.archivace.hasrights.get" class="cz.shmoula.webscripts.HasRights" parent="webscript">
      <property name="authenticationComponent" ref="AuthenticationComponent"/>
      <property name="permissionService" ref="PermissionService"/>
  </bean>

And that's it, pretty simple ;-).

Custom „modify content properties dialog“

There is this dialog present in Alfresco (edit-content-properties.jsp), but I wanted to write my own and also describe things I discovered during playing with browseBean.

There is this dialog present in Alfresco (edit-content-properties.jsp), but I wanted to write my own and also describe things I discovered during playing with browseBean.

Let's start with simple bean extending BaseDialogBean with just one getter (and also implementation of abstract methods, ie. getFinishButtonDisabled() or finishImpl()), which returns a Node (org.alfresco.web.bean.repository.Node).

public class ModifyContentProperties extends BaseDialogBean {

    public Node getNode(){
        return this.browseBean.getDocument();

   }
}

Our bean requies just one property – browseBean, so let's set it in faces config:

 <managed-bean>
       <managed-bean-name>ModifyContentProperties</managed-bean-name>
       <managed-bean-class>cz.shmoula.ModifyContentProperties</managed-bean-class>
       <managed-bean-scope>request</managed-bean-scope>
       <managed-property>
           <property-name>browseBean</property-name>
           <value>#{BrowseBean}</value>
       </managed-property>
   </managed-bean>

For successfully access to getDocument() method an action listener in web client config is needed. Without this listener (and parameter) the methodreturns null, which is really not expecting value :-). So you need to add that listener and parametr into action definition:

<action id="modify_content_properties">
    <label>Editovat vlastnosti</label>
    <image>/images/icons/edit_form.gif</image>
    <action>dialog:modifyContentProperties</action>
    <action-listener>#{BrowseBean.setupContentAction}</action-listener>
    <params>
        <param name="id">#{actionContext.id}</param>
    </params>
</action>

 A JSP page is very simple, just one component from repo.tld library – propertySheetGrid. More information about this componentcan be found in the alfresco devel wiki. I'm using a (default) externalConfig for describing which property to view or not. Information about config service should be found also in developer wiki, so check it out.

 <%@ taglib uri="/WEB-INF/repo.tld" prefix="r" %>
<r:propertySheetGrid id="content-details-contents" value="#{ModifyContentProperties.node}"  externalConfig="true" />

This simple configuration opens a dialog with properties editing inputs, which are filled by information of opened document (or node, if you apply this config – add action – to a Node). BUT you can't save changes. We don't have an OK button method handled. How to get this stuff working? Very simple, Gavinc already wrote this code in org.alfresco.web.bean.content.EditContentPropertiesDialog, so all we need to do is to change a class, which our ModifyContentProperties extending and add overriding methods for default Cancel and OK buttons calls.

 import org.alfresco.web.bean.content.EditContentPropertiesDialog;

public class ModifyContentProperties extends EditContentPropertiesDialog {
    
    @Override
    protected String getDefaultCancelOutcome(){
      return super.getDefaultCancelOutcome() +
                 AlfrescoNavigationHandler.OUTCOME_SEPARATOR +
                 "browse";
    }

    @Override
    protected String getDefaultFinishOutcome(){
       return super.getDefaultFinishOutcome() +
                 AlfrescoNavigationHandler.OUTCOME_SEPARATOR +
                 "browse";
    }

.  .  .

EditContentPropertiesDialog has an editableNode property, which is just a copy of original node, i which we can write our changes. So we need to assign this editableNode to our propertySheetGrid component.

<r:propertySheetGrid id="content-details-contents" value="#{ModifyContentProperties.editableNode}" externalConfig="true"/>

That is all, fast and simple … and now at one place, so you must not spent so much time to looking for how this works as me 🙂

Alfresco Quick upload

In Alfresco there is no simple way to modify uploading code. You can't just copy and customize org.alfresco.web.bean.content.AddConteneDialog class and /jsp/content/add-content-dialog.jsp ie you can use add-content-dialog.jsp and modify it, but when you try to use AddContentDialog class updated in your project, it doesn't work. I found somewhere on forums (sry, i can't find a link) that add-content-dialog.jsp is just a page snippet and when you coding your own dialog, you must write code for whole page and there is problem with r:upload component. So i'll try to describe my simple solution for QuickUpload content to Alfresco through a Servlet.

In Alfresco there is no simple way to modify uploading code. You can't just copy and customize org.alfresco.web.bean.content.AddConteneDialog class and /jsp/content/add-content-dialog.jsp ie you can use add-content-dialog.jsp and modify it, but when you try to use AddContentDialog class updated in your project, it doesn't work. I found somewhere on forums (sry, i can't find a link) that add-content-dialog.jsp is just a page snippet and when you coding your own dialog, you must write code for whole page and there is problem with r:upload component. So i'll try to describe my simple solution for QuickUpload content to Alfresco through a Servlet.

My servlet – UploadAnalysisFileServlet – extends javax.servlet.http.HttpServlet, i'm using both methods – GET and POST too. (If you don't know how servlets work, just look at this tutorial) I'm using asynchronous requests and iframe, which work "behind scene" and after success user can handle some more action. Actions are following:

  1. View page with select file input and upload button in a form 
  2. After file select and upload button press is AJAX Request fired and file and information are transfered between servlet and client
  3. If file is successfully loaded, iframe views a succesfully-uploaded-image.gif and ok button is enabled
  4. QuickUpload bean control is triggered – aspects and properties are added to new content
  5. File is succesfully uploaded and properties setted up, so back to space view

Simplified "action diagram":
 
 
Now let's look inside code snipets; firstly item one, View page with select file input and upload button in a form

<iframe id="dialog:dialog-body:upload_target" src="progress_anim.gif" style="visibility:hidden"></iframe>
<div id='dialog:dialog-body:fileDiv'>
      <h:inputHidden id="alfFileId" value="#{QuickUpload.fileId}" />
      <input type="file" id='dialog:dialog-body:alfFileInput' name="alfFileInput"/>
      <input type="button" value="upload" onclick="sendAjaxRequest();" id='dialog:dialog-body:uploadButton'/>
</div>

 This is just an hidden iframe with content of animation of progress icon and a simple form with upload input type and button, which triggers following JavaScript routine. Ajax calling is based on Prototype JavaScript Framework.
 function sendAjaxRequest(){
    var form = document.getElementById('dialog');
    document.getElementById('dialog:dialog-body:fileDiv').style.visibility = "hidden";

    form.action = '/alfresco/uploadAnalysisFileServlet';
    form.enctype= 'multipart/form-data';
    form.target = 'dialog:dialog-body:upload_target';

    var ifr = document.getElementById('dialog:dialog-body:upload_target');
    ifr.style.visibility = "visible";
    var doc = null;  
    if(ifr.contentDocument)  
      doc = ifr.contentDocument;  // note: this is varying for different browsers!

    var pars = "uploadid=" + document.getElementById("dialog:dialog-body:alfFileId").value;
    var myAjax = new Ajax.Request("/alfresco/uploadAnalysisFileServlet",
         { method: 'get', parameters: pars, onComplete: checkExists });

    form.submit();
    
    form.action = '/alfresco/faces/jsp/dialog/container.jsp';
    form.enctype= 'application/x-www-form-urlencoded';
    form.target = '';
}

First action is getting a form of dialog, then default action of this form is redirected to my servlet. After that is an ID sent through get method to servlet and a file is sent too, viapost metod, thanks to form.submit(). After this sending is dialog form redirected back to original value and onComplete method is called (it just reads a responseText and check, if it is true or false), which enables OK button.
 
How are post and get methods handled in servlet? A org.alfresco.web.bean.FileUploadBean class is used:
 
 public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
       this.fileUploadBean = new FileUploadBean();
       this.uploadId = request.getParameter("uploadid");
       PrintWriter out = response.getWriter();
       out.println("uploadId = "+this.uploadId);
   }
A doGet method just creates a new FileUploadBean and sets and returns ID of file (I'm using this just for debugging and experimenting purposes, it can all be placed just in a Post method). Now let's handle post method data:
 
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
       HttpSession session = request.getSession();
       ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
      
       List<FileItem> fileItems = upload.parseRequest(request);
       for (FileItem item : fileItems){
           if(item.getFieldName().equalsIgnoreCase("alfFileInput")){
               String filename = item.getName();
               filename = FilenameUtils.getName(filename);
               final File tempFile = TempFileProvider.createTempFile("alfresco", ".upload");
               item.write(tempFile);
               this.fileUploadBean.setFile(tempFile);
               this.fileUploadBean.setFileName(filename);
               this.fileUploadBean.setFilePath(tempFile.getAbsolutePath());
           }
       }
      
       session.setAttribute(FileUploadBean.getKey(uploadId), this.fileUploadBean);
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       out.println("<img src="/alfresco/images/icons/deploy_successful.gif"/>");
   }
This snippet is hardly simplified, but idea is still readable: it reads all file items and if one of them is our file input (alfFileInput), temporary file is created and fileUploadBean properties are set. Then is set an attribute in a session – whole fileUploadBean and a response is sent back to JavaScript client – view of succesfull_upload inside iframe.
 
At this phase a user can do "OK", so QuickUpload's finishImpl method is triggered. It handles a uploaded file following simple way:
FacesContext ctx = FacesContext.getCurrentInstance();
FileUploadBean fileBean = (FileUploadBean)ctx.getExternalContext().getSessionMap().
                                get(FileUploadBean.FILE_UPLOAD_BEAN_NAME.concat("-"+this.getFileId()));
       
if(fileBean != null){
    this.file = fileBean.getFile();
    this.fileName = fileBean.getFileName();
 
    NodeRef spaceRef = this.navigator.getCurrentNode().getNodeRef();
    FileInfo fileInfo = this.getFileFolderService().create(spaceRef, fileBean.getFileName(), ContentModel.TYPE_CONTENT);
    NodeRef fileNodeRef = fileInfo.getNodeRef();
               
    Map<QName, Serializable> fileDesc = new HashMap<QName, Serializable>(3, 1.0f);
    fileDesc.put(ContentModel.PROP_TITLE, this.fileName);
 
    ContentWriter writer = this.contentService.getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true);
    writer.putContent(this.file);
}
Firstly a FileUploadBean is extracted back from SessionMap, then a content inside currentNode is created with specified parameters (it is also possible to add some aspects and properties there). After all that just "return outcome;" and hooray, we have simple working QuickUpload routine for Alfresco ;-).

iCal export implementation for Alfresco

For my vcf planning calendar, which is partially described in my Bachelor's thesis, I made function, which does export to iCal calendar format. I used Jav-backed WebScript at Alfresco side and iCal4j library for implementation of RFC 2445 standard – iCalendar.

For my vcf planning calendar, which is partially described in my Bachelor's thesis, I made function, which does export to iCal calendar format. I used Jav-backed WebScript at Alfresco side and iCal4j library for implementation of RFC 2445 standard – iCalendar.

The aim was to create service with parameter of node with planned sessions (ArchivaceSummary aspect) which exports iCal file with all sessions (ArchivaceSession aspect) in it. Simple data model scheme of aspects is at following picture. Those aspects are just flags of type of nodes, only ArchivaceSession aspect associates some properties – a date of begin and end of action. More informations are in my Bachelor's thesis.

Image Hosted by ImageShack.us

Due to use iCal4j library I needed to use Java-backed web script, because i can't see a simple way to create iCal file just with Freemarker, which is used as a rendering machine in "normal" web scripts. Java-backed web scripts are clearly described at Alfresco wiki pages, but when you try to write your own you discover that there is no library in SDK. This problem is reported as a bug, but there is still no solution. It's needed to download library (and source) alfresco-web-framework and include it to project, then it's all ok and it's possible to build Java-backed web scripts.

So, every webscript needs a description file, i put this one into WEB-INF/classes/alfresco/templates/webscripts/org/alfresco/archivace/ical.get.desc.xml

<webscript>
    <shortname>iCal Export</shortname>
    <description>Export kalendare z Archivacniho prostoru</description>
    <url>/archivace/ical?nodeRef={noderef}</url>
    <authentication>user</authentication>
    <transaction>required</transaction>
</webscript>

You can see from its name (ical.get.desc.xml) that this webscript implements get http method. You also need to specify that fact in bean identificator – as a postix, as you can see on next listing of part of web-scripts-application-context.xml.

 <bean id="webscript.org.alfresco.archivace.ical.get"
    class="cz.shmoula.webscripts.ICal"
    parent="webscript">
  </bean>

This postfix is picked up by the Web Script engine, also 'webscript.' prefix is picked up. Webscript prefix identifies that bean you are specifying is a webscript implementation.  Notice that url parameter in desc.xml and suffix of bean identificator  are corresponding: alfresco.archivace.ical.get   —  /archivace/ical.Second parameter, class, specifies class with implementation. My class implementation is based on AbstractWebScript class, which provides simplier development of WebScripts. Main method of this class is method public void execute(WebScriptRequest req, WebScriptResponse res), which is described on next listing.

public void execute(WebScriptRequest req, WebScriptResponse res)
            throws IOException {
        // getting request data
        HttpServletRequest httpReq = req.getHttpServletRequest();
        // opening specified node
        Node noda = new Node(NodeRef(httpReq.getParameter("noderef")));
        // creating new calendar object
        net.fortuna.ical4j.model.Calendar calendar = new net.fortuna.ical4j.model.Calendar();

        // cycling through node and reading data
        for (Iterator i = noda.getChildAssociations().values().iterator(); i
                .hasNext();) {
            . . .
            if (n.hasAspect(ArchivaceModel.archSession)) {
                // if type of child is what I want, just create data from provided info and add to calendar
                this.addEvent(n.getProperties());
            }
            . . .
        }
        // setting response and printing out a calendar
        res.setContentType("text/calendar");
        res.getWriter().write(this.calendar.toString());
    }

Pressty simple, huh? And the last task – calling this webscript. Either by specifying an url with required parameter (node reference), or in code. I'm using an ActionLink from Alfresco Tag Library called this way:

 <a:actionLink value="iCal export"
    image="/images/icons/calendar-16.gif"
    href="/service/archivace/ical?noderef=#{NavigationBean.currentNode.nodeRefAsString}"
/>

And that is it. I have a calendar export button on my page as you can see on following image.

Image and video hosting by TinyPic