Liferay 7.3: Add service builder to the portlet

Previously we created the portlet and service builder inside the eclipse workspace instead of creating a liferay workspace project inside eclipse workspce. So I face the following issues to add the service builder to my portlet (both of them are reside in eclipse workspace)

Could not run phased build action using Gradle distribution 'https://services.gradle.org/distributions/gradle-5.6.4-bin.zip'.
Build file '/home/abhilash/eclipse-workspace/register-emailbox/build.gradle' line: 32
A problem occurred evaluating root project 'register-emailbox'.
Project with path ':sitesService:sitesService-api' could not be found in root project 'register-emailbox'.

Many of them had this issue and you can search in this article of Liferay dev for creating service builder:

https://liferay.dev/blogs/-/blogs/creating-service-builder-mvc-portlet-in-liferay-7-with-liferay-ide-3-

People commented like:

But no solution mentioned here

After some research I came to know that solving this issue, we need to create a portlet and a service builder inside the liferay workspace not eclipse workspace (We should create a liferay workspace project inside eclipse workspace).

Lets do that this time.

Click File -> New -> Liferay Workspace Project

Provide a Project Name and click on Finish

Next right click on the da-workspace, New -> Liferay Module Project

Provide the Project Name, then it automatically changes the Location

Provide the class name and project name

Deploy this service by clicking on the gradle section of IDE and double click on deploy

Deployed successfully

You can see the module os created inside our new Liferay Workspace: da-workspace

Jar file created

Copy this jar file and paste into the liferay server folder path given below:

~/liferay-ce-portal-tomcat-7.3.0-ga1-20200127150653953/liferay-ce-portal-7.3.0-ga1/deploy

You can see the server log like this:

2020-04-14 09:16:09.299 INFO  [fileinstall-/home/abhilash/liferay-ce-portal-tomcat-7.3.0-ga1-20200127150653953/liferay-ce-portal-7.3.0-ga1/osgi/modules][BundleStartStopLogger:39] STARTED com.emailbox_1.0.0 [1117]

Status -> STARTED

Now delete our old services. Goto the Goshell and uninstal the bundles:

Now goto the liferay and check our newly created portlet

Now lets repeat the steps for creating the service-builder from the previous article. But this time create it from da-workspace

File -> New -> Liferay Module Project

Services are created – For details check the previous article

Folder structure for the portlet and the service builder

Add the details as shown in the below screenshots (If any doubt check the previous article).

Do builder service and deploy

Copy this jar files one by one to the server’s deploy folder. First *api.jar and then *service.jar

Server logs:

liferay-ce-portal-tomcat-7.3.0-ga1-20200127150653953/liferay-ce-portal-7.3.0-ga1/osgi/modules][BundleStartStopLogger:39] STARTED com.siteservice.api_1.0.0 [1118]

liferay-ce-portal-7.3.0-ga1/osgi/modules][BundleStartStopLogger:39] STARTED com.siteservice.service_1.0.0 [1119]


Check the database, you can see the Site_ Table and columns are created.

Now add the service builder dependancy to the portlet

Add this two lines in the build.gradle file

Right click on showEmailBox portlet and gradle -> refresh gradle project

DONE! You are successfully binded the service builder to your portlet.

now add the following to your portal class file above the doView function

@Reference
private SiteLocalService _siteLocalService;

now you can use the following default functions provided by liferay on the service.

_siteLocalService.fetchSite(23);
_siteLocalService.createSite(2344);
_siteLocalService.deleteSite(2233);
_siteLocalService.getSitesCount();
_siteLocalService.updateSite(site);

But what is we needed to fetch suppose some sites which has particular site_id Or fetch all sites which has registered after this time etc?

For all these custom query to mysql db, we needed to create a custom finder methods. So lets create one.

Open service.xml of `siteService-service`

Click on Finders and add Name and Type

Click on Finder column and add the db column to find

Click on Source, you can see the finder is added

Double click on the buildService to build the service

Now we can add custom finder findBySiteId to this service.

Open siteLocalServiceImpl.java

package com.siteservice.service.impl;

import com.liferay.portal.aop.AopService;
import com.siteservice.model.Site;
import com.siteservice.service.base.SiteLocalServiceBaseImpl;

import java.util.List;

import org.osgi.service.component.annotations.Component;


@Component(
	property = "model.class.name=com.siteservice.model.Site",
	service = AopService.class
)
public class SiteLocalServiceImpl extends SiteLocalServiceBaseImpl {

	public List<Site> findBySiteId(long site_id) {
		return sitePersistence.findBySiteId(site_id);
	}
}

Now do the buildService for siteService. Then Gradle -> Refresh and deploy the service. Copy this jar files one by one to the server’s deploy folder. First *api.jar and then *service.jar

Refresh Gradle project for the portlet – showEmailBox

Add the following to the doView function of the portlet

Site site = _siteLocalService.findBySiteId(2233).get(0);
		
System.out.println("We got the site: ---------");
System.out.println(site);

and don’t forget to create a site entry in the database with id: 2233

mysql> insert into Site_ (id_, site_id, name, register_from_date, register_to_date, created_at, updated_at) values (1, 2233, 'Site 2020', '2020-01-01', '2020-06-19', CURDATE(), CURDATE());

deploy the portlet and check you are getting the site in the server console.

that’s it for now, will see in the next article.

Liferay 7.3: Create a custom MVC portlet

What is a portlet?

A portlet is fragment on a webpage as web application and is used with portlets on the same webpage.

When you access a web site, you interact with an application. That application may be simple: it may only show you information, such as an article. The application may be complex, including forms, sending data etc. These applications run on a platform that provides application developers the building blocks they need to make applications.

If there are so many implementations of MVC frameworks in Java, why did Liferay create yet another one?

Liferay MVC provides these benefits:

It’s lightweight, as opposed to many other Java MVC frameworks.
There are no special configuration files that need to be kept in sync with your code.
It’s a simple extension of GenericPortlet.
You avoid writing a bunch of boilerplate code, since Liferay’s MVC framework simply looks for some pre-defined parameters when the init() method is called.
The controller can be broken down into MVC command classes, each of which handles the controller code for a particular portlet phase (render, action, and resource serving phases).
Liferay’s portlets use it. That means there are plenty of robust implementations to reference when you need to design or troubleshoot your Liferay applications.

Each portlet phase executes different operations:

Init: 

The init()  method is called by the portlet container during deployment and reads init parameters defined in portlet.xml file. The Portlet interface exposes the init method as:  void init (PortletConfig config) throws PortletException
The PortletConfig interface is  to retrieve configuration  from the portlet definition in the deployment descriptor. The portlet can only read the configuration data. The configuration information contains the portlet name, the portlet initialization parameters, the portlet resource bundle and the portlet application context.

Render:

Generates the portlet’s contents based on the portlet’s current state. When this phase runs on one portlet, it also runs on all other portlets on the page. The Render phase runs when any portlets on the page complete the Action or Event phases.

In this phase portlet generates content and renders on webpage.

The render phase is called in below cases:
1. The page that contains portlet is rendered on web page
2. After completing Action Phase
3. After completing Event Processing phase

below is example:

<portlet:renderURL var=“loadEmployees”> <portlet:param name=”mvcPath”
value=”/WEB-INF/view/empList.jsp” /> </portlet:renderURL>
<a href=”<%=loadEmployees%>”>Click here</a>


Action:

In response to a user action, performs some operation that changes the portlet’s state. The Action phase can also trigger events that are processed by the Event phase. Following the Action phase and optional Event phase, the Render phase then regenerates the portlet’s contents.

 its result of user actions such as add,edit, delete

  1. only one portlet can be entered into action phase for a request in a portlet container
  2. Any events triggered during the Action phase are handled during the Event phaseof the portlet lifecycle. Events can be used when portlets want to communicatewith each other. The Render phase will be called when all events have been handled.


Event:

Processes events triggered in the Action phase. Events are used for IPC. Once the portlet processes all events, the portal calls the Render phase on all portlets on the page.
Resource-serving: Serves a resource independent from the rest of the lifecycle. This lets a portlet serve dynamic content without running the Render phase on all portlets on a page. The Resource-serving phase handles AJAX requests.

Reference:

You can see more details and clarify your doubts by checking the following docs:

https://help.liferay.com/hc/en-us/articles/360018159451-Liferay-MVC-Portlet-

https://help.liferay.com/hc/en-us/articles/360018159431-Introduction-to-Portlets-

https://help.liferay.com/hc/en-us/articles/360017880432-Creating-an-MVC-Portlet-

http://www.javasavvy.com/liferay-portlet-basics-and-lifecycle/

Now we get into the action.

Step 1: Open Developer Studio and goto File -> New -> Liferay Module Project

Add Project Name, select mvc-portlet

Add class Name and package name and click finish

Step 2: Take Gradle task from right side section and double click on the deploy of created portlet

You can check the created portlet in the Studio’s workspace folder as above

The controller class of the portlet

Step 3: We will be changing the Class file and view file and deploy the changes and check

Add some code snnippet inside the above java Class, so that class look like this:

package com.register.portlet;

import com.register.constants.CheckRegisterPortletKeys;

import java.io.IOException;

import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet;

import javax.portlet.Portlet;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.osgi.service.component.annotations.Component;

/**
 * @author abhilash
 */
@Component(
	immediate = true,
	property = {
		"com.liferay.portlet.display-category=Register",
		"com.liferay.portlet.header-portlet-css=/css/main.css",
		"com.liferay.portlet.instanceable=true",
		"javax.portlet.display-name=CheckRegister",
		"javax.portlet.init-param.template-path=/",
		"javax.portlet.init-param.view-template=/view.jsp",
		"javax.portlet.name=" + CheckRegisterPortletKeys.CHECKREGISTER,
		"javax.portlet.resource-bundle=content.Language",
		"javax.portlet.security-role-ref=power-user,user"
	},
	service = Portlet.class
)
public class CheckRegisterPortlet extends MVCPortlet {
	public void doView(RenderRequest renderRequest, RenderResponse renderResponse) 
		   throws IOException, PortletException {
		System.out.println("inside my check registration logic controller");
		super.doView(renderRequest, renderResponse);
	}
}

Change the view.jsp as above

Step 4: Deploy again so that you can see the jar file is created as below:

The jar file created

Copy the jar file into this tomcat server folder, so that it can pick the package

Step 5: You can see the package status in the Gogo shell Liferay provides, goto the http://localhost:8080 and check inside the Configuration section Gogo Shell. Type command: lb

See the status – Installed. It should be ACTIVE after we deploy it.

Here are the list of osgi lifecycle status:

Step 6: Handle the Errors if any

I am getting some issues with this creation, lets see what is the problem.

I don’t have any idea why I am getting this. After some research I tried to add the module that is missing here, but no luck. Then I realised we are on Liferay 7.3 and See the pic of the IDE there we selected 7.2 version because thats the latest version available there. Hmm…So…yeahh that may be the issue here. You got that!

So Update your IDE and create the package again.

Now it Works!

And check our newly created portlet in the right side section (inside Widget) of Liferay Site.

You can see this messge that we wrote inside the Class inside my check registration logic controller in your server console in IDE. And this message This portlet is created by Abhilash inside the Portlet.

Congrats .. You have created your first custom portlet in Liferay.

Liferay 7.3: Configure IDE

Step 1. Download it from

Download from here:
https://liferay.dev/project/-/asset_publisher/TyF2HQPLV1b5/content/ide-installation-instructions

Extract it to your /home directory

Step 2. run the installer

./LiferayProjectSDKwithDevStudioCommunityEdition-201910152009-linux-x64-installer.run

You can see the steps involving the process below.

Select java runtime

After install Open it. Double click on the following file:

~/LiferayProjectSDKwithDevStudioCommunityEdition/liferay-developer-studio/DeveloperStudio

you can see the welcome page. Close it.



Click on Workbench to start on

This is how Liferay Studio Workspace home page look like

You can create liferay plugins / projects etc from here.

Step 3. Click on right corner first button and open perspective.

select Liferay plugins

Open Perspective

Step 4. Left bottom corner there is ‘Servers’ Tab

right click on it and select ‘New’ -> ‘Server’

Select ‘Liferay inc’ -> Liferay 7.x and click next

Add the tomcat server to your SDK to control the server from SDK. This helps you to see the server logs and other live status in IDE

Select the tomcat server path from your downloaded liferay portal

Make sure you are using the timestamp folder in the path of the server, else it not gonna work. It will show you an error like this:

If you start the tomcat server and try to access it without the timestamp PATH

You can add an existing resources created if available like theme etc to the server. If you don’t have any resources don’t worry. We are going to cover this in next chapter.

Click on the server name on the bottom left corner and you can see the configurations of the server.

Server Started. You can see the server logs in the console

LifeRay: What is Liferay? How to install it?

What is liferay?

With liferay we can create any number of custom sites. We can easily create sections like web content, blog content etc and share between those
sites. We can drag and drop sections to create website parts. So it is easy to use for admin users to add sections and drag to create pages.

“Liferay Portal is an open source enterprise web platform for building business solutions that deliver immediate results and long-term value. Liferay Portal started out as a personal development project in 2000 and was open sourced in 2001.”

Insallation:

Download liferay from: https://www.liferay.com/it/downloads-community

Or by command line:

wget https://releases.liferay.com/portal/7.3.1-ga2/liferay-ce-portal-tomcat-7.3.1-ga2-20200327090859603.tar.gz

Here we are going to install liferay version 7.3

Links:

https://portal.liferay.dev/docs/7-2/deploy/-/knowledge_base/d/installing-product

OR

check the readme file in (after downloading liferay portal)

~/Downloads/liferay-ce-portal-tomcat-7.3.1-ga2-20191111141448326/liferay-ce-portal-7.3.0-ga1/ folder

After that Download and install Java (JDK) 8 (if necessary) in your local environment.

OpenJDK 8

Java 8 is the current Long Term Support version and is still widely supported, though public maintenance ends in January 2019. To install OpenJDK 8, execute the following command:


sudo apt install openjdk-8-jdk
➜ java -version
openjdk version "1.8.0_232"
OpenJDK Runtime Environment (build 1.8.0_232-8u232-b09-0ubuntu1~18.04.1-b09)
OpenJDK 64-Bit Server VM (build 25.232-b09, mixed mode)

Extract the liferay portal .zip file. Copy the folder liferay-ce-portal-7.3.0-ga1 to your home path. And go inside the folder path as shown below:

cd ~/liferay-ce-portal-7.3.0-ga1/tomcat-9.0.17/bin

and do:

Start Tomcat server:

sh startup.sh

Using CATALINA_BASE:   /home/abhi/liferay-ce-portal-7.3.0-ga1/tomcat-9.0.17
Using CATALINA_HOME:   /home/abhi/liferay-ce-portal-7.3.0-ga1/tomcat-9.0.17
Using CATALINA_TMPDIR: /home/abhi/liferay-ce-portal-7.3.0-ga1/tomcat-9.0.17/temp
Using JRE_HOME:        /usr/lib/jvm/java-8-openjdk-amd64
Using CLASSPATH:       /home/abhi/liferay-ce-portal-7.3.0-ga1/tomcat-9.0.17/bin/bootstrap.jar:/home/abhi/liferay-ce-portal-7.3.0-ga1/tomcat-9.0.17/bin/tomcat-juli.jar
Tomcat started.

Restart command for Tomcat server:

sh shutdown.sh && sh startup.sh

Goto http://localhost:8080/

Go with default hypersonic DB if you are in testing environment.


Restart the Tomcat server

sh shutdown.sh && sh startup.sh

and goto http://localhost:8080

If the server is not started properly, you can check the logs here:

cd ~/liferay-ce-portal-7.3.0-ga1/tomcat-9.0.17/logs/ && tail -f catalina.out

I faced the following issue in new 7.3 version with mysql db which I didn’t face with 7.2 version with Hypersonic DB. My mysql db schema is not proper to version 7.3.

  __    ____________________  _____  __
   / /   /  _/ ____/ ____/ __ \/   \ \/ /
  / /    / // /_  / __/ / /_/ / /| |\  /
 / /____/ // __/ / /___/ _, _/ ___ |/ /
/_____/___/_/   /_____/_/ |_/_/  |_/_/

Starting Liferay Community Edition Portal 7.3.0 CE GA1 (Athanasius / Build 7300 / January 20, 2020)

2020-03-23 12:22:13.798 INFO  [main][StartupHelperUtil:99] There are no patches installed
You must first upgrade the portal to the required schema version 8.1.0
2020-03-23 12:22:13.860 ERROR [main][MainServlet:300] java.lang.RuntimeException: You must first upgrade the portal to the required schema version 8.1.0
java.lang.RuntimeException: You must first upgrade the portal to the required schema version 8.1.0
	at com.liferay.portal.events.StartupHelperUtil.verifyRequiredSchemaVersion(StartupHelperUtil.java:220)
	at com.liferay.portal.events.StartupAction.doRun(StartupAction.java:136)
	at com.liferay.portal.events.StartupAction.run(StartupAction.java:77)
	at com.liferay.portal.internal.servlet.MainServlet.init(MainServlet.java:297)

You’re presented a Basic Configuration page. Complete the configuration options. Liferay Portal uses an embedded database (HSQL) to make installation fast and easy. This database is not ready for production, so consider configuring a production-ready database (e.g., MySQL) if you plan on doing more than just exploring/testing. Agree to the terms and conditions, create a password, and configure a security question/answer.

You can now use Liferay Portal!

You can check all the projects from Liferay:

https://liferay.dev/projects

Get started from here:
https://portal.liferay.dev/

Liferay IDE:
https://liferay.dev/projects/ide

Liferay SDK:

“Liferay Plugin SDK is a development environment allows you to develop plugins for Liferay of all types such as Portlet, Themes, Layout Templates. The Liferay Plugin SDK is based on the Apache Ant tool and it can be integrated with all the common IDEs or used directly from the command line by executing a set of predefined commands (targets, in Ant’s nomenclature). In this tutorial I show how to configure the Plugin SDK in the Eclipse IDE”

Check this link (this doc is for version 6.1) :

https://portal.liferay.dev/docs/6-1/develop/-/knowledge_base/t/installing-the-sdk

LifeRay DXP:

This is the paid version from Liferay. With Liferay DXP you can implement not just static site, but something like today’s frontend fromeworks do (updating the DOM according to framework and spontaneous data change). Also you get the liferay support according to your plan.

Links:

https://www.liferay.com/products/dxp
https://www.liferay.com/solutions/websites
https://www.liferay.com/products/dxp/30-day-trial