techbits.de » javascript http://www.techbits.de thoughts on hardware, software, development and tech news Mon, 01 Apr 2013 05:39:07 +0000 en hourly 1 http://wordpress.org/?v=3.2.1 Introducing the User Script Console http://www.techbits.de/2013/04/01/introducing-the-user-script-console/ http://www.techbits.de/2013/04/01/introducing-the-user-script-console/#comments Mon, 01 Apr 2013 03:01:15 +0000 Florian http://www.techbits.de/?p=434 Continue reading ]]> The Alfresco JavaScript Console is really popular among Alfresco administrators and developers to easy automate tasks around Alfresco. This leads to more and more requests from users to have their problems fixed and tasks automated and keeps developers and administrators from more important tasks.

With the new User Script Console extension for Alfresco Share the users finally can access the powerful JavaScript API directly by themselves without needing a specialist. It integrates as a page in a Share site:

Of cause it can not be expected of end users to know JavaScript or the Alfresco APIs right away. That is why the User Script Console slowly introduces the users to the capabilities of the API using a Gamification approach. Users start out as novices and can gain experience (XP) while using the JavaScript API.

User “Experience”

API access gradually changes with increased experience:

  • 0 XP = No Alfresco API access
  • 10 XP = Read properties and permissions, only document root object
  • 1000 XP = Add comments, add Tags to any node
  • 5000 XP = Write properties and add tags, Site API, full ScriptNode api
  • 10000 XP = Groups API (Add/Remove people from sites)
  • 20000 XP = Full Alfresco Javascript API
  • 50000 XP = runas admin, access beans using Packages.java

A new user starting out as a novice must first write a syntactically correct JavaScript using given examples. He receives 1 XP for each successful transaction and will soon gain access to some parts of the Alfreco API (XP of 10 or more). Commands above his experience level are not available:

Examples

To help users find their way around, there are examples in the “Examples” menu that are adjusted to the users experience level. It starts out with a list of simple JavaScript examples for “for”-loops and “if”-clauses.

Badges

Additionally users can earn badges for special achievements (each earns 500 XP):

  • Unlocker: Unlocked more than 10 documents that were locked by the Sharepoint API.
  • Tagmaster: Added 100 different tags to documents
  • Ninja: more than 10 “hidden” property changes with behaviourfilter.disableBehaviour()
  • Shapeshifter: More than 100 calls of the transformDocument/transformImage
  • JsGuru: Run 10 consecutive scripts that all JsLint without any warnings
  • Loadtester: Your last 10 scripts have all run longer than 30s
  • MrClean: Purge the archive store (nodeArchiveService)
  • Reporter: Generation of more than 10000 lines of print output
  • Bouncer: Removed at least 100 people from groups/sites
  • Hacker: Usage of Packages.java to access Spring beans directly

The new User Script Console will help to empower the savvy user to automate Alfresco in an unprecedented way and lets administrators focus on more important tasks like backup and restore of the Alfresco repository.

Available today for Alfresco 4.1.

]]>
http://www.techbits.de/2013/04/01/introducing-the-user-script-console/feed/ 4
Using the Javascript Console: Creating users with avatar images http://www.techbits.de/2011/12/02/using-the-javascript-console-creating-users-with-avatar-images/ http://www.techbits.de/2011/12/02/using-the-javascript-console-creating-users-with-avatar-images/#comments Fri, 02 Dec 2011 22:51:07 +0000 Florian http://www.techbits.de/?p=387 Continue reading ]]> Automatically creating users has become easier with the new CSV user import features in Alfresco 4.0 or the Create Bulk Users extension from share-extras. If you want to be really flexible and set all the user properties or even set custom properties, using the Javascript API to create users can still be very useful. That’s why I’ll show you how to create users using the Javascript Console.

Let’s start with a short video preview on how the user and avatar creation works.

Creating users

Here is a function that creates a single user using the createPerson function of the global people object. The additional properties location and jobtitle are also filled here for the user. The cm:person object has several more properties to offer. To see a list of all properties available have a look at the cm:person type in the contentModel.xml.

