Saturday, March 29, 2014

Difference between Friendly URL’s and URL mappings

Friendly URLs
Friendly URLs are human readable URL prefixes generated based on the content node hierarchy. The URL prefix for content sub node will contain the prefix assigned to the super and all other nodes above it. Friendly URLs are added to a page through page properties in Admin UI or we can add them through XML access too.


By default, Friendly URLs are disabled in websphere portal, to enable them

1. Open WAS admin console.
2. Navigate to Resources -> Resource environment -> Resource environment providers.
3. Search WP_ConfigService and click custom properties.
4. Click “NEW” and add “friendly.enabled” in name and “true” for the value.
5. If it already exists change “friendly.enabled” to true
URL Mappings

URL mappings are used to define the human readable URL prefixes to the content in the portal which will serve as entry points onto the portal. However, these URL mappings will not be preserved upon navigating to other content node. We can define URL mappings through Admin UI and XML access. Portal does not provide any API to construct URL mappings programmatically. URL mappings are preferred when we need a URL to link up between two different portals. This will allow us to maintain a constant URL even with change in content node.


The URL assigned is stored in the page level metadata as com.ibm.portal.friendly.name.
Few Important Points
1. We need to maintain URL mappings for each entry point and they will not be valid for the next navigation state.
2. We need to define friendly URLs for all the pages or nodes in the hierarchy before assigning it to sub pages. It cannot resolve a friendly URL unless and until all pages are properly defined with respective URLs.

3. For friendly URLs, URl assigned is stored in page level metadata as com.ibm.portal.friendly.name.

Thursday, March 27, 2014

SOAP versus RESTful Web service – comparison

Web services are very popular and widely used to integrate similar (i.e. Java applications) and disparate systems (i.e. legacy applications and applications written in .Net etc). It is imperative to understand the differences, pros, and cons between each approach. 


Key Area
SOAP based Web service
RESTful Web service
Specification/Platform Fundamentals (SF/PF)
Transport is platform & protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP, SMTP, etc.

Permits only XML data format, hence language neutral.

You define operations, which tunnels through the POST or GET. The focus is on accessing the named operations and exposing the application logic as a service.

Defines the contract via WSDL.

Transport is protocol specific. Supports only HTTP or HTTPS protocols.

Permits multiple data formats like XML, JSON data, text, HTML, atom, RSS, etc.

Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE web operations. The focus is on accessing the named resources and exposing the data as a service.

Traditionally, the big drawback of REST was the lack of contract for the web service. This has changed with WSDL 2.0 defining non SOAP bindings and the emergence of WADL.

Simpler to implement. REST has Ajax support. It can use the XMLHttpRequestobject.

Good for stateless CRUD (Create, Read, Update, and Delete) operations.

Performance Consideration (PC)
SOAP based reads cannot be cached. The application that uses SOAP needs to provide cacheing.
REST based reads can be cached. Performs and scales better.
Security (SE)
Supports both SSL security and WS-security, which adds some enterprise security features. Supports identity through intermediaries, not just point to point SSL.

WS-Security maintains its encryption right up to the point where the request is being processed.

WS-Security allows you to secure parts (e.g. only credit card details) of the message that needs to be secured. Given that encryption/decryption is not a cheap operation, this can be a performance boost for larger messages.

It is also possible with WS-Security to secure different parts of the message using different keys or encryption algorithms. This allows separate parts of the message to be read by different people without exposing other, unneeded information.

SSL security can only be used with HTTP. WS-Security can be used with other protocols like UDP, SMTP, etc.

Supports only point-to-point SSL security.

The basic mechanism behind SSL is that the client encrypts all of the requests based on a key retrieved from a third party. When the request is received at the destination, it is decrypted and presented to the service. This means the request is only encrypted while it is traveling between the client and the server. Once it hits the server (or a proxy which has a valid certificate), it is decrypted from that moment on.

The SSL encrypts the whole message, whether all of it is sensitive or not.

Transaction Management (TM)

Has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources.
REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.



Quality of Service (QoS)
SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries.
REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.
Best Practice (BP)
In general, a REST based web service is preferred due to its simplicity, performance, scalability, and support for multiple data formats. SOAP is favored where service requires comprehensive support for security, transactional reliability and stricter contract.

Monday, March 17, 2014

Difference between Hashtable and HashMap in java

HashMap
HashMap implements Map interface which maps key to value. It is not synchronized and is not thread safe. Duplicate keys are not allowed and null keys as well as value are allowed.

HashMap<Interger,String> empHashmap=new HashMap<Integer,String>();
empHashmap.put(1,"Kameshwar");
empHashmap.put(2,null);  // This will work fine

Hashtable

Hashtable implements Map interface which maps key to value. It is synchronized and thread safe. Duplicate keys are not allowed and null key is also not allowed.

Hashtable<Interger,String> empHashmap=new Hashtable<Integer,String>();
empHashmap.put(1,"Kameshwar");
empHashmap.put(2,null);  //not allowed and will throw NullPointer exception at run time

Hashtable vs HashMap:

Parameter
HashTable
HashMap
Synchronized
Yes
No
ThreadSafe
Yes
No
Performance
Due to theadSafe and Synchronized, it is often slower than HashMap
In single threaded environment, it is much faster than Hashtable. So if you do not work in multi thread environment ,then HashMap is recommended
Null key
Do not allow
Allows null key as well as values
Fail fast
enumeration in Hashtable is not fail fast
Iterator in HashMap is fail fast
Extends
It extends Dictionary class which is quite old
It extends AbstractMap class
Alternative
No alternative
You can use ConcurrentHashMap for multi thread environment

Some important points need to be discussed. 

  • Synchonized meaning only one thread can modify one table  at one point of time. When any thread perform update operation on hashtable then it acquires lock on it and other threads have to wait for lock to be released.
  • Fail-fast iterator means if one thread is iterating over HashMap and other thread trying to modify HashMap structurally it will throw ConcurrentModification Exception and fail immediately. Structurally modification means inserting or deleting elements that can change structure of map.

Can we synchronize HashMap?

Yes, We can synchonized a HashMap also with the help of Collections.synchonizedMap(hashmap) so HashMap can be synchronized by using below code.

Map map=Collections.synchonizedMap(hashmap)

Sunday, March 16, 2014

Changes required in serveResource to serve special characters

It seems that returning UTF-8 characters from characters from serveResource method requires some additional steps.

I created this sample portlet which returns some Chinese characters from both 
doView() and serveResource() method. The content returned from doView() is ok, but the content returned by serveResource() returns garbage character

public void doView(RenderRequest request, RenderResponse response) 
throws PortletException, IOException {
  // Set the MIME type for the render response
  response.setContentType("text/html; charset=UTF-8");
  response.getWriter().println("
这是世界您好");
}

public void serveResource(ResourceRequest request,
  ResourceResponse response)
  throws PortletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    response.getWriter().println("
这是世界您好");
}

It seems that in order to return valid response from 
serveResource method we have to add some additional properties on the response

public void serveResource(ResourceRequest request, ResourceResponse response)
  throws PortletException, IOException {
  response.setContentType("text/html; charset=UTF-8");
  response.setCharacterEncoding("UTF-8");
  response.setProperty("Content-Type","text/html; charset=UTF-8");
  response.getWriter().println("
这是世界您好");
}

Two-Phase rendering support in IBM WebSphere Portal 7.0 and 8.0 with JSR 286 Portlets

When you work on portlets there are certain challenges when it comes to setting up cookies, http headers or changing the page title dynamically. IBM WebSphere Portal with JSR-286 portlets can solve this problem by enabling Two-Phase Rendering.

By default, two-phase rendering is turned off. To enable two-phase rendering for a portlet, you must update the portlet.xml deployment descriptor for the portlet.

Add the following entry to the file:

<portlet>
...
<container-runtime-option>
<name>javax.portlet.renderHeaders</name>
<value>true</value>
</container-runtime-option>
</portlet>

Changing or setting up Page Title of a JSR-286 Portlet dynamically

To write into the HTML head section of your JSR 286 portlet, for example, to change a page title, use the addProperty method on the PortletResponse.

Invoke the addProperty method to modify the HTML head section.

PortletReponse.addProperty(String key, org.w3c.dom.Element element)

Note: When modifying the HTML head section, you must invoke the addProperty method before the response headers are committed. This should occur no later than during the render headers sub phase of the render lifecycle phase.

Below is the example to explain this.
protected void doHeaders(RenderRequest request, RenderResponse response)
{
    Element title = response.createElement("title");
    title.setTextContent("My Portal Page Title");
    response.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT, title);

}

Wednesday, March 12, 2014

Available implicit objects Liferay JSP page

On a normal JSP page, some objects are implicitly available. In addition, we can get several others in Liferay using the taglibs. But we don't know all.

Lets see about normal JSP first:

These objects are created by the container automatically and the container makes them available to us. Since these objects are created automatically by the container and are accessed using standard variables; and that is why, they are called implicit objects. They are parsed by the container. They are available only within the jspService method and not in any declaration.

1. request (javax.servlet.ServletRequest)
2. response (javax.servlet.ServletResponse)
3. out (javax.servlet.jsp.JspWriter)
4. pageContext (javax.servlet.jsp.PageContext)
5. session (javax.servlet.http.HttpS)
6. application (javax.servlet.ServletContext)
7. config (javax.servlet.ServletConfig)
8. page (java.lang.Object)
9. exception (java.lang.Throwable)

Now, lets eleborate the liferay context:

The following statements will give 14 default objects :

1. <%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
2. <portlet:defineObjects />
3. actionRequest (javax.portlet.ActionRequest)
4. actionResponse (javax.portlet.ActionResponse)
5. eventRequest (javax.portlet.EventRequest)
6. eventResponse, (javax.portlet.EventResponse)
7. portletConfig, (javax.portlet.PortletConfig)
8. portletName, (java.lang.String portletName ;
9. portletPreferences, (javax.portlet.PortletPreferences)
10. portletPreferencesValues, (java.util.Map)
11. portletSession, (javax.portlet.PortletSession)
12. portletSessionScope, (java.util.Map)
13. renderRequest, (javax.portlet.RenderRequest)
14. renderResponse, (javax.portlet.RenderResponse)
15. resourceRequest, (javax.portlet.ResourceRequest)
16. resourceResponse (javax.portlet.ResourceResponse)

And the following statements will give 18 default objects :

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


and the type of each object as follows :

1. themeDisplay (com.liferay.portal.theme.ThemeDisplay)
2. company (com.liferay.portal.model.Company)
3. account (com.liferay.portal.model.Account)
4. user (com.liferay.portal.model.User)
5. realUser (com.liferay.portal.model.User)
6. contact (com.liferay.portal.model.Contact)
7. layout (com.liferay.portal.model.Layout)
8. layouts (java.util.List)
9. plid (java.lang.Long)
10. layoutTypePortlet (com.liferay.portal.model.LayoutTypePortlet)
11. scopeGroupId (java.lang.Long)
12. permissionChecker (com.liferay.portal.security.permission.PermissionChecker)
13. locale (java.util.Locale)
14. timeZone (java.util.TimeZone)
15. theme (com.liferay.portal.model.Theme)
16. colorScheme (com.liferay.portal.model.ColorScheme)
17. portletDisplay (com.liferay.portal.theme.PortletDisplay)
18. portletGroupId (java.lang.Long)

These default objects can be acquired using pageContext which is an implicit object of JSP. Use the following code for getting default objects.

ActionRequest actionRequest = (ActionRequest) pageContext.findAttribute(“actionRequest”);

So, here are the objects that I found. Hope this will help.

How to fetch parameter from url in Liferay:

Example : 1
If the value is in request object we can get the parameter like this :

String articleId1 = actionRequest.getParameter("articleId");
System.out.println("String : Article ID : "+articleId1);


Example : 2

If you are getting the value from portal url :

String articleId = ParamUtil.getString(actionRequest, "articleId");
System.out.println("Article ID : "+articleId);

Example : 3

If you are getting the parameter from address bar :

HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(actionRequest));
String myArticleId = httpReq.getParameter("articleId");

Custom Attributes in Liferay

Follow the steps for making custom attributes-
Go to Control Panel -> User - > Custom Attribute -> Add Custom Attribute
An Attribute is a key and type of the field (once saved) cannot be changed at all...
Accessing Custom Attribute Pragmatically:
ThemeDisplay themeDisplay=(ThemeDisplay)request.getAttribute(Web_Keys.THEME_DISPLAY);
User user = themeDisplay.getUser();
System.out.println(user.getExpendoBridge().getAttribute("CustomAttributeName"));
Setting Attribute Pragmatically:
ThemeDisplay themeDisplay =(ThemeDisplay)request.getAttribute(Web_Keys.THEME_DISPLAY);
User user = themeDisplay.getUser();
System.out.println(user.getExpendoBridge().setAttribute("CustomAttributeName","Value"));
Adding custom Attribute form element at Sign In Portlet
write the following code in /root/html/portlet/login/create_account.jsp
<liferay ui:custom-attribute-list
                  className="com.liferay.portal.model.user"
                  editable="<%=true%>"
                  label="<%=true%>">
but this will not visible to due to permission. So, login as admin and provide permission to guest to see and modify custom field through control panel.