Thursday, 31 March 2016

How to access Portal and Custom Service(Portlet) in Velocity Template (.vm) file

Accessing a custom service / liferay service would be essential specially if you are dealing with the .vm file in Theme / Template (Webcontent)

 There are four simple steps to access service inside .vm file:

1)    Changes in portal-ext.properties
2)    Modify .vm file to access portal service
3)    Modify .vm file to access portlet (custom service)
4)    Verify

Here are the steps in detail:

1)    Changes in portal-ext.properties

To access service we need to use the velocity custom field called "serviceLocator" but by default we can not use service inside .vm file.
as "serviceLocator" variable is restricted to use in .vm file

Here is the default configuration of the liferay inside portal-impl/src/portal.properties

    #
    # Set a comma delimited list of variables the Velocity engine cannot
    # have access to. This will affect Dynamic Data List templates, Journal
    # templates, and Portlet Display templates.
    #
    velocity.engine.restricted.variables=serviceLocator


To enable use of "serviceLocator" below line need to be placed inside porta-ext.properties file.

    velocity.engine.restricted.variables=
   
2)    Modify .vm file to access portal service

Lets say if I want to find company id of one of the existing webcontent ("JournalArticle") then here is the code I may write. Service provided by Liferay OOTB (Out of the Box)

#set ($customLocalService = $serviceLocator.findService('com.liferay.portlet.journal.service.JournalArticleLocalService'))
$customLocalService
Company Id : $customLocalService.getArticle(22214).getCompanyId();



3)    Modify .vm file to access portlet (custom service)

Lets say I have my own portlet called "student-service-portlet" and I like to access name of student having student id "45" then here is the code I would write.

#set ($customLocalService1 = $serviceLocator.findService('student-service-portlet','com.myschool.entities.service.StudentLocalService'))
$customLocalService1
Student Name is : $customLocalService1.getStudentById(45).getName();


4)    Verify

To verify our functionality we will make use of Webcontent , Structure, Template.

Just create one web content with one dummy structure and a template associated to it.
Select the language of Template as "Velocity (.vm)" and paste the code written in step #2 / #3
Save Webcontent and add "Web Content Display" portlet and select the newly created webcontent in it.

On screen you will see the output as

com.liferay.notifications.hook.service.impl.JournalArticleLocalServiceImpl@5e7eb702 Company Id : 20155; com.myschool.entities.service.impl.StudentLocalServiceImpl@49a78571 Student Name is : Henal;

We are done!

Cheers!
Henal Saraiya

Tuesday, 22 March 2016

How to Create a Liferay Application Startup Event Hook

How to Create a Liferay Application Startup Event Hook

Many a times I have seen that application needs to have a lot of configuration, doing all such configuration manually is time consuming job at the same time its tedious too. Fortunately Liferay provides a way to get configuration done grammatically and get rid of manual configuration. Application Startup Event Hook is useful for writing a configuration logic related to configuration of the system.

Here are the simple steps for creating the Application Startup Event Hook
1    Create a Hook "{startupaction}"
2    Create a custom class / action to be executed for configuration
3    Create a properties file for a Hook
4    Map properties file entry with "liferay-hook.xml"
5    Deploy "{startupaction}" hook
6    Test functionality

Here are the steps in detail
1    Create a Hook "{startupaction}"

    To create a hook from command prompt follow below commands:
    i)    Go to your liferay plugin sdk / hooks
    ii)    Fire a command on command propmpt called e:/lifera.../hook>create startupaction "startupaction"