function createUser(username, firstname, lastname, email, location, 
  jobtitle) {

  var password = username; // use for testing only!

  var p = people.createPerson(username, firstname, lastname, email,
    password, true);

  p.properties["cm:location"] = location;
  p.properties["cm:jobtitle"] = jobtitle;
  p.save();
}

It is useful to have this custom createUser function to easily create multiple users. Here is a list of some users we want to add to Alfresco.

createUser("homer", "Homer", "Simpson", "h.simpson@springfield.fox", 
    "Springfield", "Nuclear Safety Inspector");

createUser("marge", "Marge", "Simpson", "m.simpson@springfield.fox",
    "Springfield", "Housewife");

createUser("bart",  "Bart",  "Simpson", "b.simpson@springfield.fox",
    "Springfield", "Kid");

createUser("lisa",  "Lisa",  "Simpson", "l.simpson@springfield.fox",
    "Springfield", "Kid");

createUser("maggie","Maggie","Simpson",
    "maggie.simpson@springfield.fox", "Springfield", "Baby");

Assigning avatar images

Now we have created a few users. The only thing that is missing are the avatar images for each of the users. Wouldn’t it be great to just throw a bunch of images in a repository folder and have them automatically assigned to each user without having to log in as each of these users and assign an avatar image manually?

for each (imageNode in space.children) {
  var name = "" + imageNode.name;  // convert to javascript string
  name = name.replace(/\..*/, ""); // remove file extension

  var user = people.getPerson(name);

  if (user) {
    var avatarAssoc = user.assocs["cm:avatar"];

    if (avatarAssoc) {
      var currentAvatar = avatarAssoc[0];

      if ((""+imageNode.nodeRef) != (""+currentAvatar.nodeRef)) {
        logger.log("changing avatar for " + name + " to " +
            imageNode.displayPath + "/" + imageNode.name);
        user.removeAssociation(currentAvatar, "cm:avatar");
        user.createAssociation(imageNode, "cm:avatar");
      }
      else {
        logger.log("no change for user " + name);
      }
    }
    else {
        logger.log("setting new avatar for " + name + " to " +
            imageNode.displayPath + "/" + imageNode.name);
        user.createAssociation(imageNode, "cm:avatar");
    }
  }
}

This script does exactly that. It assumes that the space variable points to a repository folder that contains an avatar image for each user. Here is how you use it.

  • Create a folder somewhere in the repository, e.g. /Data Dictionary/User Images would be good name to use.
  • Upload your avatar images to that folder. Square aspect ratio would be best but image resolution doesn’t matter.
  • You avatar images should be named by username, e.g. “homer.jpg” or “marge.png” if you have the users “homer” and “marge”.
  • Select the “User Images” folder as space in the Javascript Console and run the script you see above.

A few things to note

  • The avatar image is stored with a cm:avatar association on each cm:person object that means that the image can be anywhere in the repository.
  • The avatar image that is assigned by the cm:avatar association will be converted into a 64×64 pixel thumbnail using the rendition service internally. This means you can use an image of any format and size that the rendition service can convert.
  • There is this odd comparison in the script:
    (""+imageNode.nodeRef) != (""+currentAvatar.nodeRef)

    Comparing nodeRefs can be really tricky in the Alfresco Javascript API, because they are Java objects. Here nodeRefs are converted into Javascript strings which can be compared with == or !=. Another way would be to use the Java equals() method like this:

    imageNode.nodeRef.equals(currentAvatar.nodeRef)

    but what you should not do, is directly comparing nodeRefs with == it won’t work:

    imageNode.nodeRef == currentAvatar.nodeRef
  • Of course you can use the avatar assignment script regardless of how you created the users. Even if the users have been imported with the LDAP synchronization you can still have the repository folder with the user images an have them assigned automatically. You could even create a rule that runs this script as soon as a new image is uploaded to the “User Images” folder.
]]>
http://www.techbits.de/2011/12/02/using-the-javascript-console-creating-users-with-avatar-images/feed/ 13
Using the Javascript Console: Permission reporting http://www.techbits.de/2011/11/06/using-the-javascript-console-permission-reporting/ http://www.techbits.de/2011/11/06/using-the-javascript-console-permission-reporting/#comments Sun, 06 Nov 2011 17:53:00 +0000 Florian http://www.techbits.de/?p=364 Continue reading ]]> I just came across an old question in the german Alfresco forum on how to create a report of permissions on all nodes in the repository. I thought to me this would be really easy to do with the Javascript Console and went ahead creating this script:

