Developing Liferay application with Service Builder | 1 Developing Liferay application with Service Builder By Pankajsharma contact
Developing Liferay application with Service Builder | 1
Developing Liferay
application with
Service Builder
By Pankajsharma
contact
Developing Liferay application with Service Builder | 2
Table of Content:
I. Create Spring MVC Portlet and Service Builder. II. Create Liferay-6.1.1 (Rest-Json) Web Services. III. Calling Portlet as a Web Service using SOAP API. IV. Custom-SQL Query in Liferay-6.1.1.ga2
Developing Liferay application with Service Builder | 3
Create Spring MVC Portlet and Service Builder
1. Create new Liferay Spring MVC Click on File Menu | New | Liferay Project.
2. Given the Project Portlet name is SampleSpring-portlet this Portlet name specified into
screenshot given below.
Developing Liferay application with Service Builder | 4
3. This step click on next then Finish Button.
Developing Liferay application with Service Builder | 5
4. Now we need to create Service.xml file, Right click on WEB-INF folder, New | Liferay
Service Builder.
Developing Liferay application with Service Builder | 6
5. Now we have created Service.xm file, In This file we have specified to various kind of
fields. And we have to take primary Key :employeeId,Entity name: Employee, And now
we have taken different kind of fields as:
And we have specified ascending Order during the insert employee details into Database table,
ascending order is display by employee First name Latter.
<!-- Audit fields -->
<column name="firstName" type="String" />
<column name="lastName" type="String" />
<column name="eMail" type="String" />
<column name="mobileNo" type="String" />
Developing Liferay application with Service Builder | 7
And In this file specified Package: com.attuneww, auther name and namespace.
Service.xml:
<!-- Order -->
<order by="asc">
<order-column name="firstName" />
</order>
<service-builder package-path="com.attuneww">
<author>PankajSharma</author>
<namespace>AttuneWW</namespace>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service
Builder 6.1.0//EN" "http://www.liferay.com/dtd/liferay-service-
builder_6_1_0.dtd">
<service-builder package-path="com.attuneww">
<author>PankajSharma</author>
<namespace>AttuneWW</namespace>
<entity name="Employee" local-service="true" remote-
service="true">
<!-- PK fields -->
<column name="employeeId" type="long" primary="true" id-
type="identity"/>
<!-- Audit fields -->
<column name="firstName" type="String" />
<column name="lastName" type="String" />
<column name="eMail" type="String" />
<column name="mobileNo" type="String" />
<!-- Order -->
<order by="asc">
<order-column name="firstName" />
</order>
<!-- Finder methods -->
<finder name="firstNameCollection" return-type="Collection">
<finder-column name="firstName" />
</finder>
</entity>
</service-builder>
Developing Liferay application with Service Builder | 8
6. Now we need to build service builder, Right Click on Project portlet |Liferay |Build
Services. After then generate various types of services. We can see that all services
hierarchy into snippet shot given below.
Developing Liferay application with Service Builder | 9
7. Now create Controller Action Class is EmployeeController,This Class is directory
:/SampleSpring-portlet/docroot/WEB-
INF/src/com/attuneww/controller/EmployeeController.java.
8. Now create to sample-spring-mvc-portlet.xml file,this file directory is :SampleSpring-
portlet/docroot/WEB-INF/sample-spring-mvc-portlet.xml and we have to specified of
Action Controller Action Class: EmployeeController.
<bean class="com.attuneww.controller.EmployeeController" />
Developing Liferay application with Service Builder | 10
sample-spring-mvc-portlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-
3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:annotation-config />
<bean
class="org.springframework.web.portlet.mvc.annotation.DefaultAnn
otationHandlerMapping" />
<bean class="com.attuneww.controller.EmployeeController" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceView
Resolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.InternalResourceView
" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="order" value="1" />
</bean>
</beans>
Developing Liferay application with Service Builder | 11
9. Create to portlet.xml file and directory : SampleSpring-portlet/docroot/WEB-
INF/portlet.xml, In this file we need to replace Portlet- class tag by
<portlet-
class>org.springframework.web.portlet.DispatcherPortlet</por
tlet-class>
From it is by default generate tag.
Developing Liferay application with Service Builder | 12
portlet.xml :
Developing Liferay application with Service Builder | 13
<?xml version="1.0"?>
<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-
app_2_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-
app_2_0.xsd http://java.sun.com/xml/ns/portlet/portlet-
app_2_0.xsd" version="2.0">
<portlet>
<portlet-name>SampleSpring</portlet-name>
<display-name>SampleSpring</display-name>
<portlet-
class>org.springframework.web.portlet.DispatcherPortlet</portlet-
class>
<init-param>
name>contextConfigLocation</name>
<value>/WEB-INF/sample-spring-mvc-portlet.xml</value>
</init-param>
<init-param>
<name>view-jsp</name>
<value>/view.jsp</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
</supports>
<portlet-info>
<title>SampleSpring</title>
<short-title>SampleSpring</short-title>
<keywords>SampleSpring</keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
<security-role-ref>
<role-name>guest</role-name>
</security-role-ref>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
Developing Liferay application with Service Builder | 14
10. Now we have need to Create web.xml file,it is directory SampleSpring-
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>
</portlet-app>
Developing Liferay application with Service Builder | 15
portlet/docroot/WEB-INF/web.xml ,and we need to add some extra tags are given
below:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SampleSpring-portlet</display-name>
<servlet>
<servlet-name>view-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>view-servlet</servlet-name>
<url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>
<jsp-config>
<taglib>
<taglib-uri>http://java.sun.com/portlet_2_0</taglib-uri>
<taglib-location>
/WEB-INF/tld/liferay-portlet.tld
</taglib-location>
</taglib>
<servlet>
<servlet-name>view-servlet</servlet-name>
<servlet-
class>org.springframework.web.servlet.ViewRendererServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>view-servlet</servlet-name>
<url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>
Developing Liferay application with Service Builder | 16
11. Create of liferay-plugin-package.properties file , we use to add of different types of jars
by this file. This file directory is: SampleSpring-portlet/docroot/WEB-INF/liferay-
plugin-package.properties.These all jars are copy into this file.
liferay-plugin-package.properties:
<taglib>
<taglib-uri>http://liferay.com/tld/aui</taglib-uri>
<taglib-location>/WEB-INF/tld/aui.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
Developing Liferay application with Service Builder | 17
12. Now this file by default generate after Build Service, If you have got it some exception to
related version build.number=8, then during deploy Liferay Portlet, while you can replace
build number as like 8.
13. Create of jsp page and it is given name: view.jsp ,it is directory : SampleSpring-
portlet/docroot/WEB-INF/jsp/view.jsp.
view.jsp:
name=SampleSpring
module-group-id=liferay
module-incremental-version=1
tags=
short-description=
change-log=
page-url=http://www.liferay.com
author=Liferay, Inc.
licenses=LGPL
liferay-versions=6.1.1
portal-dependency-jars=\
commons-beanutils.jar,\
commons-collections.jar,\
commons-fileupload.jar,\
commons-io.jar,\
commons-lang.jar,\
jstl-api.jar,\
jstl-impl.jar,\
spring-aop.jar,\
spring-asm.jar,\
spring-beans.jar,\
spring-context-support.jar,\
spring-context.jar,\
spring-core.jar,\
spring-expression.jar,\
spring-jdbc.jar,\
spring-transaction.jar,\
spring-web-portlet.jar,\
spring-web-servlet.jar,\
spring-web.jar
Developing Liferay application with Service Builder | 18
<%@page import="com.liferay.portal.kernel.util.ListUtil"%>
<%@page import="com.attuneww.service.EmployeeLocalServiceUtil"%>
<%@page import="com.attuneww.model.Employee"%>
<%@page import="java.util.List"%>
<%@taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui"%>
<%@taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%>
<%List<Employee>
employee=EmployeeLocalServiceUtil.getEmployees(0,EmployeeLocalServiceUtil.ge
tEmployeesCount());
String update=null;
Employee employ=null;
String firstName="",lastName="",email="",mobileNo="";
if(request.getParameter("resourcePrimKey")!=null){
update=request.getParameter("resourcePrimKey");
employ=EmployeeLocalServiceUtil.getEmployee(Long.valueOf(request.getParamete
r("resourcePrimKey")));
firstName=employ.getFirstName();
lastName=employ.getLastName();
email=employ.getEMail();
mobileNo=employ.getMobileNo();
}%>
<h1>Please Enter Employee Details</h1>
<portlet:defineObjects/>
<portlet:renderURL var="renderOneMethodURL">
<portlet:param name="action" value="renderOne"></portlet:param>
</portlet:renderURL>
<portlet:actionURL var="actionOneMethodURL">
<portlet:param name="action" value="actionOne"></portlet:param>
</portlet:actionURL>
<aui:form action="${actionOneMethodURL}" method="post">
<aui:input name="employeeId" value="<%=update %>" type="hidden"></aui:input>
<aui:input type="text" label="First Name:" name="firstName"
value="<%=firstName %>">
<aui:validator name="required"/>
<aui:validator name="alpha"/>
</aui:input>
Developing Liferay application with Service Builder | 19
<aui:input type="text" label="Last Name:" name="lastName"
value="<%=lastName %>">
<aui:validator name="alpha"/>
</aui:input>
<aui:input type="text" label="Email:" name="email" value="<%=email %>">
<aui:validator name="email"/>
</aui:input>
<aui:input type="text" label="Mobile Number:" name="mobileNo"
value="<%=mobileNo %>">
<aui:validator name="digits"></aui:validator>
<aui:validator name="minLength">8</aui:validator>
<aui:validator name="maxLength">10</aui:validator>
</aui:input>
<%if(update!=null) {%>
<input type="submit" name="update" value="Update">
<%}else{ %>
<input type="submit" name="save" value="Save">
<%} %>
</aui:form>
<liferay-ui:search-container emptyResultsMessage="there-are-no-User"
delta="5">
<liferay-ui:search-container-results>
<%results = ListUtil.subList(employee,
searchContainer.getStart(),
searchContainer.getEnd());
total = employee.size();
pageContext.setAttribute("results", results);
pageContext.setAttribute("total", total);
%></liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="com.attuneww.model.Employee"
keyProperty="employeeId" modelVar="users">
<liferay-ui:search-container-column-text name="FirstName"
value="<%=users.getFirstName()%>" />
<liferay-ui:search-container-column-text name="lastName"
value="<%=users.getLastName()%>" />
<liferay-ui:search-container-column-text name="email"
value="<%=users.getEMail()%>" />
<liferay-ui:search-container-column-text name="mobileNo"
value="<%=users.getMobileNo()%>" />
<liferay-ui:search-container-column-jsp
path="/WEB-INF/jsp/actionkey.jsp" align="right" />
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
Developing Liferay application with Service Builder | 20
14. In this code, we have need to get all Employee List, then we have taken if condition to
check resourcePrimKey not equal null, then you can get all parameters with in help of
resourcePrimKey.
15. In this code we have specified various kinds of fields with in Input validation tag.
<%List<Employee>
employee=EmployeeLocalServiceUtil.getEmployees(0,EmployeeLocalSer
viceUtil.getEmployeesCount());
String update=null;
Employee employ=null;
String firstName="",lastName="",email="",mobileNo="";
if(request.getParameter("resourcePrimKey")!=null){
update=request.getParameter("resourcePrimKey");
employ=EmployeeLocalServiceUtil.getEmployee(Long.valueOf(request.
getParameter("resourcePrimKey")));
firstName=employ.getFirstName();
lastName=employ.getLastName();
email=employ.getEMail();
mobileNo=employ.getMobileNo();
}%>
<h1>Please Enter Employee Details</h1>
<portlet:defineObjects/>
<portlet:actionURL var="actionOneMethodURL">
<portlet:param name="action" value="actionOne"></portlet:param>
</portlet:actionURL>
<aui:form action="${actionOneMethodURL}" method="post">
<aui:input name="employeeId" value="<%=update %>"
type="hidden"></aui:input>
<aui:input type="text" label="First Name:" name="firstName"
value="<%=firstName %>">
<aui:validator name="required"/>
<aui:validator name="alpha"/>
</aui:input>
<aui:input type="text" label="Last Name:" name="lastName"
value="<%=lastName %>">
<aui:validator name="alpha"/>
</aui:input>
<aui:input type="text" label="Email:" name="email" value="<%=email
%>">
<aui:validator name="email"/>
</aui:input>
<aui:input type="text" label="Mobile Number:" name="mobileNo"
value="<%=mobileNo %>">
Developing Liferay application with Service Builder | 21
16. Now in Jsp we have form when we submit form it will match Actionurl parameter in
Controller class action parameters value actionOne, Mapping with action value. Then call
@ActionMapping(params = "action=actionOne") actionOneMethod and call
actionOneMethod(ActionRequest request, ActionResponse response) method.
<aui:validator name="digits"></aui:validator>
<aui:validator name="minLength">8</aui:validator>
<aui:validator name="maxLength">10</aui:validator>
</aui:input>
<%if(update!=null) {%>
<input type="submit" name="update" value="Update">
<%}else{ %>
<input type="submit" name="save" value="Save">
<%} %>
</aui:form>
Developing Liferay application with Service Builder | 22
package com.attuneww.controller;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.attuneww.controller.EmployeeController;
import com.attuneww.model.Employee;
import com.attuneww.model.impl.EmployeeImpl;
import com.attuneww.service.EmployeeLocalServiceUtil;
@Controller(value = "EmployeeController")
@RequestMapping("VIEW")
public class EmployeeController {
private static Log log = LogFactoryUtil.getLog(EmployeeController.class);
@RenderMapping
public String handleRenderRequest(RenderRequest request,RenderResponse
response,Model model){
return "view";
}@ActionMapping(params = "action=actionOne")
public void actionOneMethod(ActionRequest request, ActionResponse response)
throws SystemException, NumberFormatException, PortalException {
Developing Liferay application with Service Builder | 23
So it will check whether this is coming for Add, Update or Delete and accordingly it will do add
or Update or Delete Operation
Then we have actionkey.jsp file which is as follows.
String employeeId= request.getParameter("employeeId");
String del=request.getParameter("resourcePrimKeyDelete");
System.out.println("Test for delete update>>>"+del+"update"+employeeId);
String firstName=request.getParameter("firstName");
String lastName=request.getParameter("lastName");
String email=request.getParameter("email");
String mobileNo=request.getParameter("mobileNo");
if(del==null){
Employee emp=new EmployeeImpl();
emp.setFirstName(firstName);
emp.setLastName(lastName);
emp.setEMail(email);
emp.setMobileNo(mobileNo);
if(employeeId.equals("")){
emp.setEmployeeId(CounterLocalServiceUtil.increment());
EmployeeLocalServiceUtil.addEmployee(emp);
}else{
emp.setEmployeeId(Long.valueOf(employeeId));
EmployeeLocalServiceUtil.updateEmployee(emp);
}}
if(del!=null){
EmployeeLocalServiceUtil.deleteEmployee(Long.valueOf(del));
}}}
Developing Liferay application with Service Builder | 24
<%@page import="com.attuneww.model.Employee"%>
<%@page import="com.liferay.portal.kernel.util.WebKeys"%>
<%@page import="com.liferay.portal.kernel.dao.search.ResultRow"%>
<%@taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%ResultRow row =
(ResultRow)request.getAttribute(WebKeys.SEARCH_CONTAINER_RESULT_ROW);
Employee newUser = (Employee)row.getObject();
String name = Employee.class.getName();
String primKey = String.valueOf(newUser.getEmployeeId());
String userId= String.valueOf(newUser.getEmployeeId());
System.out.println("primKey>>"+primKey);
%><liferay-ui:icon-menu>
<portlet:renderURL var="editURL">
<portlet:param name="jspPage" value="/WEB-INF/jsp/view.jsp"></portlet:param>
<portlet:param name="resourcePrimKey" value="<%=primKey %>" />
</portlet:renderURL>
Developing Liferay application with Service Builder | 25
17. This is Action Key files which will have Edit and Delete Action.
18. When we click on Edit it will add resourcePrimKey as parameter and redirecting to
view.jsp so in view when we get this it will go for update.
<liferay-ui:icon image="edit" message="Update" url="<%=editURL.toString()
%>" />
<portlet:actionURL var="actionOneMethodURL">
<portlet:param name="action" value="actionOne"></portlet:param>
<portlet:param name="resourcePrimKeyDelete" value="<%=primKey %>" />
</portlet:actionURL>
<liferay-ui:icon-delete url="<%=actionOneMethodURL.toString() %>" />
</liferay-ui:icon-menu>
if(request.getParameter("resourcePrimKey")!=null){
update=request.getParameter("resourcePrimKey");
employ=EmployeeLocalServiceUtil.getEmployee(Long.valueOf(request.getPa
rameter("resourcePrimKey")));
firstName=employ.getFirstName();
lastName=employ.getLastName();
email=employ.getEMail();
mobileNo=employ.getMobileNo();
Developing Liferay application with Service Builder | 26
19. For Delete again match with actionOne, Mapping with action value. Then call
@ActionMapping(params = "action=actionOne") method.
20. This way Portlet will work now.
21. Now we have to import liferay Project Portlet with Liferay Portal. We can see crud
operations as add, update and delete with in browser. And we have following snippet shot
given below.
Developing Liferay application with Service Builder | 27
Liferay-6.1.1 (REST-JSON) Web Services
1. Create New Liferay Project JSONWebServices. Right Click on new |Liferay Project and
Given name of Rest-json Portlet is: Employee-RestWebServices-portlet.
2. Now click on next Select Liferay MVC then Finish.
Developing Liferay application with Service Builder | 28
3. Now Right Click on WEB-INF folder Select New Liferey Service Builder, it is directory of
service builder file: Employee-RestWebServices-portlet/docroot/WEB-INF/service.xml.
4. Now we can see to appear a popup window and Insert Details and Click On Finish.
5. In this file to create table column values were auto generated by Build Service within help
eclipse Editor. Now write own table columns name replace/rewrite Table field in File.
6. We have to specified entity name :EmployRestfull.and create an primary key is
employeeId with id(long) and remote service:true.
7. Now create an Employee attributes various kinds of fields given below.
8. Now write finder Tag for Search Content. A field which you want to Search.
Developing Liferay application with Service Builder | 29
Service.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder
6.1.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_6_1_0.dtd">
<service-builder package-path="com.attuneww">
<author>pankaj</author>
<namespace>JSONWebservices</namespace>
<entity name="EmployRestfull" local-service="true" remote-service="true">
<!-- PK fields -->
<column name="employeeId" type="long" primary="true" id-type="identity"/>
<!-- Audit fields -->
<column name="name" type="String" />
<column name="eMail" type="String" />
<column name="mobileNo" type="String" />
<column name="companyname" type="String" />
Developing Liferay application with Service Builder | 30
9. Now, right click on Service.xml file and Liferay -> Build Services.
10. It will generate portlet service packages under docroot/WEB-INF/src folder.
<!-- Order -->
<order by="asc">
<order-column name="employeeId" />
</order>
<!-- Finder methods -->
<finder name="EmplyeeName" return-type="EmployRestfull">
<finder-column name="name" />
</finder>
</entity>
</service-builder>
Developing Liferay application with Service Builder | 31
11. Now, right click on build.xml file |Liferay|SDK and run the build-service task.
12. Now Implement services Edit in com.attuneww.service.impl.EmployRestfullServiceImpl.
Here we are getting EmployRestfull Object using EmployRestfull Id (employeeId). This
method returns EmployRestfull Object. In Liferay any Object automatically sterilizes and
produces as JSON data.
package com.attuneww.service.impl;
package com.attuneww.service.impl;
import com.attuneww.model.EmployRestfull;
import com.attuneww.service.EmployRestfullLocalServiceUtil;
import com.attuneww.service.base.EmployRestfullServiceBaseImpl;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
public class EmployRestfullServiceImpl extends
EmployRestfullServiceBaseImpl {
public EmployRestfull getEmployRestfull(long employeeId) throws
PortalException,SystemException
{ return EmployRestfullLocalServiceUtil.getEmployRestfull(employeeId);
}}
Developing Liferay application with Service Builder | 32
13. Add the following <servlet> and <servlet-mapping> Entries to portlet’s web.xml file.
<filter>
<filter-name>Secure JSON Web Service Servlet Filter</filter-name>
<filter-
class>com.liferay.portal.kernel.servlet.PortalClassLoaderFilter</fi
lter-class>
<init-param>
<param-name>filter-class</param-name>
<param-
value>com.liferay.portal.servlet.filters.secure.SecureFilter</param
-value>
</init-param>
<init-param>
<param-name>basic_auth</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>portal_property_prefix</param-name>
<param-value>jsonws.servlet.</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Secure JSON Web Service Servlet Filter</filter-name>
<url-pattern>/api/jsonws/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>JSON Web Service Servlet</servlet-name>
Developing Liferay application with Service Builder | 33
14. Now, again run the build-service task and make sure that build successful.
15. Once this completed, start the server if not started previously.
16. Then Run Employee-RestWebServices-portlet|compile and Employee-RestWebServices-
portlet|deploy.
17. Now make sure that build successful, and now open Liferay console at
http://localhost:8080 in your browser.
18. Login as [email protected] password is test.
19. Now click on Add-|more-|sample , then type portlet name you can see to your portlet
project inside sample folder.
class>com.liferay.portal.kernel.servlet.PortalClassLoaderServlet</ser
vlet-class>
<init-param>
<param-name>servlet-class</param-name>
<param-
value>com.liferay.portal.jsonwebservice.JSONWebServiceServlet</param-
value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JSON Web Service Servlet</servlet-name>
<url-pattern>/api/jsonws/*</url-pattern>
</servlet-mapping>
Developing Liferay application with Service Builder | 34
20. Make sure that plugins appear, this may confirm that plugins deployed properly.
21. Now open http://localhost:8080/api/jsonws this URL in browser. It will show JSON web
services API page.
Developing Liferay application with Service Builder | 35
22. Now to access your json web services enter the following url –
http://localhost:8080/<<portlet-context-name>>/api/jsonws
portlet-context-name: portlet project name.
http://localhost:8080/Employee-RestWebServices-portlet/api/jsonws
After then we can see that is generate get method name is getEmployRestfull left corner side
portlet.
Developing Liferay application with Service Builder | 36
Note: service-method-name is generated from the service’s method name by converting its
camel case to lower case and using dashes (-) to separate words. We can see that into given
above snippet as get-employ-restfull.
23. Now click on This Method as get-employ-restfull, we got it new form.
Developing Liferay application with Service Builder | 37
24. It will show One text field Id, now enter value in Box (I previously added One value direct
in database employeeId=1, name=pankaj, [email protected], mobileNo=7895461231,comapnayname=attuneww.)
Developing Liferay application with Service Builder | 38
25. When we enter 1 in employeeid in textbox it will show result to json format in result tab.
Developing Liferay application with Service Builder | 39
26. When we click on URL Example tab it will show URL to access this result. And any client
can access result directly using this link.
http://localhost:8080/Employee-RestWebServices-portlet/api/secure/jsonws/employrestfull/get-employ-restfull/employee-id/1?p_auth=M9j0rD6G
Developing Liferay application with Service Builder | 40
27. Now, write this URL in Browser. You will get Query result in Page. And we can see that
employee result in json format.
Calling Portlet (Liferay-6.1.1ga2) as a Web Service using SOAP API
1. Create New Liferay Project In eclipse SOAPWebServices.Right Click select |New|Liferay
Project then we see that a one popup window and enter following details as portlet
Project name.
Developing Liferay application with Service Builder | 41
2. Click on Next and Select Liferay MVC.
Developing Liferay application with Service Builder | 42
3. Click Finish and Project will appear in Project Explorer.
4. Now Right Click on WEB-INF Folder and
5. Select |New |Liferey Service Builder.A popup will show and Insert Details and Click on
Finish.
Developing Liferay application with Service Builder | 43
6. Service.xml file will be seen under WEB-INF folder. And It's directory this file
SOAPWebServices-portlet/docroot/WEB-INF/service.xml. Now open file in Editor.
7. Table column values were auto generated by eclipse. Now write own table column name
replace/rewrite Table field in File.
8. Create an Employee entity with id (long) and name (String),email(String),
mobileno(String),companyname(String)) attributes.
9. Now write finder Tag for Search Content. A field which you want to Search.
Developing Liferay application with Service Builder | 44
Service.xml:
<service-builder package-path="com.attune">
<author>attune</author>
<namespace>attune</namespace>
<entity name="Employee" local-service="true" remote-service="true">
<!-- PK fields -->
<column name="empid" type="long" primary="true" />
<!-- Audit fields -->
<column name="name" type="String" />
<column name="eMail" type="String" />
<column name="mobileNo" type="String" />
<column name="companyname" type="String" />
<!-- Order -->
<order by="asc">
<order-column name="empid" />
</order>
<!-- Finder methods -->
<finder name="EmplyeeName" return-type="Collection">
<finder-column name="name" />
</finder>
</entity>
</service-builder>
Developing Liferay application with Service Builder | 45
10. Now, Right click on Service.xml file and New| Liferay |Build Services.
11. It will generate portlet service packages under docroot/WEB-INF/src folder.
Developing Liferay application with Service Builder | 46
12. Now, right click on build.xml file and run the New|Liferay|SDK| build-service task. And
again need to WSDD,New|Liferay|Build WSDD.it's mandatory to build WSDD.
13. Now Implement services Edit in com.attune.service.impl.EmployeeLocalServiceImpl Add
implementation for CURD and finder method.
Developing Liferay application with Service Builder | 47
EmployeeLocalServiceImpl.java
14. Now, again run the build-service task and make sure that build successful.
15. Similarly Edit com.attune.service.impl.EmployeeServiceImpl.
package com.attune.service.impl;
import java.util.List;
import com.attune.NoSuchEmployeeException;
import com.attune.model.Employee;
import com.attune.service.base.EmployeeLocalServiceBaseImpl;
import com.attune.service.persistence.EmployeeUtil;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.exception.SystemException;
public class EmployeeLocalServiceImpl extends EmployeeLocalServiceBaseImpl {
public Employee create(Employee model) throws SystemException{
long empid = CounterLocalServiceUtil.increment(Employee.class.getName());
model.setEmpid(empid);
Employee newModel = EmployeeUtil.create(model.getEmpid());
newModel.setName(model.getName());
newModel.setCompanyname(model.getCompanyname());
newModel.setEMail(model.getCompanyname());
newModel.setMobileNo(model.getMobileNo());
EmployeeUtil.update(newModel,true);
//EmployeeUtil.update(newModel);
return newModel;
}
public Employee update(Employee model) throws NoSuchEmployeeException,
SystemException
{
Employee newModel = EmployeeUtil.findByPrimaryKey(model.getEmpid());
newModel.setName(model.getName());
newModel.setCompanyname(model.getCompanyname());
newModel.setEMail(model.getCompanyname());
newModel.setMobileNo(model.getMobileNo());
EmployeeUtil.update(newModel,true);
return newModel;}
public List<Employee> findByEmplyeeName(String name) throws SystemException
{ return EmployeeUtil.findByEmplyeeName(name);
}public Employee remove(long empid) throws NoSuchEmployeeException,
SystemException
{return EmployeeUtil.remove(empid);
}}
Developing Liferay application with Service Builder | 48
EmployeeServiceImpl.java
16. Now, again run the build-service task and make sure that build successful.
17. Once this completed, start the server if not started previously.
18. Then Run SOAPWebServices|compile and SOAPWebServices|deploy.
package com.attune.service.impl;
import java.util.List;
import com.attune.NoSuchEmployeeException;
import com.attune.model.Employee;
import com.attune.service.EmployeeLocalServiceUtil;
import com.attune.service.base.EmployeeServiceBaseImpl;
import com.liferay.portal.kernel.exception.SystemException;
public class EmployeeServiceImpl extends EmployeeServiceBaseImpl {
public Employee create(Employee model) throws SystemException{
return EmployeeLocalServiceUtil.create(model);
}public Employee update(Employee model) throws NoSuchEmployeeException,
SystemException
{return EmployeeLocalServiceUtil.update(model);
}public List<Employee> findByEmplyeeName(String name) throws SystemException
{return EmployeeLocalServiceUtil.findByEmplyeeName(name);}
public Employee remove(long empid) throws NoSuchEmployeeException,
SystemException
{return EmployeeLocalServiceUtil.remove(empid);
}}
Developing Liferay application with Service Builder | 49
19. Now make sure that build successful, and now open Liferay console at
http://localhost:8080 in your browser.
20. Login as [email protected] password is test.
21. Now click on Add->more|sample and we can see that your portlet under sample all portlet
hierarchy, you already have added into sample by click on add.
Developing Liferay application with Service Builder | 50
22. Make sure that plugins appear, this may confirm that plugins deployed properly.
23. Now, open http://127.0.0.1:8080/WebServices-
Developing Liferay application with Service Builder | 51
portlet/api/axis/Plugin_SOAPWS_EmployeeService?wsdl in browser. In this url
WebServices-portlate is Portlate name, attune is Name Space which we were declare
while we creating Service.xml, EmployeeServices is entityname of service.xml.
24. Make sure that this url is open up in browser, because this completes plugin service
creation. Then we can see xmlns:wsdl file.
Create Web Service Client
1. Now we need to test our webservice. For that we need to have another tomcat runtime as
our Liferay tomcat 6 runtime eclipse plugin doesn't support building webservices. Also we
need to make sure that the tomcat runtime and liferay run on different ports. I used the
ports 8006, AJp-port: 8010 and http:8081 of my tomcat runtime.
2. Create One dynamic web project.And make sure that you select normal tomcat instead of
liferay tomcat while configuring the project. Right click select|New|other|Web|Next.We
Developing Liferay application with Service Builder | 52
can see that and enter Dynamic Web project name.
Developing Liferay application with Service Builder | 53
Developing Liferay application with Service Builder | 54
3. Now click on New Runtime. And configure Apache Webserver. Apache tomcat Server
configuration before create Dynamic web project.
Developing Liferay application with Service Builder | 55
4. Now we need to create us Service Client, Right click select|New|other|Web Services|Web
Service Client|Next.
Developing Liferay application with Service Builder | 56
5. After Next click, we can see that new popup window, we need to copy of Service URL
as:http://localhost:8080/SOAPWebServices-
portlet/api/axis/Plugin_SOAPWS_EmployeeService?wsdl and Make sure that scroll should
be dragged to the top. You will find scroll on extreme left of the window, we have need to
set server configuration, then click on server runtime:Tomcatv7.0Server,You will find
scroll on extreme left of the window, we can see that all things given following snippet
shot below and Click Finish.
Developing Liferay application with Service Builder | 57
6. Click Next on this and next screen. Then click on "Start server" to start the tomcat
runtime. Then click Finish.
Developing Liferay application with Service Builder | 58
Developing Liferay application with Service Builder | 59
Developing Liferay application with Service Builder | 60
7. Eclipse will then deploy the client and open up a screen to test your webservice.
Developing Liferay application with Service Builder | 61
8. We will test create method first. We will provide the
primaryKey=0,name=Test,[email protected],mobileno=999999999,companyname=Tes
t and id=1 and click invoke.
Developing Liferay application with Service Builder | 62
9. In the results section we can see that the employee entity has been created with the
id=1.
Developing Liferay application with Service Builder | 63
10. Now invoke findByEmplyeeName and provide name=pankaj. The result will show the
reference of the entity object returned by the webservice. (It will return the object not
the exact value.
11. We want add employee record into database, then we have used to created employee
method by from servicesImpl class.
Developing Liferay application with Service Builder | 64
12. We can see that which you have to already added employee record into your database
table given following snippet shot below.
Developing Liferay application with Service Builder | 65
Custom Query in Liferay 6.1.1
The following will explain how to work with custom-sql in liferay 6.1.1
1. Create new Liferay MVC Click on File Menu | news |Liferay Project.
2. Given the Project Portlet name is LiferayCustomQuery this Portlet name specified into
screenshot given below.
Developing Liferay application with Service Builder | 66
3. This step click on next then Finish button.
4. N
o
w
w
e
n
e
e
d
t
o
c
r
e
a
t
e
Service.xml file, Right click on WEB-INF folder,New | Liferay |Service Builder.
Developing Liferay application with Service Builder | 67
5. In a service.xml (Under docroot/WEB-INF) add the following lines.
Developing Liferay application with Service Builder | 68
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder
6.1.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_6_1_0.dtd">
<service-builder package-path="com.attune">
<author>pankaj</author>
<namespace>LiferayCustom</namespace>
<entity name="Books" local-service="true" remote-service="true">
<!-- PK fields -->
<column name="bookId" type="long" primary="true" />
<!-- Audit fields
<column name="title" type="String" />
<column name="author" type="String"/>
<!-- Order -->
<order by="asc">
<order-column name="bookId" />
</order>
<!-- Finder methods -->
<finder name="Author" return-type="Collection">
<finder-column name="author" />
</finder>
</entity>
</service-builder>
Developing Liferay application with Service Builder | 69
6. Build the service (you can use ant build-service or directly from IDE)
7. We can that all service class hierarchy into Package Explorer.
8. Create custom-sql folder under src folder
9. Create default.xml file under custom-sql and add the following lines of code.
<?xml version="1.0" encoding="UTF-8"?>
<custom-sql >
<sql file="custom-sql/book-custom-sql.xml"/>
</custom-sql >
Developing Liferay application with Service Builder | 70
10. Create book.xml file under the same custom-sql folder mentioned in step 4 and add the
following lines of code.
11. Create the file BooksFinderImpl.java under persistence (persistence will get after the first
time build service) and add the following lines of code.
<?xml version="1.0" encoding="UTF-8"?>
<custom-sql>
<sql id="findBooks">
<![CDATA[SELECT * FROM LiferayCustom_Books WHERE
(LiferayCustom_Books.title like ?)]]>
</sql>
</custom-sql>
Developing Liferay application with Service Builder | 71
package com.attune.service.persistence;
import java.util.List;
import com.attune.model.impl.BooksImpl;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.SQLQuery;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
import com.liferay.util.dao.orm.CustomSQLUtil;
public class BooksFinderImpl extends BasePersistenceImpl implements BooksFinder {
public List findBooks(String name) throws SystemException {
Session session = null;
try {
session = openSession();
String sql = CustomSQLUtil.get(FIND_BOOKS); SQLQuery query = session.createSQLQuery(sql);
query.addEntity("Book", BooksImpl.class);
QueryPos qPos = QueryPos.getInstance(query); qPos.add(name);
return (List)query.list();
}catch (Exception e) {
}
return null;
}
public static String FIND_BOOKS = "findBooks";
}
Developing Liferay application with Service Builder | 72
12. Add the following lines of code under BooksLocalServiceImpl.
package com.attune.service.impl;
import java.rmi.RemoteException;
import java.util.List;
import com.attune.model.Books;
import com.attune.service.base.BooksLocalServiceBaseImpl;
import com.attune.service.persistence.BooksFinderUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
public class BooksLocalServiceImpl extends BooksLocalServiceBaseImpl {
public List<Books> findBook(String name) throws PortalException,
SystemException, RemoteException {
return BooksFinderUtil.findBooks("%" + name + "%"); }
}
Developing Liferay application with Service Builder | 73
13. Again run "ant build-service" again passing the service.xml file as parameter. This will
update the corresponding interface with the new method defined.
14. Now go ahead and call BookLocalServiceImpl method from your jsp or java normally how
you call other methods. For testing purpose add the following lines of code in Portlet
under doView() method.
15. Now we need to search form to create as View.jsp ,which is perform to operate to search
container to use to find out value of book records.
<%@page import="com.sun.org.apache.xerces.internal.impl.dv.dtd.NMTOKENDatatypeValidator"%> <%@taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%> <%@page import="com.liferay.portal.kernel.util.ListUtil"%> <%@page import="com.attune.model.Books" %> <%@page import="com.attune.service.BooksLocalServiceUtil"%> <%@page import="java.util.List"%> <%@page import="java.util.*" %> <%@page import="java.text.*" %> <%@ include file="/init.jsp" %> <portlet:defineObjects />
<h>Here You can Search Of Products Record</h>
<portlet:actionURL var="asd" name ="search" /> <aui:form name="b" action="<%=asd.toString() %>" method="post" > <aui:input type="text" label="Please Enter Name Of Book" name="booknameLike" value="" />
Developing Liferay application with Service Builder | 74
<aui:button type="submit" value="Search" /> </aui:form>
<%
List<Books> ab = new ArrayList<Books>();
if(request.getParameter("bookname") != null)
{
String str=request.getParameter("bookname");
System.out.println("str val"+str);
ab = BooksLocalServiceUtil.findBook(str);
}
else
{
ab = BooksLocalServiceUtil.getBookses(0,BooksLocalServiceUtil.getBooksesCount());
}
System.out.println(ab);
%>
<liferay-ui:search-container delta="5" emptyResultsMessage="no-users-were-found"> <liferay-ui:search-container-results
results="<%=ab %>" total="<%= ab.size()%>"> </liferay-ui:search-container-results>
<liferay-ui:search-container-row className="com.attune.model.Books" keyProperty="bookId" modelVar="book">
<liferay-ui:search-container-column-text name="title" property="title"/> <liferay-ui:search-container-column-text name="author" property="author"/> </liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
Developing Liferay application with Service Builder | 75
16. Now it will need to create Book Action classs ,this class we have to specified search
method redirect on view jsp page then mapping with action URL,name variable value.
<portlet:actionURL var="asd" name ="search" /> we are enter bok name into search .
Developing Liferay application with Service Builder | 76
package com.attune.action;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import com.liferay.util.bridges.mvc.MVCPortlet;
public class BookAction extends MVCPortlet {
public void search(ActionRequest req,ActionResponse res) throws Exception
{
String str = req.getParameter("booknameLike");
res.setRenderParameter("bookname",str );
//Redirect search container to display result
res.setRenderParameter("jspPage","/view.jsp");
}
}
package com.attune.action;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import com.liferay.util.bridges.mvc.MVCPortlet;
public class BookAction extends MVCPortlet {
public void search(ActionRequest req,ActionResponse res) throws Exception
{
String str = req.getParameter("booknameLike");
res.setRenderParameter("bookname",str );
//Redirect search container to display result
res.setRenderParameter("jspPage","/view.jsp");
}
}
Developing Liferay application with Service Builder | 77
17. In this step, we alreday have to insert some values manualy into database.
Developing Liferay application with Service Builder | 78
18. No
w
ru
n
de
plo
y
life
ray
pr
otl
et
pr
oje
ct
sel
ect
|N
ew|
Lferay|SDK|deploy,then we will add our liferay portlet project ,we are enter bok name into
search text box,then we can see that book result display to given following snippet below.
Developing Liferay application with Service Builder | 79