Friday, 22 September 2017

Spring MVC Portlet in liferay

Spring MVC Portlet in Liferay 


Today we will discuss how to create Spring Portlet in Liferay.For doing this first we create a simple Portlet and then convert it into Spring Portlet.By using Spring Portlet we can handle multiple action request ,multiple resource request in seperate methods.We can have multiple action methods in single class.
Lets Start this step by step:-



Step 1:-Create liferay Plugin Project
Open eclipse click on :-
file->New->Liferay Plugin Project.
Give project name as FirstSpringMVC and finish.



Step 2:-Create MVC Portlet in project

Creating Portlet and Services using Maven in Liferay

Liferay Portlet And Services using  Maven 


Defining Maven in a single line is not possible .Maven do many things for us like resolving dependencies, create project structure, build  a project, creating war/jar etc. By using Maven you can also create portlet, theme, services without any need of sdk. Before starting this you have to install Maven and Ant in your machine.So it is highly recommended to read my previous blog  How to install Maven and How to install Ant.

Lets Start this step by step:-
Step 1:-Set up liferay-portal-maven
First download liferay-portal-maven from here according to your server version , in my case liferay-portal-maven-6.2.0-ce-rc5 and i am using liferay-portal-6.2.0-ce-rc5 server.

After downloading extract it to a folder and open it . Create a file build.username.properties inside this here username is your Computer name like in my case  build.Aditya.properties . Then paste this inside build.Aditya.properties:-

build.Aditya.properties
gpg.keyname=
gpg.passphrase=
lp.maven.repository.id=liferay
lp.maven.repository.url=${http://localhost/nexus/content/repositories/liferay-release}
lp.version.maven=6.2.0-RC5


Then Open command prompt and go to that directory(H:\Liferay6.2 practice\liferay-portal-maven-6.2.0-ce-rc5) and run ant install. This will take sometime because it install many necessary file be sure you are connected to internet.All downloaded files goes to C:\Users\Aditya\.m2.

Thursday, 21 September 2017

How To Install Ant

How to install Ant?


Ant is a Apache project.It is open source software used to compile , assemble and run java application .Before installing Ant it is compulsory to install Java as mention in my previous article How to install Maven step 1. 


Lets Start this step by step:-


Step 1:-Down load Apache Ant
First download Apache ant from Here and extract it in c drive. After extracting set the two environment variable as:-

  • ANT_Home  = C:\apache-ant-1.9.4
  • PATH = C:\apache-ant-1.9.4\bin
PATH is seperated by ;

Step 2:-Test Apache Ant

For Checking that Ant install successfully you can open command prompt(win+r then type cmd) and type ant -version this will give you detail as:-


How to install Maven

How to install Maven ?


Defining Maven in a single line is not possible .Maven do many things for us like resolving dependencies, create project structure, build  a project, creating war/jar etc. By using Maven you can also create portlet, theme, services without any need of sdk. So lets install maven.

Lets Start this step by step:-

Step 1:-Install Java(jdk)
For installing Maven first we need to download jdk from  Here and install.Then set the environment variable(User Variable).For setting environment variable in window 7 .
Click start-->right click on computer-->properties-->Advanced system setting-->Advanced-->Environment variable-->New

The two important variables are:-

1)PATH
  This environment variable is provide the path of  javac otherwise you have to copy paste your java file into bin and then compile your file from inside the bin folder of jdk. Ex-

  PATH = C:\Program Files\Java\jdk1.8.0_31\bin

2)JAVA_HOME
  This variable is need to run many other software like tomcat and maven.This takes the path till jdk. Ex-

  JAVA_HOME = C:\Program Files\Java\jdk1.8.0_31





For Checking that java install successfully you can open command prompt(win+r then type cmd) and type java -version this will give you detail as:-



Step 2:-Install Maven

  • For installing Maven first we need to download maven from here and extract in C drive .
  • Then set  M2_HOME = C:\apache-maven-3.2.3
  • Then set PATH = C:\apache-maven-3.2.3\bin
Now your path become:-

PATH = C:\Program Files\Java\jdk1.8.0_31\bin;C:\apache-maven-3.2.3\bin

Seperated by ;

Step 3:-Check Maven
For Checking that Maven install successfully you can open command prompt(win+r then type cmd) and type mvn -version this will give you detail as:-


Many To Many Relationship in Liferay Services

Today we will discuss Many To Many relationship in Liferay


As discuss earlier Liferay Service Builder create tables with service.xml. But is there any way to provide Many To Many relationship between entities. Yes there is today we will discuss  Many To Many relationship in liferay. Before Reading this blog it is highly recommended to read my previous blog on  Service Builder in Detail.

Lets Start this step by step:-

Step 1:-Create service.xml
You can create service as mention in my previous article Service Builder in Detail .