2    Create a custom class / action to be executed for configuration

    Custom Action class which we create will be executed (run method) at the time of deploying our {startupaction} hook
    Lets say we create a Class/Action called "MyStartUpAction" which is used to create a custom field of an organization called "orgType".
    Here is the sample code for

        package com.startup.action;

        import java.util.List;

        import com.liferay.portal.kernel.events.ActionException;
        import com.liferay.portal.kernel.events.SimpleAction;
        import com.liferay.portal.kernel.exception.PortalException;
        import com.liferay.portal.kernel.exception.SystemException;
        import com.liferay.portal.kernel.util.UnicodeProperties;
        import com.liferay.portal.model.Company;
        import com.liferay.portal.model.Role;
        import com.liferay.portal.model.User;
        import com.liferay.portal.security.auth.PrincipalThreadLocal;
        import com.liferay.portal.security.permission.PermissionChecker;
        import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
        import com.liferay.portal.security.permission.PermissionThreadLocal;
        import com.liferay.portal.service.CompanyLocalServiceUtil;
        import com.liferay.portal.service.RoleLocalServiceUtil;
        import com.liferay.portal.service.UserLocalServiceUtil;
        import com.liferay.portlet.expando.model.ExpandoBridge;
        import com.liferay.portlet.expando.model.ExpandoColumnConstants;
        import com.liferay.portlet.expando.util.ExpandoBridgeFactoryUtil;

        public class MyStartupAction extends SimpleAction {
            /*
             * (non-Java-doc)
             *
             * @see com.liferay.portal.kernel.events.SimpleAction#SimpleAction()
             */
            public MyStartupAction() {
                super();
            }

            /*
             * (non-Java-doc)
             *
             * @see com.liferay.portal.kernel.events.SimpleAction#run(String[] arg0)
             */
            public void run(String[] companyId) throws ActionException {
                // TODO Auto-generated method stub

                System.out.println("Length of arguments " + companyId.length + " value is " + companyId[0]);
                System.out.println("My Startup Action Method has been called..... !!!");
               
                //We like to create a custom field for the resourceType as "organization".
                String modelResource = "com.liferay.portal.model.Organization";
                long resourcePrimKey = 0;
                String name = "orgType";

                ExpandoBridge expandoBridge = ExpandoBridgeFactoryUtil
                        .getExpandoBridge(Long.parseLong(companyId[0]), modelResource,
                                resourcePrimKey);

                UnicodeProperties properties = null;
                try {
                    properties = expandoBridge.getAttributeProperties(name);
                } catch (Exception e) {
                    properties = new UnicodeProperties();
                }

                //Creating a default property for the "orgType" custom field
                int type = ExpandoColumnConstants.STRING;
                properties.setProperty(ExpandoColumnConstants.PROPERTY_HEIGHT, "105");
                properties.setProperty(ExpandoColumnConstants.PROPERTY_WIDTH, "450");

                //This is a mimic to set a custom permission checker. If we dont set this then while adding a new attribute in expando will create a permission checker error. Piece of code from DoAsUserThread class
                setPermissionChecker(companyId);

                try {
                    expandoBridge.addAttribute(name, type);
                } catch (PortalException e) {
                }
                expandoBridge.setAttributeProperties(name, properties);
            }
           
            /*
                Setting up the custom permission checker object
            */
            private void setPermissionChecker(String[] companyId) {
                Company companyqq = null;
                try {
                    companyqq = CompanyLocalServiceUtil.getCompanyById(Long.parseLong(companyId[0]));
                } catch (PortalException | SystemException e1) {
                }
                Role adminRole = null;
                try {
                    adminRole = RoleLocalServiceUtil.getRole(companyqq.getCompanyId(),"Administrator");
                } catch (PortalException | SystemException e1) {
                }
                List<User> adminUsers = null;
                try {
                    adminUsers = UserLocalServiceUtil.getRoleUsers(adminRole.getRoleId());
                } catch (SystemException e1) {
                }

                PrincipalThreadLocal.setName(adminUsers.get(0).getUserId());
                PermissionChecker permissionChecker = null;
                try {
                    permissionChecker = PermissionCheckerFactoryUtil.create(
                            adminUsers.get(0), true);
                } catch (Exception e1) {
                }
                PermissionThreadLocal.setPermissionChecker(permissionChecker);
            }
        }

   
