Wednesday, November 24, 2010

Simple Struts Portlet

1) portlet-ext.xml

--------------------



<portlet>

<portlet-name>EXT_3</portlet-name>

<display-name>Library Portlet</display-name>

<portlet-class>com.liferay.portlet.StrutsPortlet</portlet-class>

<init-param>

<name>view-action</name>

<value>/ext/library/view</value>

</init-param>

<expiration-cache>0</expiration-cache>

<supports>

<mime-type>text/html</mime-type>

</supports>

<resource-bundle>com.liferay.portlet.StrutsResourceBundle</resource-bundle>

<security-role-ref>

<role-name>power-user</role-name>

</security-role-ref>

<security-role-ref>

<role-name>user</role-name>

</security-role-ref>

</portlet>







2) liferay-portlet-ext.xml

----------------------------



<portlet>

<portlet-name>EXT_3</portlet-name>

<struts-path>ext/library</struts-path>

<use-default-template>false</use-default-template>

</portlet>







3) liferay-display.xml

------------------------



add



<portlet id="EXT_3" />



inside



<category name="category.example">






4) struts-config.xml

----------------------



<action path="/ext/library/view" forward="portlet.ext.library.view" />



5) tiles-defs.xml

-------------------



<definition name="portlet.ext.library" extends="portlet" />

<definition name="portlet.ext.library.view" extends="portlet.ext.library">

<put name="portlet_content" value="/portlet/ext/library/view.jsp" />

</definition>





(create the following two jsp files under "/ext/ext-web/docroot/html/portlet/ext/library")



6. init.jsp

-------------



<%@ include file="/html/portlet/init.jsp" %>

Add commonly used variables and declarations here!





7. view.jsp

-------------



<%@ include file="/html/portlet/ext/library/init.jsp" %>

Simple Struts Portlet!



8 Language-ext.properties

---------------------------



Add a new entry in the above file,



javax.portlet.title.EXT_3=Library Portlet

Liferay testing tools

1. jUnit

2. selenium

3. jMeter

4. Grinder

Spring Portlet

Step 1:



create a dummy JSP portlet to begin with by using the following command



create.bat weather "Weather Spring Portlet"


================================================================



Step 2:


create a folder "context" under "/docroot/WEB-INF"



create file "weather-portlet.xml" under "context"



<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "../../dtd/spring-beans.dtd">

<beans>



<bean id="weatherService" class="com.sample.weather.WeatherServiceImpl" />

<bean id="weatherController" class="com.sample.weather.WeatherController">

<property name="weatherService" ref="weatherService" />

</bean>

<bean class="org.springframework.web.portlet.handler.PortletModeHandlerMapping">

<property name="portletModeMap">

<map>

<entry key="view" value-ref="weatherController" />

</map>

</property>

</bean>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />

<property name="prefix" value="/jsp/" />

<property name="suffix" value=".jsp" />

</bean>

</beans>



================================================================



Step 3:



create file "application.xml" under "context"



<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "../dtd/spring-beans.dtd">



<beans>

<bean id="weatherService" class="com.sample.weather.WeatherServiceImpl" />

<!-- Default View Resolver -->

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="cache" value="false"/>

<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>

<property name="prefix" value="/jsp/"/>

<property name="suffix" value=".jsp"/>

</bean>

</beans>



================================================================



Step 4:


create file "view.jsp" docroot/jsp



<%@ page contentType="text/html" isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>



<table border="1">

<tr>

<th>City</th>

<th>Temperature</th>

</tr>

<c:forEach items="${temperatures}" var="temperature">

<tr>

<td>${temperature.key}</td>

<td>${temperature.value} </td>

</tr>

</c:forEach>

</table>



================================================================



Step 5:


create file WeatherController.java under /docroot/WEB-INF/src/com/sample/weather



package com.sample.weather;



import javax.portlet.RenderRequest;

import javax.portlet.RenderResponse;

import org.springframework.web.portlet.ModelAndView;