service.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 6.2.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_6_2_0.dtd">
<service-builder package-path="com.aditya" auto-namespace-tables="false">
<author>aditya.bhardwaj</author>
<namespace>emplo</namespace>
<entity name="Employee" local-service="true" remote-service="false" table="Employee">
<column name="eid" type="long" primary="true"></column>
<column name="name" type="String"></column>
<column name="address" type="String"></column>
<column name="deptid" type="Collection" entity="Department" mapping-table="Employee_department"/>
</entity>
<entity name="Department" local-service="true" remote-service="false" table="Department">
<column name="deptid" type="long" primary="true"></column>
<column name="department" type="String"></column>
<column name="eid" type="Collection" entity="Employee" mapping-table="Employee_department"/>
</entity>
</service-builder>
view rawservice.xml hosted with ❤ by GitHub

Just focus on line no 11 and 17:-

<column name="deptid" type="Collection" entity="Department" mapping-table="Employee_department"/>
<column name="eid" type="Collection" entity="Employee" mapping-table="Employee_department"/>
view rawservice.xml hosted with ❤ by GitHub

Explanation:-
Here we create a third entity(table) Employee_department Which contain the primary key of both tables.

Step 2:-Check point
Now build the service.xml and open tables.sql inside sql folder.  

tables.sql
create table Department (
deptid LONG not null primary key,
department VARCHAR(75) null
);
create table Employee (
eid LONG not null primary key,
name VARCHAR(75) null,
address VARCHAR(75) null
);
create table Employee_department (
deptid LONG not null,
eid LONG not null,
primary key (deptid, eid)
);
view rawtables.sql hosted with ❤ by GitHub

As you can see 3 tables are created two for entities and one for mapping.

Step 3:-Calling Services
Just create a doView() method and add data to the tables here we consider a scenario where one employee belong to two department.

public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
try {
Employee employee;
employee = EmployeeLocalServiceUtil.createEmployee(CounterLocalServiceUtil.increment());
employee.setAddress("Delhi");
employee.setName("Ramesh");
employee = EmployeeLocalServiceUtil.addEmployee(employee);
Department department1,department2;
department1 = DepartmentLocalServiceUtil.createDepartment(CounterLocalServiceUtil.increment());
department1.setDepartment("IT");
department1 =DepartmentLocalServiceUtil.addDepartment(department1);
department2 = DepartmentLocalServiceUtil.createDepartment(CounterLocalServiceUtil.increment());
department2.setDepartment("Research");
department2 =DepartmentLocalServiceUtil.addDepartment(department2);
DepartmentLocalServiceUtil.addEmployeeDepartments(employee.getEid(), new long[]{department1.getDeptid(),department2.getDeptid()});
}
catch (SystemException e) {
e.printStackTrace();
}
}
view rawTesting.java hosted with ❤ by GitHub

Thats it just see the tables in database:-



You can Download source code from Many To Many mapping in Liferay

Wednesday, 20 September 2017

Custom Sql in Liferay

Today we will discuss Custom Sql/Sql query in Liferay

Liferay Service Builder create basic CRUD method but there are some scenarios when we have to write SQL query. For writing native SQL query we use the concept of Custom Query in Liferay. Before Reading this blog it is highly recommended to read my previous blog on  Service Builder in Detail.

Lets Start this step by step:-

Step 1:-Create service.xml
You can create service as mention in my previous article Service Builder in Detail .

service.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 6.2.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_6_2_0.dtd">
<service-builder package-path="com.aditya">
<author>Aditya</author>
<namespace>pm</namespace>
<entity name="Student" local-service="true" remote-service="false">
<column name="sid" type="long" primary="true"></column>
<column name="name" type="String"></column>
<column name="rollno" type="int"></column>
<column name="mobileno" type="long"></column>
<order by="asc">
<order-column name="mobileno"></order-column>
</order>
<finder name="Mobile" return-type="Collection">
<finder-column name="mobileno"></finder-column>
</finder>
</entity>
</service-builder>
view rawservice.xml hosted with ❤ by GitHub

Step 2:-Create xml files for sql Query
Now create a folder custom-sql inside src and create default.xml in it.

default.xml(/WEB-INF/src/custom-sql/default.xml)
<?xml version="1.0" encoding="UTF-8"?>
<custom-sql >
<sql file="custom-sql/student-custom-sql.xml"/>
</custom-sql >
view rawdefault.xml hosted with ❤ by GitHub

here we can write our sql query but for good maintanability we create seperate file student-custom-sql.xml and include in default.xml.

student-custom-sql.xml
<?xml version="1.0" encoding="UTF-8"?>
<custom-sql>
<sql id="studentBetweenQuery" >
<![CDATA[
SELECT * from pm_student st WHERE st.sid BETWEEN ? AND ?
]]>
</sql>
</custom-sql>

  • Here we use sql id this is unique for each query.This id is used to fetch the query in method.
  • No need to write semicolon(;).
  • You can create one xml file for one entity and then include in default.xml.

Step 3:-Create xxxFinderImpl Class
Now create xxxFinderImpl class inside persistence in our case create StudentFinderImpl that extends BasePersistenceImpl and implements StudentFinder.

StudentFinderImpl.java
package com.aditya.service.persistence;
import com.aditya.model.Student;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
public class StudentFinderImpl extends BasePersistenceImpl<Student> implements StudentFinder{
}

Initally it shows error because there is no StudentFinder interface.

Run Service builder

After this error is gone and StudentFinder interface is created which is blank.


StudentFinder.java
package com.aditya.service.persistence;
public interface StudentFinder {
}
view rawStudentFinder.java hosted with ❤ by GitHub
One more class StudentFinderUtil is also created .

StudentFinderUtil.java
package com.aditya.service.persistence;
import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil;
import com.liferay.portal.kernel.util.ReferenceRegistry;
/**
* @author Aditya
*/
public class StudentFinderUtil {
public static StudentFinder getFinder() {
if (_finder == null) {
_finder = (StudentFinder)PortletBeanLocatorUtil.locate(com.aditya.service.ClpSerializer.getServletContextName(),
StudentFinder.class.getName());
ReferenceRegistry.registerReference(StudentFinderUtil.class,
"_finder");
}
return _finder;
}
public void setFinder(StudentFinder finder) {
_finder = finder;
ReferenceRegistry.registerReference(StudentFinderUtil.class, "_finder");
}
private static StudentFinder _finder;
}

Step 4:-Create method in xxxFinderImpl Class
Create method in this class and provide implementation.This is the main task where we fire query and get the result.

StudentFinderImpl.java
package com.aditya.service.persistence;
import java.util.List;
import com.aditya.model.Student;
import com.aditya.model.impl.StudentImpl;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.SQLQuery;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
import com.liferay.util.dao.orm.CustomSQLUtil;
public class StudentFinderImpl extends BasePersistenceImpl<Student> implements StudentFinder {
public List<Student> getStudentBetweenStudentId(int start, int end) {
Session session = null;
try {
session = openSession();
String sql = CustomSQLUtil.get("studentBetweenQuery");
SQLQuery queryObject = session.createSQLQuery(sql);
queryObject.setCacheable(false);
queryObject.addEntity("Student", StudentImpl.class);
QueryPos qPos = QueryPos.getInstance(queryObject);
qPos.add(start);
qPos.add(end);
return (List<Student>) queryObject.list();
//return (List<Student>) QueryUtil.list(queryObject,getDialect(),start, end);// for pagination feature
} catch (Exception e) {
e.printStackTrace();
} finally {
closeSession(session);
}
return null;
}
}

Explanation:-

1)CustomSQLUtil.get("studentBetweenQuery");
Here we fetch the sql query from xml file with the help of sql id. For different queries different id and method in this class.

2)queryObject.addEntity("Student", StudentImpl.class);
Here we add our entity to queryObject. If sql query belong to multiple tables than we have to add all the entities to query object.

3)return (List<Student>) queryObject.list();
Here we return List<Student> because our query return all records belong to Student table but if our query contain two or more table like in case of join then we return List<Object[]>.

Step 5:-Expose method to LocalServiceUtil Class
We can't directly call method from StudentFinderImpl or StudentFinderUtil . All method are call from xxxLocalServiceUtil
Class so first we create method in xxxLocalServiceImpl 

StudentLocalServiceImpl.java
public class StudentLocalServiceImpl extends StudentLocalServiceBaseImpl {
public List<Student> getStudentBetweenStudentId(int start, int end) {
return StudentFinderUtil.getStudentBetweenStudentId(start, end);
}
}

Here this show error because StudentFinderUtil has not containgetStudentBetweenStudentId(start, end).

Run Service builder

Now error is gone coz this will create method in StudentFinder interface and StudentFinderUtil  Class also.Now StudentFinder and StudentFinderUtil become:-

StudentFinder.java
public interface StudentFinder {
public java.util.List<com.aditya.model.Student> getStudentBetweenStudentId(
int start, int end);
}
view rawStudentFinder.java hosted with ❤ by GitHub

StudentFinderUtil.java
public class StudentFinderUtil {
public static java.util.List<com.aditya.model.Student> getStudentBetweenStudentId(
int start, int end) {
return getFinder().getStudentBetweenStudentId(start, end);
}
public static StudentFinder getFinder() {
if (_finder == null) {
_finder = (StudentFinder)PortletBeanLocatorUtil.locate(com.aditya.service.ClpSerializer.getServletContextName(),
StudentFinder.class.getName());
ReferenceRegistry.registerReference(StudentFinderUtil.class,
"_finder");
}
return _finder;
}
public void setFinder(StudentFinder finder) {
_finder = finder;
ReferenceRegistry.registerReference(StudentFinderUtil.class, "_finder");
}
private static StudentFinder _finder;
}

Now Both Contain  getStudentBetweenStudentId(int start, int end).

Note:-
Normally we first create method in interface then provide implementation in Impl class but in Liferay we provide implementation in xxxLocalServiceImpl first and Run service builder which create method in Inteface.

Step 6:-Call method from LocalServiceUtil Class
Now from your doView() or from jsp call your method as:-

public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
try {
System.out.println("Student==>"+StudentLocalServiceUtil.getStudentBetweenStudentId(101, 104).size());
}
catch (SystemException e) {
e.printStackTrace();
}
super.doView(renderRequest, renderResponse);
}
view rawTest.java hosted with ❤ by GitHub

You can download source code from Custom Sql in Liferay

 

Copyright @ 2013 Test.