3    Create a properties file for a Hook

    Create a properties file lets say "portal.properties" in our case on the location   
    liferay-plugins-sdk-6.2\hooks\{startupaction}-hook\docroot\WEB-INF\src\portal.properties
   
    Inside the "portal.properties" file add an entry as below of our custom class / action i.e. MyStartupAction in our case
    application.startup.events=com.startup.action.MyStartupAction

   
4    Map properties file entry with "liferay-hook.xml"

    We need to specify the name of the property file inside the "liferay-hook.xml" file. This is the file which Liferay hook will read for all the overridden properties
   
    Here is the sample entry of "liferay-hook.xml"
    <?xml version="1.0"?>
    <!DOCTYPE hook PUBLIC "-//Liferay//DTD Hook 6.2.0//EN" "http://www.liferay.com/dtd/liferay-hook_6_2_0.dtd">

    <hook>
        <portal-properties>portal.properties</portal-properties>
    </hook>

   
5    Deploy "{startupaction}" hook
   
    Alright Then! We are done with our coding / changes for application startup action hook. Just deploy our hook via below command

    i)    Open command Prompt and go to the location of your plugin sdk and hit "ant"
    ii)    e:\...\liferay-plugins-sdk-6.2\hooks\{startupaction}-hook>ant
   
6    Test functionality

Once we deploy our {startupaction} hook in the console we can see below entries which is the proof that our hook is invoked and our custom
field will be created called "orgType" under "organization".







Console Output is:
Length of arguments 1 value is 20155
My Startup Action Method has been called..... !!!


To verify from the Admin console follow below steps

1)    Go to "Admin" -> "Control Panel"
2)    Go to "Configuration" -> "Custom Fields"
3)    Go to "Organization" -> "Edit"
4)    See our newly created custom field called "orgType" is created and available in listing

Great! We are done!

Cheers!
Henal Saraiya

Thursday, 3 December 2015

How to read liferay portlepreferences and read particular key of the preferences

Many a times we like to read the preferences of the portlet which is not of the current portlet scope (Preferences of the other than the current portlet). Liferay provides API called "PortletPreferencesLocalServiceUtil" to get the portletpreferences object / value.

API has methods which returns the one of the two objects :

1) com.liferay.portal.model.PortletPreferences
   This will provide the model object of PortletPreferences. It will not support to directly fetch value of specified key. If we like to get handler to fetch directly value from the key then we need to convert the "com.liferay.portal.model.PortletPreferences" to "javax.portlet.PortletPreferences". Liferay provides the API for this conversion as well:

Here is the quick example:
   //Fetching the list of model object of PortletPreferences

   List<com.liferay.portal.model.PortletPreferences> portletPreferencesObj = PortletPreferencesLocalServiceUtil.getPortletPreferences(themeDisplay.getLayout().getPlid(), portletId);
  
   //Take out the xml / preferences of PortletPreferences Table


   String xmlValue = portletPreferencesObj.get(0).getPreferences();
  
   //Convert the xml into javax.portlet.PortletPreferences i.e. key value pair


   javax.portlet.PortletPreferences portletPreferencesObjWithKeyValue = com.liferay.portlet.PortletPreferencesFactoryUtil.fromDefaultXML(xmlValue);

  
   //Once we have converted portlet preference object we can fetch value of the specified key. "studentId" in our case
                           
   String studentId = portletPreferencesObjWithKeyValue.getValue("studentId",StringPool.BLANK);              


2) javax.portlet.PortletPreferences
    This allows to read the value of the specified key directly:
   
    Here is the quick example:   
    //Returns the "javax.portlet.PortletPreferences" Object

    javax.portlet.PortletPreferences portletPreferencesObj = PortletPreferencesLocalServiceUtil.getPreferences(themeDisplay.getCompanyId()
                            ,PortletKeys.PREFS_OWNER_ID_DEFAULT,PortletKeys.PREFS_OWNER_TYPE_LAYOUT,themeDisplay.getLayout().getPlid(),
                            portletId);
    //Once we have portlet preference object we can fetch value of the specified key. "studentId" in our case 

                          
    String studentId = portletPreferencesObj.getValue("studentId",StringPool.BLANK);   
           