import org.springframework.web.portlet.mvc.AbstractController;



public class WeatherController extends AbstractController {

private WeatherService weatherService;

public void setWeatherService(WeatherService weatherService) {

this.weatherService = weatherService;

}

public ModelAndView handleRenderRequestInternal(

RenderRequest request, RenderResponse response) throws Exception {

return new ModelAndView("view","temperatures", weatherService.getMajorCityTemperatures());

}

}



================================================================



Step 6:


create the interface WeatherService.java under /docroot/WEB-INF/src/com/sample/weather




package com.sample.weather;



import java.util.Map;

public interface WeatherService {

public Map<String, String> getMajorCityTemperatures();

}



================================================================



Step 7:



create the implementation WeatherServiceImpl.java under /docroot/WEB-INF/src/com/sample/weather



package com.sample.weather;



import java.util.HashMap;

import java.util.Map;



public class WeatherServiceImpl implements WeatherService {

public Map<String, String > getMajorCityTemperatures() {

Map<String, String > temperatures = new HashMap<String, String>();

temperatures.put("New York", "6.0");

temperatures.put("London", "10.0");

temperatures.put("Singapore", "5.0");

return temperatures;

}

}



Step 8:



Modify portlet.xml file



replace,



<portlet-class>com.sample.jsp.portlet.JSPPortlet</portlet-class>



with,



<portlet-class>org.springframework.web.portlet.DispatcherPortlet</portlet-class>



-------------------------



replace,



<init-param>

<name>view-jsp</name>

<value>/view.jsp</value>

</init-param>



with,



<init-param>

<name>contextConfigLocation</name>

<value>/WEB-INF/context/weather-portlet.xml</value>

</init-param>



----------------------------



insert



<portlet-mode>view</portlet-mode>

<portlet-mode>help</portlet-mode>



inside,



<supports> elements



================================================================



Step 8:



(insert the below contents into web.xml)



<display-name>Weather Portlet based on Spring</display-name>



<context-param>

<param-name>webAppRootKey</param-name>

<param-value>com.sample.weather</param-value>

</context-param>



<context-param>

<param-name>log4jConfigLocation</param-name>

<param-value>/WEB-INF/classes/log4j.properties</param-value>

</context-param>



<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/context/application.xml</param-value>

</context-param>



<listener>

<listener-class>org.springframework.web.util.WebAppRootListener</listener-class>

</listener>



<listener>

<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>

</listener>



<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>



<servlet>

<servlet-name>ViewRendererServlet</servlet-name>

<servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>



<servlet-mapping>

<servlet-name>ViewRendererServlet</servlet-name>

<url-pattern>/WEB-INF/servlet/view</url-pattern>

</servlet-mapping>




================================================================



Step 9:



Copy the contents of "lib" folder to "WEB-INF/lib"

Liferay-clustering

Running Liferay in a clustered environment consists of 6 steps.

1. Preparations and getting things ready.
2. Connecting to a remote MySQL database.
3. Running 2 or More "IDENTICAL" Liferay tomcat instances on 2 Or more physical machines.
4. Making one machine as "Apache Web Server"
5. Connecting apache with tomcat using apache module "mod_jk"
6. Configuring mod_jk for clustering for both load-balancing and fail-over.
7. Verifying whether clustering is working fine.

=================================================================================

1. Preparations and getting things ready.

Select 4 physical machines (servers) in your LAN network. Each should have an internal IP address.

Just ping between the 4 machines and confirm that the pinging is successful.

Make sure none of the machines have fire wall running.

1 machine we'll use as Database server (Either windows or Linux) on which MySQL is installed and running
2 machines will be made as clustered servers on which identical verions of liferay is up running.
1 machine will be the apache http server which will be exposed to the outside world. Let this be a windows machine.
In the later part of this exercise we'll see how to run apache on a Linux server.

Note down the IP address of IP addresses of all four machines.

Machine 1 (MySQL) - [IP Address 1]
Machine 2-a (Liferay 1) - [IP Address 2]
Machine 2-b (Liferay 2) - [IP Address 3]
Machine 3 (Apache server with mod_jk) [IP Address 4]

----------------------------------------------------------------------------------------------
2. Connecting to a remote MySQL database.
----------------------------------------------------------------------------------------------

On the machine where mysql is running, open mysql prompt by typing "mysql -u root -proot mysql" from the command window.

Run these following scripts. Before running dont forget to modify the [IP Address X].

create database lportal2 character set utf8;

-- Giving access to the first Liferay machine (2-a)
---------------------------------------------------

insert into db (
Host
,Db
,User
,Select_priv
,Insert_priv
,Update_priv
,Delete_priv
,Create_priv
,Drop_priv
,Grant_priv
,References_priv
,Index_priv
,Alter_priv
,Create_tmp_table_priv
,Lock_tables_priv
,Create_view_priv
,Show_view_priv
,Create_routine_priv
,Alter_routine_priv
,Execute_priv
)
values (
"[IP Address 2]"
,"lportal2"
,"root"
,"Y"
,"Y"
,"Y"
,"Y"
,"Y"
,"Y"
,"N"
,"Y"
,"Y"
,"Y"
,"Y"
,"Y"
,"Y"
,"Y"
,"Y"
,"N"
,"N"
);

GRANT ALL ON lportal2.* TO root@'[IP Address 2]' IDENTIFIED BY 'root';

-- Giving access to the second Liferay machine (2-b)
-- --------------------------------------------------

insert into db (
Host
,Db
,User
,Select_priv
,Insert_priv
,Update_priv
,Delete_priv
,Create_priv
,Drop_priv
,Grant_priv
,References_priv
,Index_priv
,Alter_priv
,Create_tmp_table_priv
,Lock_tables_priv
,Create_view_priv
,Show_view_priv
,Create_routine_priv
,Alter_routine_priv
,Execute_priv
)
values (
"[IP Address 3]"
,"lportal2"
,"root"
,"Y"
,"Y"
,"Y"
,"Y"
,"Y"
,"Y"
,"N"
,"Y"
,"Y"
,"Y"
,"Y"
,"Y"
,"Y"
,"Y"
,"Y"
,"N"
,"N"
);

GRANT ALL ON lportal2.* TO root@'[IP Address 3]' IDENTIFIED BY 'root';

Important:

Once you have run the above scripts, pls dont forget to restart your MySQL.

Verification:

Now open the command window in the 2 machines where liferay is running and enter the command,

mysql -h [IP Address 1] -u root -proot lportal2;

This should successully get entry to the mysql prompt.

Do the similar thing on the other machine where Liferay is running and confirm that is it also connecting to
the remote Mysql database server.

Programmatically import LAR file into Liferay.

public static void addDefaultLayoutsByLAR(
long userId, long groupId, boolean privateLayout, File larFile)
throws PortalException, SystemException {

Map parameterMap = new HashMap();

parameterMap.put(
PortletDataHandlerKeys.PERMISSIONS,
new String[] {Boolean.TRUE.toString()});
parameterMap.put(
PortletDataHandlerKeys.PORTLET_DATA,
new String[] {Boolean.TRUE.toString()});
parameterMap.put(
PortletDataHandlerKeys.PORTLET_DATA_CONTROL_DEFAULT,
new String[] {Boolean.TRUE.toString()});
parameterMap.put(
PortletDataHandlerKeys.PORTLET_SETUP,
new String[] {Boolean.TRUE.toString()});
parameterMap.put(
PortletDataHandlerKeys.USER_PERMISSIONS,
new String[] {Boolean.FALSE.toString()});

LayoutLocalServiceUtil.importLayouts(
userId, groupId, privateLayout, parameterMap, larFile);
}

Creating a new Theme

In the $PLUGINS_SDK/themes folder run:


ant -Dtheme.name=newtheme -Dtheme.display.name="My New Theme" create



"newtheme" will be the theme name we would like to give.


"My New Theme" will the display name of our theme.


Navigate to the newly created $PLUGINS_SDK/themes/newtheme/_diffs and add some customizations to the default theme.


After this, In the $PLUGINS_SDK/themes folder run:


ant war


The war file of our theme will be created in the $PLUGINS_SDK/themes/dist .

Now deploy this war file.

You can go to your deploy (webapps) directory and see the new theme folder being created there.

Once your theme has been deployed, and you're ready to modify the CSS, use the custom.css file to change and override the default styling, leaving all of the other CSS files alone. You can modify any of the javascript files, image files, and template files, but the CSS changes should be restricted to custom.css.


Once you're done modifying your files, you must place them in your _diffs directory with the same directory structure as the actual theme.we'll assume that you've modified the custom.css file, an image file in the dock, and two template


files: portal_normal.vm and portlet.vm. With those files, your _diffs directory would look like this:


plugins/themes/newtheme/


_diffs/

css/

custom.css

images/

dock/

menu_bar.png

templates/

portal_normal.vm

portlet.vm

The order in which your theme is built goes something like this:


It creates the directory and adds the appropriate build files, and XML files needed. It then copies all of the files from the _unstyled/ directory, and after that, the files from _styled/ are copied over, and the last step is that your files in the _diffs directory are copied over. So this means you will place all of your new files and changed files into the _diffs directory.


Color Schemes


In your liferay-look-and-feel.xml (located in WEB-INF), you would specify the class names like so:



<theme id="my_theme" name="My Theme">

<root-path>/my_theme</root-path>

<templates-path>${root-path}/templates</templates-path>

<images-path>${root-path}/images</images-path>

<template-extension>vm</template-extension>

<color-scheme id="01" name="Blue">

<css-class>blue</css-class>

<color-scheme-images-path>${images-path}/color_schemes/${css-class}</color-scheme-images-path>

</color-scheme>

<color-scheme id="02" name="Green">

<css-class>green</css-class>

</color-scheme>

</theme>


The way you would style your different color schemes is like so:


Inside of your css directory, create a folder called "color_schemes". Inside of that directory, place a css file for each of your color schemes. In the case above, we would could either have just one called green.css and let the default styling handle the first color scheme, or you could have both blue.css and green.css.


Now, inside of your custom.css, you would place the following lines:


@import url(color_schemes/blue.css);

@import url(color_schemes/green.css);

The way you would identify the styling for the css is this way: In blue.css you would prefix all of your css styles like this:


.blue a {color: #06C;}

.blue h1 {border-bottom: 1px solid #06C}


And in green.css you would prefix all of your css styles like this:

.green a {color: #0C6;}

.green h1 {border-bottom: 1px solid #0C6}


Customization of CSS

Here are the descriptions for each of the CSS files:


main.css

this file includes all of the other css files. This file can be edited, but probably should not be.

custom.css

This file is where the developer should place all of their css that is different from the other files, unless they are not concerned about upgrading their theme later on. By placing their custom CSS in this file, and not touching the other files, they can be assured that the upgrading of their theme later on will be much smoother.


base.css

This file contains all of the base styling that is fairly generic, such as the styling for all elements not directly related to another aspect of the site, such as the forms or navigation or dock.


forms.css

This file contains all css styling related to form elements on the page.


layout.css

This file contains all of the styling related to the layouts. It is fairly low level, and should most likely not be edited, unless there is something specific they need.


navigation.css

This file contains all of the styling related to the navigation, as well as the dock.


portlet.css

This file contains all of the styling related to the portlets, including the JSR-168 class-names.


tabs.css

This file includes all of the styling related to the tabs in the portlets.


deprecated.css

This file contains styles that are deprecated, but included for compatibility. It can most likely be safely ignored.



Use the custom.css file to change and override the default styling, leaving all of the other CSS files alone. You can modify any of the javascript files, image files, and template files, but the CSS changes should be restricted to custom.css.


For example the body background color is defined in base.css as follows:


body {



background-color: #fff;



}


in the above example the background color used is white ,and if would like to change the color to say black then write the below css in custom.css:


body {



background-color: #000;

}


Similarly we can change the default css by rewriting them in custom.css


Templates:


Here are the descriptions for each of the templates:

portal_normal.vm

this file contains the overall site structure, from opening HTML tag to closing. It includes the header, and footer, and includes the two templates (i.e., dock.vm and navigation.vm) and it also includes the system files needed by the liferay core


dock.vm

this file contains all of the HTML for the dock.


navigation.vm

this file contains all of the html for the navigation


portal_pop_up.vm

this file contains the entire html structure for popup windows.


portlet.vm

this file contains the HTML that wraps every portlet, including the portlet title and portlet-icons.


Customization of templates:

Example portal_normal.vm

If we want the dock to appear only when the user is signed in then the following changes have to be made in portal_normal.vm


Replace the following code


#parse ("$full_templates_path/dock.vm")



with

#if ($themeDisplay.isSignedIn())




#parse ("$full_templates_path/dock.vm")




#end

Import the lar file for the guest community.

Enable the below property in portal-ext.properties to import the lar file for the guest community.

#
# Specify a LAR file that can be used to create the guest public layouts.
# If this property is set, the previous layout properties will be ignored.
#
default.guest.public.layouts.lar=${liferay.home}/deploy/default_guest_public.lar

Inter Portlet Communictaion For Session Attributes

If we set any value in session it will be available until session available.

Include Following Line in liferay-portlet.xml:
<private-session-attributes>false</private-session-attributes>

Create session attribute in any file:
PortletSession ps = req.getPortletSession();
ps.setAttribute(key, value, PortletSession.APPLICATION_SCOPE);

Example:
ps.setAttribute("SAMPLE_ATTRIBUTE", "sample", PortletSession.APPLICATION_SCOPE);

Access in other Portlet File:
String name = ps.getAttribute("SAMPLE_ATTRIBUTE", PortletSession.APPLICATION_SCOPE);
Now name contains sample.

SignOut Message in .vm File

Step: 1
Add the below lines in LogoutAction.java
after session.invalidate();
HttpSession logoutSession = request.getSession();
logoutSession.setAttribute("logoutSession", logoutSession);


Step: 2

create EXTServicePreAction.java under (com.liferay.portal.events.EXTServicePreAction.java )


EXTServicePreAction.java

package com.liferay.portal.events;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.liferay.portal.kernel.events.Action;
import com.liferay.portal.kernel.events.ActionException;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.util.WebKeys;

public class EXTServicePreAction extends Action {


public void run(HttpServletRequest req, HttpServletResponse res)
throws ActionException {
Map vmVariables = new HashMap();
HttpSession session = req.getSession();
HttpSession logoutSession = null;
logoutSession = (HttpSession)session.getAttribute("logoutSession");

try {
if(Validator.isNotNull(logoutSession)){
logoutSession.setAttribute("flag", true);
}else{
logoutSession = req.getSession();
logoutSession.setAttribute("flag", false);
}
} catch (Exception ex) {
Logger.getLogger(EXTServicePreAction.class.getName()).log(Level.SEVERE, null, ex);
}
vmVariables.put("logoutSession", logoutSession);

req.setAttribute(WebKeys.VM_VARIABLES, vmVariables);
}
}

step: 3
Add the below line in portal-ext.properties

servlet.service.events.pre=com.liferay.portal.events.ServicePreAction,com.liferay.portal.events.EXTServicePreAction



step: 4

Add the below line in portal_normal.vm

#if ($logoutSession.getAttribute("flag"))
<div>
<b>Successfully Logout</b>
$logoutSession.invalidate()
</div>
#end

Installing Liferay 5.2.3 on Existing Apache Tomcat 6.0.24

1. Download and install Apache Tomcat 6.0.24 into your preferred directory.

2. Download and install JDK 5 . Set an environment variable called %JAVA_HOME% (in Windows) or $JAVA_HOME (in Linux/UNIX) to point to your JDK directory.


3. Create and edit $TOMCAT_HOME/conf/Catalina/localhost/ROOT.xml to set up the portal web application.
<Context path="" debug="0" reloadable="true" cookies="true" crossContext="false" privileged="false" />


4. Download liferay-portal-5.2.3.war.


5. Download Liferay's Portal 5.2.3 Dependencies.

5.1. Create a $TOMCAT_HOME/lib/ext directory and unzip the dependencies ZIP in there.

6. Edit $TOMCAT_HOME/conf/catalina.properties. common.loader= ${catalina.home}/common/classes,\ ...\ ${catalina.home}/common/lib/ext/*.jar


7. Make sure your database server is installed and is working.
If it's installed in a different machine make sure that it's accessible from the one where Liferay is being installed.


8. Configure data sources for your database. Make sure the JDBC driver for your database is accessible by Tomcat.
8.1. Obtain the JDBC driver for your version of the database server. In the case of MySQL use mysql-connector-java-{$version}-bin.jar.
8.2. Copy the JAR file to $TOMCAT_HOME/lib/ext

9. Create a database for Liferay.
For example: create database lportal character set utf8; Liferay will automatically create the tables and populate it the first time it starts.

10. To add support for accessing Liferay's services remotely and to access the document library using WebDAV follow these steps:
10.1. Download tunnel-web.war
10.2. Create a directory called $TOMCAT_HOME/webapps/tunnel and unzip the WAR contents inside

11. Create $TOMCAT_HOME/conf/jaas.config.

PortalRealm { com.liferay.portal.kernel.security.jaas.PortalLoginModule required; };


12. Edit $TOMCAT_HOME/bin/catalina.bat so that Tomcat can reference the login module.
set JAVA_OPTS=-Xms128m -Xmx512m -Dfile.encoding=UTF8 -Duser.timezone=GMT -Djava.security.auth.login.config=%CATALINA_HOME%/conf/jaas.config

13. Delete contents $TOMCAT_HOME/webapps/ROOT directory.


14. Unpack liferay-portal-5.2.3.war to $TOMCAT_HOME/webapps/ROOT.


15. For supporting UTF-8 UIRIEncoding, edit $TOMCAT_HOME/conf/server.xml.


16. Run Tomcat, point browser to http://localhost:8080. Sign in as test@liferay.com and password test


NOTE: ---- ************copy the following jar files in lib/ext folder to avoid startup problem:********
activation.jar annotations.jar ccpp.jar container.jar hsql.jar jms.jar jta.jar jutf7.jar mail.jar mysql.jar portal-kernel.jar
portal-service.jar portlet-container.jar portlet.jar postgresql.jar serializer.jar support-tomcat.jar xalan.jar xercesImpl.jar

xml-apis.jar

Inter Portlet Communication (IPC) for Portlets on Different Page

Use the below code for Inter Portlet Communication (IPC) for Portlets on Different Page:-

String plidName = "Sample_WAR_Sampleportlet";
long plidForward = getPortletId(plidName);
PortletURL url = new PortletURLImpl(request,plidName, plidForward, PortletRequest.ACTION_PHASE);

---------------------------------------------------------------------------------

public static long getPortletId(String portletId) {

PortletPreferences prfs = null;
try {
DetachedCriteria dCriteria = DetachedCriteria
.forClass(PortletPreferences.class);
dCriteria.add(Restrictions.eq("portletId", portletId));
DynamicQuery dynamicQuery = new DynamicQueryImpl(dCriteria);

List list = PortletPreferencesLocalServiceUtil.dynamicQuery(dynamicQuery);

if (!list.isEmpty()) {
prfs = (PortletPreferences) list.get(0);
}

} catch (Exception e) {
e.printStackTrace();
}
return prfs.getPlid();
}

Share & Enjoy

Twitter Delicious Facebook Digg Stumbleupon Favorites More