Showing posts with label aui. Show all posts
Showing posts with label aui. Show all posts

Monday, February 10, 2014

Introduction to AUI Java Script in Liferay

Objective:

Use AUI java script in liferay development.

What is AUI (Alloy UI)?

Alloy UI is java scrip library winch contains many java script function we can use this for fast implementation of application.

Generally in each application we need to write more java script in web application and some time we need to write same code in multiple times, to avoid this people came up with java script libraries we will use some kind of syntax so that it will bring more functionality to that application.

We can say simple as less writing more work

In any web application java scrip is basic requirement so for this instead of using legacy JavaScript people came up some set of methods/function placed in single place. Whenever we need any functionality simple we use that source file in web application we will use some java script syntax notation to apply real functionality in application

What are most popular java scrip libraries in market?

We have many java script libraries in market like jQuery, AUI, YUI, ExtJs, Dojo and Prototype.

How are these libraries working?

Each java script libraries have many legacy java script code but that code have been abstracted and they will give some syntax notation we will simple use those syntax to apply functionality to application. Each java script has its own syntax style.

How these are finally will work in our application?

In our application we just call source JavaScript of file in our application using <script/> tag then we will use syntax notation that given by java script libraries implementations.

What is basic principle they have used in their implementation?

Java script library implementers use the Module/Plugin. They have made it libraries as pieces so that based on usage they have divided libraries as module or Plugin. The basic and minimum common functionality they have placed in core source file so that whenever we want use then we need minimum core module/Plugin.

Can we implement our own module/Plugin?

Yes we can implement our own Module/Plugin with their specification and syntaxes and we will use core functionality to implement our module or Plugin.

How can we load required Module/Plugin?

We can load Module or Plugin using <script/> or they have given some syntax notation to load required modules. The script in different module or Plugin and they packaged into different source files.

The following screen shows you AUI modules and which are used in Liferay Portal


Which model AUI follows?

AUI will follows modular based implementation so that we will load required module at run time using some syntax and this is called on demand java script load.

What is use of on demand java script loading?

On demand java script avoid unnecessary loading of java script in page so that page loading will be fast. Generally whenever we use <script/> all java script files will be loaded as soon as page is loaded. But in that page we may use few java script even though all java scrip already loaded to avoid this we will use on demand java script which help us loading required java scrip at run time.

Note:

Here we need to load minimum core functionality first that will be loaded by liferay portal default.

What is relation between AUI and Liferay?

AUI is a java scrip library which follows module based java script implementation. Liferay have used AUI java scrip for entire liferay portal so that they have implemented as many modules. Liferay also have custom modules these are enhanced from AUI script these modules used in only in liferay

Note:

 We can use AUI java script in any web application not only in liferay.

What is advantage of use AUI in Liferay?

If we use AUI in liferay then we can use all libraries and other liferay specific functionality directly in liferay development and we have many liferay AUI tags so that we can simple use in Liferay development. Liferay have many AUI components and java script libraries in liferay.

What is source for AUI implementation?

AUI inherited from YUI java script which came from Yahoo

Way of using AUI in any Web application

We need place following script tag in any html page or jsp page so that we can use AUI java script.


<script src="http://cdn.alloyui.com/2.0.0/aui/aui-min.js"></script>


Note:

AUI java script has many components so for look and feel we need call css too

<link href="http://cdn.alloyui.com/2.0.0/aui-css/css/bootstrap.min.css" rel="stylesheet"></link>

Finally if we want use AUI script and its components then do as follows in any html page or JSP page of your web application.


<script src="http://cdn.alloyui.com/2.0.0/aui/aui-min.js"></script>
<link href="http://cdn.alloyui.com/2.0.0/aui-css/css/bootstrap.min.css" rel="stylesheet"></link>


Use AUI in Liferay Development

To use AUI java script and its components in Liferay we need to do as follows in JSP pages


<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<aui:script>
//Start writing AUI script here
<aui:script>


Loading AUI Script

We will use two ways to load AUI script

Using <script> tag and its use attribute


<aui:script use="'aui-io-request,aui-base">
<aui:script>


Using AUI ().use(--) Function


AUI().use('aui-base','aui-io-request', function(A){
// write all AUI scrip here then it will be loaded when page is loaded
});



Note:

In AUI we will reference object as A in every where this like a document object in legacy java script.


We can load many AUI modules based on usage and each module separated by comma separator
The following are example module AUI have many modules.

AUI Modules


aui-audio, aui-base, aui-io, aui-datepicker, aui-node


The following screen shows AUI modules




Example:

When we want to get values of text box then we have to do as follows


<aui:script use="aui-base">
var A = AUI();
var inputValue=A.one('#inputTextBoxId').get('value');
<aui:script>


OR


<aui:script>
AUI().use('aui-base','aui-io-request', function(A){
var inputValue=A.one('#inputTextBoxId').get('value');
});
<aui:script>



We have AUI components in Liferay so that we can use AUI html input components as follows
We need to add AUI tag libraries in JSP page then we can use AUI components and each tag prefix with aui as like <aui:xxx>

<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<aui:input name="articleId" type="text" value="" />

When we use above above ‘aui’ tag then input name attribute will be appended with portlet name space


<aui:input name="articleId" type="text" value="" />

Is same as

<input name="<portlet:namespace/>articleId" id=”<portlet:namespace/> articleId” type="text" value="" />



When we access any element in AUI we will use different assessors those are mostly ID or class name

Note:

For ID we will use # and for class we will use dot (.)

Example:


<aui:input name="articleId" type="text" value="" />
<aui:script>
AUI().use('aui-base','aui-io-request', function(A){
var inputValue=A.one('#<portlet:namespace/>articleId).get('value');
});
<aui:script>

Note:
We already know aui input tag appended with portlet name space.


Simple HTML input accessing using AUI with ID

<input name="articleId" type="text" value="" />
<aui:script>
AUI().use('aui-base','aui-io-request', function(A){
var inputValue=A.one('#articleId).get('value');
});
<aui:script>

Note:

 The above is for simple html text box value accessing from AUI script.


The following is simple html input with portlet name space

<input name="<portlet:namespace/>articleId" id=”<portlet:namespace/> articleId” type="text" value="" />
<aui:script>
AUI().use('aui-base','aui-io-request', function(A){
var inputValue=A.one('#<portlet:namespace/>articleId).get('value');
});
<aui:script>


AUI input tag and its equal tag in normal html


<aui:input name="articleId" type="text" value="" />

Equals to

<input name="<portlet:namespace/>articleId" id=”<portlet:namespace/> articleId” type="text" value="" />

Equals to

<input name="_2_articleId" id=”="_2_articleId” type="text" value="" />



Note:

In the above _2_ is a portlet name space after paged rendered in the browser.

If we use AUI HTML components then we have to use <portlet:namespace/>  in AUI scrip to access the element

Example:


<aui:input name="articleId" type="text" value="" />
<aui:script>
AUI().use('aui-base','aui-io-request', function(A){
var inputValue=A.one('#<portlet:namespace/>articleId).get('value');
});
<aui:script>


If we use simple html input then we no need to add portlet name space in AUI script

<input name="articleId" type="text" value="" />
<aui:script>
AUI().use('aui-base','aui-io-request', function(A){
var inputValue=A.one('#articleId).get('value');
});
<aui:script>


If we add manually portlet name space for normal html input then we need to use same in AUI script


<input name="<portlet:namespace/>articleId" id=”<portlet:namespace/> articleId” type="text" value="" />
<aui:script>
AUI().use('aui-base','aui-io-request', function(A){
var inputValue=A.one('#<portlet:namespace/>articleId).get('value');
});
<aui:script>


Note:

In every where we will use A is reference AUI Script variable it is nothing but document object in legacy java script

Legacy Java Script

Case:1

<input name="articleId" type="text" value="" />
<script>
var inputValue=document.getElemenetById("artcileId").value;
<script>

Case:2

<aui:input name="articleId" type="text" value="" />
<script>
var inputValue=document.getElemenetById("<portlet:namespace/>artcileId").value;
<script>

Case:3

<input name="<portlet:namespace/>articleId" id=”<portlet:namespace/> articleId” type="text" value="" />
<script>
var inputValue=document.getElemenetById("<portlet:namespace/>artcileId").value;
<script>



AUI Java Script


Case:1

<input name="articleId" type="text" value="" />
<aui:script>
AUI().use('aui-base','aui-io-request', function(A){
var inputValue=A.one('#articleId).get('value');
});
<aui:script>

Case:2

<aui:input name="articleId" type="text" value="" />
<aui:script>
AUI().use('aui-base','aui-io-request', function(A){
var inputValue=A.one('#<portlet:namespace/>articleId).get('value');
});
<aui:script>

Case:3

<input name="<portlet:namespace/>articleId" id=”<portlet:namespace/> articleId” type="text" value="" />
<aui:script>
AUI().use('aui-base','aui-io-request', function(A){
var inputValue=A.one('#<portlet:namespace/>articleId).get('value');
});
<aui:script>



Author

Friday, January 10, 2014

Content Auto Update Using AUI Ajax in Liferay Plugin Portlet

Objective:

Update the content in portlet for particular intervals using AUI Ajax mechanism.

Environment:

Liferay 6.2 +Tomcat 7.x+MySQL 5.1
Note:

The code will work for portal 6.2 version you can try for 6.1 too.

Download Content Auto Update Portlet from following location

You can find source and war file


Portlet Screen:



Procedure for deploy portlet:

You can use war file and directly place in your portal deploy folder and test or you can also use source to deploy portlet.

Once portlet is deployed successfully you can see the portlet in sample category name as Content Auto Update.

Introduction:

Some time we may get requirement to update content in portlet for every particular intervals from server. To do this job we will use Ajax call to update content on portlet

What is Set Interval method?

Native java script has set interval method from this we can execute some task for each particular interval.

What is Ajax call?

Ajax is way of calling server content without page refresh in the browser. This will help us to avoid whole page loading for a little content update.

Ajax will help us to update particular part of web page with server side content or dynamic content.

This Ajax mechanism is implemented in client side java script. We have rich Ajax implemented java script libraries in market

The following are popular


AUI, YUI, DOJO, Prototype  and ExtJS


Note:

 Liferay have inbuilt support for AUI script.

What is Serve Resource Method?

Server Resource method is meant for serving some resource or content from server in portlet technology. This method helps us to serve images, files, JSON data and XML data from server.
This method especially we will use with Ajax call to get content from server.

Implementation

Assume we want update users data in page for every particular interval. We will use Ajax and set interval methods to complete this job.

We will use AUI library to implement Ajax in liferay. AUI is very popular java script library for liferay.

The following are the steps to implement
  1. Load AUI library in JSP page
  2. Create server Resource URL
  3. Implement Serve Resource Method to serve Dynamic content
  4. Use AUI Ajax method with serve resource URL
  5. Use Set Interval method to call Ajax

Load AUI library in JSP page

We are using AUI script in JSP page  so we need to load AUI script.AUI is on demand java script library so that whenever we need we can load that java script module this will avoid load all unnecessary java script in the page.

On demand java script load required java script when page is loaded.

We have two ways to load AUI script in page
  1. <aui:script/> Tag
  2. AUI Use Method

<aui:script/> Tag:

This script tag load required core AUI script in the page. If we want more modules then we will specify use attribute for tag.

<aui:script use="aui-node,aui-base">
    // script here
</aui:script>

Note:

When we want use AUI tags in jsp page we need to include aui tag library in jsp page as follows


<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>


AUI Use Method:

AUI use method also loads required AUI java script when page loaded. This can do same thing like <aui:script/> tag.

The fowling syntax for AUI use method

AUI().use('aui-base','aui-io-request', function(A){
//write aui script here
});

Note:

In liferay some of core java script already loaded when liferay portal is ready. That is why we able to sue AUI syntax directly in page. In addition to that if we required other java script module then we will use above mechanism to load on demand java script.

Create server Resource URL

Server Resource URL is meant for call the server resource method from Portlet Action class. We will use this URL in Ajax call. This we will call it as destination URL for Ajax

We will use portlet URL tag to create serve resource URL

The following is serve resource URL

<portlet:resourceURL var="updaContentURL">
</portlet:resourceURL>

Note:

If we want use portlet tags we have to include following tag in JSP page.


<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>


Implement Serve Resource Method to serve Dynamic content

Now we have to override serve Resource method in portlet action class this method will serve the dynamic content as response.

When we is server Resource URL call it will execute serve Resource in portlet action class.
This is the place our business logic should be present.

The following is example

@Override
public void serveResource(ResourceRequest resourceRequest,ResourceResponse resourceResponse)throws  IOException, PortletException {
try {
System.out.println("====serveResource========");
JSONObject jsonUser=null;
JSONArray usersJsonArray=JSONFactoryUtil.createJSONArray();
List<User> userList=UserLocalServiceUtil.getUsers(1, UserLocalServiceUtil.getUsersCount());
for(User userObj:userList){
jsonUser=JSONFactoryUtil.createJSONObject();
jsonUser.put("firstName",userObj.getFirstName());
jsonUser.put("lastName",userObj.getLastName());
jsonUser.put("email",userObj.getEmailAddress());
jsonUser.put("screeName",userObj.getScreenName());
usersJsonArray.put(jsonUser);
}
PrintWriter out=resourceResponse.getWriter();
System.out.println(usersJsonArray.toString());
out.print(usersJsonArray.toString());
}
catch (Exception e) {
e.printStackTrace();
}
}

Note:

Here we need JSON as response data so we will use JSON objects to server JSON data as response.

Use jQuery Ajax method with serve resource URL

Now we will use AUI Ajax to get content from server and we will update in page.

AUI implemented Ajax in aui-io-request module. This module has method called io.request from which we can use Ajax. We also need to mention what kind of data we required as response and here we will JSON as response data.

The following is AUI Ajax call syntax

AUI().use('aui-base','aui-io-request', function(A){
//aui ajax call to get updated content
A.io.request('<%=updaContentURL%>',{
                        dataType: 'json',
                        method: 'GET',
                        data: { paranName: 'ParamValue' },
                        on: {
                                    success: function() {
                                    // response data will be received here     
                                    }
                        }
            });
});

Note:

We have to load aui-io-request module to use Ajax call.

Use Set Interval method to call Ajax

We will use java script native set interval method this will execute the task for each particular intervals

The following is syntax

<script>
//this is set interval method which call the update method for every 30 secends means 3000 milli seconds
setInterval(updateDiv,3000);
//update method to get content from server using resource url
function updateDiv(){
            //Ajax call here
 }
</script>

The following is complete code

Write following code in JSP page

<%@ include file="init.jsp"%>
<style>
#usersTable td{
width:150px;
font-size: 12px;
font-weight: bold;
}
</style>
<portlet:resourceURL var="updaContentURL">
</portlet:resourceURL>
<h1>Content Auto Update From Server using AUI Ajax call with SetInterval Method</h1>
<br/>
<br/>
<div id="userContent">
<table id="usersTable" border="1">
</table>
</div>
<div id="wait" style="display:none; width: 69px; height: 89px; border: 1px solid black; position: absolute; top: 50%; left: 50%; padding: 2px;">
<img src='http://www.w3schools.com/jquery/demo_wait.gif' width="64" height="64" /><br>Loading..</div>
<script>
//this is set interval method which call the update method for every 30 secends means 3000 milli seconds
setInterval(updateDiv,3000);
//update method to get content from server using resource url
function updateDiv(){
AUI().use('aui-base','aui-io-request', function(A){
A.one('#wait').setStyle('display', 'block');
var allRows="";
//aui ajax call to get updated content
A.io.request('<%=updaContentURL%>',{
dataType: 'json',
method: 'GET',
data: { paranName: 'ParamValue' },
on: {
success: function() {
var data=this.get('responseData');
A.Array.each(data, function(obj, idx){
var tableRow='<tr><td>'+obj.screeName+'</td><td>'+obj.firstName+
'</td><td>'+obj.lastName+'</td><td>'+obj.email+'</td></tr>';
allRows=allRows.trim()+tableRow.trim();
A.one('#usersTable').empty();
A.one('#usersTable').setHTML(allRows.trim());
A.one('#wait').setStyle('display','none');
});
}
}
});
});
}
</script>


The following is Serve Resource method in portlet action class

package com.meera.contentautoupdate;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
public class ContentAutoUpdateAction extends MVCPortlet {
@Override
public void serveResource(ResourceRequest resourceRequest,ResourceResponse resourceResponse)throws  IOException, PortletException {
try {
System.out.println("====serveResource========");
JSONObject jsonUser=null;
JSONArray usersJsonArray=JSONFactoryUtil.createJSONArray();
List<User> userList=UserLocalServiceUtil.getUsers(1, UserLocalServiceUtil.getUsersCount());
for(User userObj:userList){
jsonUser=JSONFactoryUtil.createJSONObject();
jsonUser.put("firstName",userObj.getFirstName());
jsonUser.put("lastName",userObj.getLastName());
jsonUser.put("email",userObj.getEmailAddress());
jsonUser.put("screeName",userObj.getScreenName());
usersJsonArray.put(jsonUser);
}
PrintWriter out=resourceResponse.getWriter();
System.out.println(usersJsonArray.toString());
out.print(usersJsonArray.toString());
}
catch (Exception e) {
e.printStackTrace();
}
}
}

Important Points
  • Ajax is way of calling server side content without whole page refresh and it will used to update part of web content.
  • Server Resource method will server images, files and particular format data from server.
  • Set Interval is method in native java script which will call task for each interval.

Related Articles:


Reference Links



Author
Meera Prince

Recent Posts

Recent Posts Widget

Popular Posts