Note: In above API "portletId" is the portletname along with the instance if it is instanceable portlet.                               

We are done!

Cheers!
Henal Saraiya

Saturday, 5 September 2015

How to implement SSL in tomcat

Before we jump into how to implement SSL, lets look at once why SSL is required:

Whenever we want to share any sensitive information from client to server, it is advisable to pass the request in an encrypted mode. SSL help us to pass the details in a secure manner from client to server. A client uses a certificate to authenticate server.

In a market there are few certificate authorities available which validates the server as per the certificate available with the browser / client.

If you want to implement SSL in tomcat its very easy. You just have to follow couple of steps and you will be done with SSL in your application.

Here are four simple steps need to be performed:

1) Generate keystore file
2) Modify server.xml file
3) Restart your server
4) Test

Here are the steps in detailed:

1) Generate keystore file

In java if we want to generate a certificate then we can use the utility called "keytool". Here are the steps one need to follow for creating a certificate:

C:\java\jdk*\bin>keytool -genkey -alias tomcat -keyalg RSA

Enter keystore password:  changeit
What is your first and last name?
  [Unknown]:  hs

Just keep pressing "Return" for all the question which is being asked like 

What is the name of your organizational unit?
What is the name of your organization?
What is the name of your City or Locality?
What is the name of your State or Province?
What is the two-letter country code for this unit?
Is CN=hs, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?
  [no]:  yes

Note: default password is "changeit".

After following above steps automatically a file will be generated on the home directory with the name called ".keystore". ex: C:\Users\{UserName}

2) Modify server.xml file

Uncomment the below line inside "\apache-tomcat-*\conf\server.xml" file to support the "https" requests.

<Connector SSLEnabled="true" clientAuth="false" maxThreads="150" port="8443" protocol="HTTP/1.1" scheme="https" secure="true" sslProtocol="TLS"/>


3) Restart your server

We are almost done with the setup of SSL,  since we have made changes inside "server.xml" file it is mandatory to bounce your server to bring "server.xml" changes.

4) Test

Time to verify whether SSL is really enabled and working or not. To verify hit any of your application's URL with "https". Ex: I have one application available called "student" so to verify default landing page I will hit my URL like this:

https://localhost:8443/student/index.jsp

We are done!

Cheers!
Henal Saraiya

Thursday, 30 July 2015

How to write hibernate application using MySql

This blog will be helpful to create simple java application using hibernate:

To make things very easy we will be taking an example of student. In this example we will be creating a "StudentRecord" table and will insert dummy student data in it.

We will see how "Hibernate" can create a table for us. Hence we don't need to worry about creating a table manually. Our application will take care of not just insertion
of the student record but creating of table as well.

There are few simple steps we need to perform for writing simple hibernate java application.

Here are the main steps:

1. Create Entity Class
2. Create ".hbm" file for the student 
3. Hibernate configuration XML file
4. Create a Dummy Class to test application
5. Run and Verify
6. Trouble Shoot

Let's see the steps in detailed

1. Create Entity Class

This is a POJO class which holds all the properties related to student along with the  setter and getter methods.

Here is the quick code snippet:

package student.persistence;

public class Student {

private int studentId;
private String studentName;
private String email;
private String gender;

public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}

In our case we have used four properties "studentId", "studentName", "email", "gender". Whose value we will be storing inside the table in the proceeding steps:

2. Create ".hbm" file for the student 

For every "POJO" we need to create ".hbm" file. ".hbm" file contains the mapping of "POJO" (Class) with "Relational Table" (StudentRecord) in our case.
At the same time ".hbm" file contains the association between "attributes" of the "POJO" with the "column" of the "Table".
We can also specify the constraint like "primary key" , "composite key" etc in ".hbm" file.

Here is the quick code snippet:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="student.persistence.Student" table="StudentRecord">
<id name="studentId">
<generator class="assigned"></generator>
</id>
<property name="studentName"></property>
<property name="email"></property>
<property name="gender"></property>
</class>
</hibernate-mapping>