The implementation

recurse(companyhome, function(node) {
  for each(permission in node.fullPermissions) {
    if (/;DIRECT$/.test(permission)) {
      logger.log(node.displayPath + "/" + node.name + ";" + permission);
    }
  }
});

There are a few interesting things going on here.

  • It uses a special recurse() function that iterates the repository recursively. This function has been built into the Javascript Console for some time but is still undocumented because I am hesitant to decide if it is ok to change or add to the Javascript API. Scripts can not be used outside/without of the Javascript Console anymore when using those extensions.
  • The iteration starts with companyhome but you could use the space variable as well and select any folder as a starting point.
  • I learned there is a special property called node.fullpermissions which is undocumented in the Alfresco Javascript API but is needed here because it returns information if a permission is inherited or not (the documented node.permissions does not tell this).
  • The script filters out any permissions that are INHERITED and only shows the DIRECT permissions to make the result list not too huge.

The result

The result of the script is a semicolon separated text output that can be imported in Excel for example, for further analysis and reporting.
/Company Home/Data Dictionary;ALLOWED;GROUP_EVERYONE;Consumer;DIRECT
/Company Home/Data Dictionary/RSS Templates;ALLOWED;guest;Consumer;DIRECT
/Company Home/Data Dictionary/Saved Searches;ALLOWED;GROUP_EVERYONE;Contributor;DIRECT
/Company Home/Guest Home;ALLOWED;guest;Consumer;DIRECT
/Company Home/Guest Home;ALLOWED;GROUP_EVERYONE;Consumer;DIRECT
/Company Home/User Homes/abeecher;ALLOWED;abeecher;All;DIRECT
/Company Home/User Homes/abeecher;ALLOWED;ROLE_OWNER;All;DIRECT

Some background on recurse()

The recurse() function is only available within the Javascript Console and can be used to recursively search through the Alfresco Repository. It is very versatile, check out the following examples.

You can generate an array of all nodes under a specific folder:

var allNodes = recurse(space);

This will return an array with ScriptNode objects (folders and documents).

The second way to use the recurse function is using a callback function as we did in the initial script. The callback is called for each node. Internally node.children is used to get the child nodes and recurse deeper. if you return any objects from the processing function they will be added to an array and are returned from the recurse() function as the first example showed it. Using the callback function is probably the most useful way to use it:

recurse(space, function(node) {
   logger.log(node.displayPath + "/" + node.name);
});

The third way allows to pass in options to change to depth of the recursion. Currently there is only the maxLevel option which is used in the following example to only iterate two levels deep:

recurse(space, {
  process : function(node) {
    logger.log(node.displayPath + "/" + node.name);
  },
  maxlevel : 2
});

One thing you should keep in mind when running recursive Javascript code in Alfresco is that the whole script runs in one transaction. When iterating over a large repository and especially if you are updating nodes you might run into trouble with the transaction caches and maybe even database locking.

]]>
http://www.techbits.de/2011/11/06/using-the-javascript-console-permission-reporting/feed/ 4
Building a Google Plus inspired image gallery http://www.techbits.de/2011/10/25/building-a-google-plus-inspired-image-gallery/ http://www.techbits.de/2011/10/25/building-a-google-plus-inspired-image-gallery/#comments Tue, 25 Oct 2011 21:06:44 +0000 Florian http://www.techbits.de/?p=212 Continue reading ]]> I recently built a Google Plus inspired image Gallery as an extension for the Alfresco ECM product which won first place in Alfresco developer challenge. Now I’d like to share my insights, explain how I built it and give you a starting point to build your own galleries based on the great G+ gallery design.

Screenshot of Alfresco Gallery Plus extension

The G+ image grid disected

The main focus of this article will be on the image grid. Let’s start with a look on the features of the original G+ image grid to find out what it takes to recreate it. To illustrate the features I am using Thomas Hawk’s G+ gallery which has some amazing images (check it out).

  1. Justifed alignment: All images are displayed in rows and aligned to left and right borders. 
  2. Even spacing: All Images are evenly spaced (6px spacing, i.e. 3px margin around each image).  
  3. Natural order: Images don’t have a special ordering to better fit in the grid. I first thought the perfect alignment was solved with some sort of bin packing algorithm, but that is not the case und is not needed. Images are usually sorted by date from latest to oldest.
  4. Cropped thumbnails: To achieve the justified layout some portions of the images are hidden (cropped). When I first checked out the G+ gallery I saw most of the cropping done with HTML but now it looks like Google generates thumbnails in any arbitrary resolution or cropping on the server-side.
      
    Both images have a similar URL which only differs in a part which specifies the resolution. The left image contains the path /w300-h150-n-k/ whereas the right image contains the path /w150-h150-n-k/ and therefore is cropped differently on the server side.
  5. Big title image: There is a “title” image or (album cover image) which spans two rows.  
  6. Comment badges: The number of comments is displayed on each image thumbnail. 
  7. Dynamic resolution: The size of the images depends on the width of the browser window. G+ uses small images for smaller browser windows and larger images for wider browser windows, i.e. the image resolution adapts to the screen size. This is espacially useful for mobile devices which have lower resultion than desktop browsers.  
  8. Window resize: The image sizes change and the grid images are re-aligned dynamically when the browser window is resized.  
  9. Dynamic row height: This is a really subtle feature: Depending on the dimensions of the images in one row (e.g. if a lot of images in portrait format) some rows are rendered bigger in height than others. This helps portrait shots not to become too small.
  10. Popup Preview: When you hover over an image an animated popup appears and displays the image in a larger rendition.
  11. Infinite scroll: When you scroll to the bottom of the page more images are loaded automatically.

As far I have seen G+ servers generate different sizes of thumbnails that are used for the window specific thumbnail size, dynamic row height and the preview popup. At times your browser will load 10-20 differently sized thumbnails of an image.

I bet the feature list above is not even complete but it shows the design and engineering effort that went into this seemingly simple gallery grid.

What if you don’t have Google’s infrastructure and manpower?

For my one man competition contribution I couldn’t possibly implement all those features. I axed the double-row-spanning title image, different thumbnail sizes and the preview popup:

  • Only one thumbnail size (120 pixel height, width depending on image aspect ratio)
  • No server side cropping, only a single static thumbnail for each image. 

Still I came pretty close to the original with all the other features.

How does the cropping in the Browser work?

To better understand how the G+ image grid worked I studied the HTML source, which basically looks like this:

The main insight I took from this is they way the images can be cropped: using a DIV with overflow:hidden and changing margin-left of the image to define the x-offset.

How to align the images?

Once I started experimenting I realized that the image alignment is not that hard to do. Let’s say we have three images and are using a fixed thumbnail height of 120 pixel.

image 1: 200x120
image 2: 180x120
image 3: 120x120

Let’s also assume we want to fit these images in a row with a given width of 460 pixels.

I started to build rows of images by adding image by image until the window width is met or surpassed.

1 image: 200 OK (<460)
2 images: 200 + 180 = 380 OK (<460)
3 images: 380 + 120 = 500 surpassed (break >460, 40 pixels too long)

So putting all three images in a row would make it 40 pixel too long. The only thing that needs to be done now is to crop all the images by overall 40 pixels to perfectly align them with the window width.

My naive approach was to simply devide the excess pixels, so 40 pixel / 3 images = 13 pixels/image You have to be careful with the integer division though. To perfectly distribute the 40 pixels you need to crop one additional pixel from one of the images:

cropped image 1: 200 - 14 = 186x120
cropped image 2: 180 - 13 = 167x120
cropped image 3: 120 - 13 = 107x120

If you sum up the witdh now you get exactly 460 pixel. Combining these values with the cropping method from the previous section we get the following HTML code for the three images.

<div style="overflow:hidden; width:186px; height:120px;">
  <img src="image1.jpg" style="width:200px; height:120px";
      margin-left:-7px"/>
</div>
<div style="overflow:hidden; width:167px; height:120px;">
  <img src="image2.jpg" style="width:180px; height:120px";
      margin-left:-6px"/>
</div>
<div style="overflow:hidden; width:107px; height:120px;">
  <img src="image3.jpg" style="width:120px; height:120px";
      margin-left:-6px"/>
</div>

As you can see the negative margin-left is used to center the cropped area horizontally. On thing I left out here is the spacing between images. We have 6 pixels of spacing between each image that have to be added in the inital sum.

This naive approch worked pretty well even with only a single thumbnail size (120 pixels height). In a later iteration I changed the distribution of the crop-pixels though, because when equally distributing the excess pixels, portrait images tend to get too small in width. That’s why I based the crop amount on the image width, with the result that wider images are cropped more than narrow ones.

The server side

As you see above the image layout algorithm needs the widths of the individual images to do it’s mojo. In my Alfresco extension I leveraged the metadata extraction capabilties to get to the thumbnail resolution. The resulting JSON data that is finally generated on the server side is a simple array with all the image data (here is a single image as an example):

{ "thumbs" : [
  {
    "thumbUrl" : "api/node/workspace/SpacesStore/c2f5e06f-ee15-4b0f-9e6c-1f734b4db45f/content/thumbnails/galpThumb120",
    "title" : "2010-05-02, 2 images, IMG_2173 - IMG_2174 - 5096x2320 - SCUL-Smartblend.jpg",
    "twidth" : 300,
    "theight" : 120,
    "description" : "",
    "author" : "Administrator",
    "nodeRef" : "workspace://SpacesStore/c2f5e06f-ee15-4b0f-9e6c-1f734b4db45f",
    "name" : "2010-05-02, 2 images, IMG_2173 - IMG_2174 - 5096x2320 - SCUL-Smartblend.jpg"
  }
]}

The most important information here are the thumbnail dimensions and the thumbUrl that are used for the gallery grid. If you are interested in the details of the server side code in my Gallery+ extension you can have a look in the webscript.

Standalone JQuery demo version

To demonstrate the grid rendering independently of the full the Alfresco extension I moved the grid generation code to a standalone website with the Javascript logic based on jQuery (the original extension is based on YUI). You can see the example in action at the following URL: http://fmaul.de/gallery-grid-example/

If you try it out, make sure to resize your browser to see the dynamic resizing in action. This is not a full jQuery gallery component, sorry – it is just meant to demonstrate the rendering but you are welcome to further extend the code to a full blown jQuery gallery.

Note that the example gallery is not backed by a REST or thumbnail server, it uses this static JSON file as image source for the purpose of demonstration. The page is built using html5 boilerplate and therefore my complete implementation can be found in the scripts.js file.

 

]]>
http://www.techbits.de/2011/10/25/building-a-google-plus-inspired-image-gallery/feed/ 79
Using the Javascript Console: Creating and populating datalists http://www.techbits.de/2011/10/18/using-the-javascript-console-creating-and-populating-datalists/ http://www.techbits.de/2011/10/18/using-the-javascript-console-creating-and-populating-datalists/#comments Tue, 18 Oct 2011 11:09:16 +0000 Florian http://www.techbits.de/?p=240 Continue reading ]]> This is the first post in a series of posts to showcase the abilities of the Alfresco Javascript Console. The Javascript Console is an Alfresco admin console extension to help developers and administrators to easily develop and execute Javascript against the Alfresco repository. For more information on the Javascript Console and how to install it, see the share-extras wiki page.

In this first installment I’d like to show how to create datalists and datalist items from Alfresco Repository Javascript which can be useful when you want to populate a site’s datalists automatically.

Using the space context to select the site

The first thing you should do in the Javascript Console is to select the space/folder the script is executed in. This automatically puts the node you have selected in a variable called “space”. In this example script we are selecting the Share site where the datalist shall be created. In my local installation I chose the site “jstest” as you can see in the screenshot.To make it even clearer which space my script is expecting I start by assigning it to a variable called “site”:

var site = space;

Now we have a variable site available pointing to the site where the datalist shall be created.

Preparing the site

The “datalists” container within a site may not exist. We need to make sure that it is available or create it if it is missing. Share usually creates this folder automatically when you create your first datalist but if you don’t have a list yet, it might be missing.

var dataLists = site.childByNamePath("dataLists");

if (!dataLists) {
  var dataLists = site.createNode("dataLists", "cm:folder");

  var dataListProps = new Array(1);
  dataListProps["st:componentId"] = "dataLists";
  dataLists.addAspect("st:siteContainer", dataListProps);
  dataLists.save();

  logger.log("Created new datalists folder.");'
}

Creating the datalist

Now let’s create a datalist. I chose the existing contacts datalist type for this example. You can have a look in the datalists model to see which types are available and which properties can be set on each type.  Usually datalists are created with cryptic UUID names (i.e. they don’t have names defined for them) but if you create them yourself you can give them any name you like so you are able to find them later on. The Share UI only displays the datalists title, the name doesn’t show up in Share. I am using “contactlist1” as the name for the new datalist:

var contactList = dataLists.childByNamePath("contactlist1");

if (!contactList) {
  var contactList = dataLists.createNode("contactlist1","dl:dataList");

  // tells Share which type of items to create
  contactList.properties["dl:dataListItemType"] = "dl:contact";
  contactList.save();

  var contactListProps = [];
  contactListProps["cm:title"] = "My Contacts";
  contactListProps["cm:description"] = "A contact list generated by a javascript.";
  contactList.addAspect("cm:titled", contactListProps);

  logger.log("Created contact datalist.");
}

Adding items

Now that we have created a datalist we are ready to place items in the datalist. Since we created a contacts list we need to place items of the type dl:contact in it. We basically create a new node, set the properties of the contact node and save it, that’s all.

var contact = contactList.createNode(null, "dl:contact")
contact.properties["dl:contactFirstName"] = "Florian";
contact.properties["dl:contactLastName"] = "Maul";
contact.properties["dl:contactEmail"] = "info@fme.de";
contact.properties["dl:contactCompany"] = "fme AG";
contact.properties["dl:contactJobTitle"] = "Senior Consultant";
contact.properties["dl:contactPhoneMobile"] = "not available";
contact.properties["dl:contactPhoneOffice"] = "not available";
contact.properties["dl:contactNotes"] = "Alfresco Expert";
contact.save();
logger.log("Created new contact: " + contact.nodeRef);

When you run the complete script you see that the contact list and one contact items are created. Naturally you can create multiple contact items of you like.

One use case for this technique could be to create a lot of items for performance testing during development or you could generate a Javascript file based on this template to migrate content to the datalists.

Wrapping up

Of course this script doesn’t need to run in the Javascript Console. You could also execute it using the Execte Script Action, my Scripts Bootstrap extension or a custom webscript. You just have to make sure you have the node of the site to start with.

Note that the logger.log() messages are printed to the output area. In the Javascript Console these are always displayed regardless of the log level of the ScriptLogger which normally controls the logger output to the Alfresco log file.

I have several other javascript snippets to share with you, so stay tuned for more posts from me on “Using the Javascript Console”. Feedback, questions or ideas for other Alfresco scripting use cases are always welcome.

 

]]>
http://www.techbits.de/2011/10/18/using-the-javascript-console-creating-and-populating-datalists/feed/ 10
Adding a like button to your Alfresco extensions http://www.techbits.de/2011/10/14/adding-a-like-button-to-your-alfresco-extensions/ http://www.techbits.de/2011/10/14/adding-a-like-button-to-your-alfresco-extensions/#comments Fri, 14 Oct 2011 09:30:05 +0000 Florian http://www.techbits.de/?p=267 Continue reading ]]> Alfresco 4.0 introduces social features into the Share client – the most prominent being the Like button. I’d like to give you a short tutorial on how to add the new Like button to your own Alfresco 4.0 Share extensions.

Webscripts Backend

Let’s start with the backend. I am assuming you already have a repository webscript set up that is returning a list of nodes or a single node to the Share client as JSON objects. Now you’d like to add a like button to your client for each document.

In the repository javascript tier you have the ratingService at your disposal. The wiki documentation doesn’t include this service yet, so I did some digging. This is how you would determine if the current user has liked the document and the number of total likes the document has:

isLiked = ratingService.getRating(node, "likesRatingScheme") !== -1;
totalLikes = ratingService.getRatingsCount(node, "likesRatingScheme");

To make it even easier you can import a utility function from the document library that does this

<import resource="classpath:/alfresco/templates/webscripts/org/alfresco/slingshot/documentlibrary-v2/parse-args.lib.js">

and then use the Common.getLikes() function to retrieve the information:

nodes.push({
  "name" : n.name,
  "title" : n.properties["cm:title"],
  "description" : n.properties["cm:description"],
  "nodeRef" : "" + n.nodeRef,
  "likes" : Common.getLikes(n)
});

With this small change (and possibly a change to the webscript’s freemarker template) you have a JSON result from your webscript that returns the like information and looks similar to this: 

{
  "name" : "document.txt",
  "title" : "A test document",
  "description" : "",
  "nodeRef : "workspace://SpacesStore/...",
  "likes" : {
    "isLiked": true,
    "totalLikes": 5
  }
}

Share frontend

Now that we have our webscript returning the like information we need to add the like button to the Share frontend code. Here I assume you have some kind of YUI code already in place which we can extend. The share.js (webapps/share/js/share.js) utility script contains a Like Button component that we can easily use.

First we need to add an empty DIV to our components freemarker template.

<div id="${el}-like"></div>

Then we can add the Like component in the client javascript:

new Alfresco.Like(this.id + '-like').setOptions({
     siteId: this.options.siteId, 
     nodeRef: item.nodeRef,
     displayName: item.name
}).display(item.likes.isLiked, item.likes.totalLikes);

This is all you need to display the Like button.

  • You only have to set the initial values using the display() function. When the user clicks the Like button the totalLikes value is automatically increased by one.
  • This works for documents (for folders you need to set the type=”folder” option).
  • You could leave out the siteId if your component is not site specific. It is used to post the like event to the site’s activity stream.

The only problem I had with this component is that it does not provide a callback or an event when the like status is updated. It posts the like status the the repository, changes it’s display state but since it doesn’t provide feedback you can not update the state of your data model (the item variable) accordingly. This means whenever you redraw or create the Alfresco.Like component you have to make sure you read the most current state of the node from the repository webscript.

All in all adding the like button is pretty painless and I hope you find it as easy to add to your Alfresco extensions.

]]>
http://www.techbits.de/2011/10/14/adding-a-like-button-to-your-alfresco-extensions/feed/ 2
Diving into java scripting frameworks http://www.techbits.de/2006/03/21/diving-into-java-scripting-frameworks/ http://www.techbits.de/2006/03/21/diving-into-java-scripting-frameworks/#comments Tue, 21 Mar 2006 20:10:01 +0000 Florian http://www.techbits.de/2006/03/21/diving-into-java-scripting-frameworks/ Continue reading ]]> As I wrote sunday, I experimented with beanshell and it worked pretty well und faster than I anticipated. Nevertheless I heard about some other scripting frameworks (and their integration in java 1.6) which motivated me to investigate a bit more in this direction. Apparently Mozilla’s Rhino is a very powerful yet fast framework that provides javascript aka ECMAscript. Performance benchmarks by Pankaj Kumar in his article BeanShell, Rhino and Java — Performance Comparison show that my choice of beanshell as a scripting framework might not have been that best – performance wise. I’ll definately check out Rhino for use in my application.

Another interesting framework I came across when looking into scripting with java is the Apache Jakarta Bean Scripting Framework (BSF) which provides a framework to create JSP pages in different scripting languages. To achieve this it offers a uniform interface which wraps several scripting languages like javascript, python, tcl and many more.

]]>
http://www.techbits.de/2006/03/21/diving-into-java-scripting-frameworks/feed/ 1