3. Hibernate configuration XML file (.cfg) file

For every application there is one "hibernate.cfg.xml" file. Which is the main mapping file. It contains the details related to database, connection,username,
password,dialect etc. Along with the few hibernate specific properties can also be specified.

Here is the quick reference of "hibernate.cfg.xml" file:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/student</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="student.hbm.xml" />
</session-factory>
</hibernate-configuration>

In our application we have used the "MySQLDialect" which means our application will be creating a table inside "MySql" database.
Property "hibernate.connection.url" contains the details like under which databse/schema our tables should get created. In Url "..../student" we have specified
that means that our table "StudentRecord" will be created under "student" schema.

Property "<mapping resource="student.hbm.xml" />", loads the student.hbm.xml file.
Property "<property name="show_sql">true</property>" will print the all the sql which our application will fire. (Its very helpful for the debugging purpose)


4. Create a Dummy Class to test application

In our java application we will be using "StudentDemo" as an entry point for the application. In our dummy class we will be doing following operations

Load Configuration file ("hibernate.cfg.xml")
Build Session Factory
Open Session
Create, Instantiate, Initialize a student pojo
begin the transaction
save/persist student pojo
commit the transaction
Close Session and Factory respectively.

Here is the code snippet for quick reference:

package student.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import student.persistence.Student;

public class StudentDemo {

    public static void main(String[] args) {

        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");

        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();
        Student student = new Student();
        student.setStudentName("Peter");
        student.setGender("M");
        student.setEmail("peter@test.com");
        
        Transaction tx = session.beginTransaction();
        session.save(student);
        
        System.out.println("Student Record Saved Successfully! ");
        
        tx.commit();
        session.close();
        factory.close();
    }
}


5. Run and Verify

When we run the "StudentDemo" class we can see below console output:

Jul 30, 2015 2:55:35 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.0.CR2}
Jul 30, 2015 2:55:35 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jul 30, 2015 2:55:35 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jul 30, 2015 2:55:37 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.0.Final}
Jul 30, 2015 2:55:37 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Refer to Hibernate 3.6 Migration Guide!
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/student]
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jul 30, 2015 2:55:40 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jul 30, 2015 2:55:42 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: 
    drop table if exists StudentRecord
Hibernate: 
    create table StudentRecord (
        studentId integer not null,
        studentName varchar(255),
        email varchar(255),
        gender varchar(255),
        primary key (studentId)
    )
Jul 30, 2015 2:55:43 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Student Record Saved Successfully! 
Hibernate: 
    insert 
    into
        StudentRecord
        (studentName, email, gender, studentId) 
    values
        (?, ?, ?, ?)
Jul 30, 2015 2:55:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost:3306/student]


We can see that first of all hibernate goes to drop the table if the table already exist. Then it creates the table using auto generated "Create" script.
and then it insert the record into the "StudentRecord" table.

Here is the snippet we can see in the database:




6. Trouble Shoot

Overall our application package structure should look like this:



For more trouble shoot please refere "http://technoknowledgespread.blogspot.in/2015/07/common-errors-while-configuring.html"

Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Common errors while configuring a hibernate application

I have seen that people struggle a lot while setting up the hibernate application.

Here is a blog which will help the user for the common errors and its resolution.

1) NoClassDefFoundError : org/apache/commons/logging/LogFactory

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:110)
at student.test.StudentDemo.main(StudentDemo.java:14)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 2 more

Resolution : Need to include jar file "commons-logging-1.2.jar"



2) NoClassDefFoundError : org/dom4j/io/SAXReader

Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/io/SAXReader
at org.hibernate.util.XMLHelper.createSAXReader(XMLHelper.java:35)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1168)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1112)
at student.test.StudentDemo.main(StudentDemo.java:15)
Caused by: java.lang.ClassNotFoundException: org.dom4j.io.SAXReader
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 4 more

Resolution : Need to include jar file "dom4j-1.6.1.jar"



3) NoClassDefFoundError: org/apache/commons/collections/SequencedHashMap

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/SequencedHashMap
at org.hibernate.mapping.Table.<init>(Table.java:32)
at org.hibernate.cfg.Mappings.addTable(Mappings.java:120)
at org.hibernate.cfg.HbmBinder.bindRootPersistentClassCommonValues(HbmBinder.java:251)
at org.hibernate.cfg.HbmBinder.bindRootClass(HbmBinder.java:236)
at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:152)
at org.hibernate.cfg.Configuration.add(Configuration.java:362)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:400)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:449)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1263)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1235)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1217)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1184)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1112)
at student.test.StudentDemo.main(StudentDemo.java:15)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections.SequencedHashMap
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 14 more

Resolution : Need to include jar file "commons.collections-3.2.1"



4) NoClassDefFoundError: net/sf/ehcache/CacheException

Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/ehcache/CacheException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at org.hibernate.cfg.SettingsFactory.createCacheProvider(SettingsFactory.java:323)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:219)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1463)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1004)
at student.test.StudentDemo.main(StudentDemo.java:17)
Caused by: java.lang.ClassNotFoundException: net.sf.ehcache.CacheException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 10 more


Resolution : Need to include jar file "ehcache-core-2.4.3"



5) NoClassDefFoundError: javax/transaction/Synchronization

INFO: Default entity-mode: pojo
Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/Synchronization
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1005)
at student.test.StudentDemo.main(StudentDemo.java:17)
Caused by: java.lang.ClassNotFoundException: javax.transaction.Synchronization
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 2 more


Resolution : Need to include jar file "jta.jar"



6) NoClassDefFoundError: net/sf/cglib/core/KeyFactory

INFO: Default entity-mode: pojo
Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/cglib/core/KeyFactory
at org.hibernate.impl.SessionFactoryImpl.<clinit>(SessionFactoryImpl.java:321)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1005)
at student.test.StudentDemo.main(StudentDemo.java:17)
Caused by: java.lang.ClassNotFoundException: net.sf.cglib.core.KeyFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 3 more


Resolution : Need to include jar file "cglib-2.1_3"



7) NoClassDefFoundError: org/objectweb/asm/Type

INFO: Default entity-mode: pojo
Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/Type
at net.sf.cglib.core.TypeUtils.parseType(TypeUtils.java:180)
at net.sf.cglib.core.KeyFactory.<clinit>(KeyFactory.java:66)
at org.hibernate.impl.SessionFactoryImpl.<clinit>(SessionFactoryImpl.java:321)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1005)
at student.test.StudentDemo.main(StudentDemo.java:17)
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 5 more


Resolution : Need to include jar file "asm-1.3.3"

Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Monday, 20 July 2015

How to use Error Handlers in Java EE

Client sends a request to the Server for a specific resource. Sometimes it is possible that due to one or another reason server sends an Http status code (related to error) to the client, instead of actual response to the client.

In Java EE it is possible to redirect or show a specific error page as and when any particular error message comes up.

There are two simple steps to be performed for "Error Handlers"

1) Modify web.xml (deployment descriptor) file to add "Error Handlers"
2) Add a JSP to be shown when an error occurs
3) Run and Verify

Here are the detailed steps:

1) Modify web.xml (deployment descriptor) file to add "Error Handlers"

<error-page>
        <error-code>404</error-code>
        <location>/login/errors/pagenotfound.jsp</location>
</error-page>

Here, we have configured "Error Handler" for the Http status code "404". It is the code for the resource not found. As and when we hit the URL or request for the
resource which server can not find at that time server will return Http status code "404".

2) Add a JSP to be shown when an error occurs

Whenever server sends 404 error code at that time JSP available inside folder "WebContent/login/errors/pagenotfound.jsp" will be shown to the user instead of technical message
which layman user can not understand.

In our case we have written a message "Hey requested resource not found"

3) Run and Verify

Once above steps are done just Build and deploy your application on the server. To understand the difference quickly lets look at the two snaps when we hit
URL "http://localhost:8080/student/MyLogin"

Before "Error Handlers"



After "Error Handlers"




Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics