Showing posts with label liferay. Show all posts
Showing posts with label liferay. Show all posts

Tuesday, December 9, 2014

Downloading documents in CSV and PDF formats using Jasper Reports

For downloading documents liferay supports jasper reports engine and one of the market place EE portlet like Reports portlet is also works on the same. To work with Reports EE portlet we should have jrxml and need to upload in to the definition to generate CSV and PDF formats or any other formats. So If you want to download any document in your custom portlet you need to write the code using Jasper Reports API for preparing document. For that we need to pass Jrxml file (Jasper Report xml file) and this creation of jrxml will be done using ireport designer tool. IReport designer tool: Install any latest version of ireport designer and create data source connection with MySql server details as shown in step1 of the tool. Once it is done next step is click on step2 link and in Report section select Blank A4 and click on button “Open this Template”. It will ask the file to save and those folder details. After this a new report will be created by opening with designer view: So this is the designer page here you can give the fields for display, headings, fonts ,styles and lines we can draw and we can add tables, sub reports using the elements in Right-hand side of Palette section. So here you can design the page in the way what we want and arrange those using designer. We can drag and drop the fields from Fields section from the “Report Inspector”. So now we have created successfully a report and its view as shown below: This jrxml will be saved in folder location you gave. Copy this jrxml and create one folder in docroot with the name as reports and save this file in this location (report1.jrxml) Use this jrxml and pass this file to the Jasper reports using below code:

private void generateReport(PortletRequest resourceRequest , PortletResponse response, Map parameters) throws IOException {

String fileType = ParamUtil.getString(resourceRequest, "fileType");

if(fileType != null && fileType != ""){

HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(response);

OutputStream outputStream = httpServletResponse.getOutputStream();

List invoicesList = new ArrayList();

try { invoicesList = InvoiceLocalServiceUtil.getInvoices(-1, -1);

} catch (SystemException e) { System.out.println("no list found");

} String path = getPortletContext().getRealPath("/reports/test_jasper.jrxml");

InputStream inputStream = new FileInputStream (path);

JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(invoicesList);

byte[] contentArray = null;

try { JasperDesign jasperDesign = JRXmlLoader.load(inputStream);

JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);

if(fileType.equalsIgnoreCase("PDF")){

System.out.println("PDF calling");

contentArray = JasperExportManager.exportReportToPdf(jasperPrint);

httpServletResponse.setContentType("application/pdf");

httpServletResponse.setHeader("Content-Disposition","attachment;filename=test."+fileType);

outputStream.write(contentArray);

}else{

httpServletResponse.setContentType("text/csv");

JRCsvExporter exporter = new JRCsvExporter();

exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);

exporter.setParameter(JRCsvExporterParameter.FIELD_DELIMITER,";");

exporter.setParameter(JRCsvExporterParameter.RECORD_DELIMITER,"\r\n");

httpServletResponse.setHeader("Content-Disposition", "attachment;filename=testcsv.csv");

StringBuffer buffer = new StringBuffer();

exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER, buffer);

exporter.exportReport();

outputStream.write(buffer.toString().getBytes());

httpServletResponse.flushBuffer();

} } catch (JRException e) {

e.printStackTrace();

System.out.println("data not found");

} outputStream.close();

}

}



Required jars for the above code is :

For preparing CSV document use the class JRCsvExporter and for PDF document use the class JasperExportManager. In above code for exporting document in to PDF and CSV formats the code has written. And remaining things are self-explanatory in the code. For downloading document we need to create OutputStream object and pass the appropriate MIME formats to the HttpServletResponse object. And from UI side I have created forms with two submit buttons “Generate CSV Report” and “Generate PDF Report”. While submitting the report I have created ResourceURL because the action we are doing here is ajax request because after downloading the document the page should not refresh. So I created liferay resource url and written serveResource() method implementation in controller side.

If we look on code in controller is : ExportReports.java



@Override public void serveResource(ResourceRequest resourceRequest, ResourceResponse response) throws IOException, PortletException {

String[] invoiceInfo = ParamUtil.getParameterValues(resourceRequest, "invoiceInfo");

generateReport(resourceRequest,response,putParameters(invoiceInfo));

} private Map putParameters(String[] invoiceInfo) {

Map parameters = new HashMap();

for(String selectedData : invoiceInfo){

selectedData = "show"+selectedData;

parameters.put(selectedData, Boolean.TRUE);

} return parameters;

}

We have completed our coding part and need to check it in application how is it working: downloaded csv file is :







Wednesday, December 3, 2014

how to get real path of a file placed in liferay plugin

how to get real path of a file placed in liferay plugin


String path = getPortletContext().getRealPath("/reports/test_jasper.jrxml");

Displaying Custom Fields In Liferay


Displaying Custom Fields In Liferay




displaying custom field attribute in jsp for "ssn"
========================================================

<liferay-ui:custom-attribute

 className="<%= User.class.getName() %>"

 classPK="<%= selUser != null ? selUser.getUserId() : 0 %>"

editable="<%= true %>"

name="ssn" label="true"/>

here name is "ssn" it should be present in language.properties file (key ,name value pair)




Getting the value in controller side for "ssn"
=====================================================

 String ssnValue = (String)PortalUtil.getExpandoValue(actionRequest, "ExpandoAttribute--" + "ssn" + "--", ExpandoColumnConstants.STRING, ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX);

Create site programmatically in Liferay


Create site programmatically in Liferay



This code does creates a site and adds site template to it...

1. It will reaad site name from portal-ext.properties file
2. It will get the site template already created from browser and then add this template to our newly created site.
3. It will get logo from the class path -WEB-INF/mylogo.png
4. It will place logo to our site..


@Override
public void doView(RenderRequest renderRequest,
RenderResponse renderResponse) throws IOException, PortletException {
System.out.println("view calling");

String customSiteName = PropsUtil.get("custom.site.name");
System.out.println("site name == "+customSiteName);

int publicLayoutSetPrototypeId = 0;
int privateLayoutSetPrototypeId =0;

try {
ServiceContext serviceContext =  ServiceContextFactory.getInstance(Group.class.getName(), renderRequest);

Group grp = null;
try {
grp = GroupServiceUtil.getGroup(serviceContext.getThemeDisplay().getCompanyId(), customSiteName);
} catch (Exception e) {

}

if(grp == null){

System.out.println("group created");
grp = GroupServiceUtil.addGroup(GroupConstants.DEFAULT_PARENT_GROUP_ID, GroupConstants.DEFAULT_LIVE_GROUP_ID, customSiteName, customSiteName+"description", GroupConstants.TYPE_SITE_OPEN,
true, GroupConstants.DEFAULT_MEMBERSHIP_RESTRICTION,
"/"+customSiteName, true, true, serviceContext);
}

System.out.println("site created.."+grp.getName());



List<LayoutSetPrototype> layoutSetPrototypes=LayoutSetPrototypeServiceUtil.search(serviceContext.getThemeDisplay().getCompanyId(),Boolean.TRUE, null);

for(LayoutSetPrototype layoutSetPrototype : layoutSetPrototypes){

if(layoutSetPrototype.getName("").equals("mysitetemplate")){

publicLayoutSetPrototypeId = (int) layoutSetPrototype.getLayoutSetPrototypeId();
System.out.println("public pages template id :"+publicLayoutSetPrototypeId);
}
if(layoutSetPrototype.getName("").equals("mysitetemplate2")){

privateLayoutSetPrototypeId = (int) layoutSetPrototype.getLayoutSetPrototypeId();
System.out.println("private pages template ID : "+privateLayoutSetPrototypeId);
}
}



MethodKey methodKey  = new MethodKey(SitesUtil.class, "updateLayoutSetPrototypesLinks",Group.class,long.class, long.class,boolean.class,boolean.class);
PortalClassInvoker.invoke(true, methodKey, grp, publicLayoutSetPrototypeId, privateLayoutSetPrototypeId,true,true);

LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(grp.getGroupId(), true);

MethodKey _mergeLayoutSetPrototypeLayoutsMethodKey  = new MethodKey(SitesUtil.class,"mergeLayoutSetPrototypeLayouts",Group.class,LayoutSet.class);

PortalClassInvoker.invoke(true,_mergeLayoutSetPrototypeLayoutsMethodKey,grp, layoutSet);

System.out.println("suuccess");

java.io.File file = new java.io.File(getPortletContext().getRealPath("/WEB-INF/mylogo.png"));

LayoutSetServiceUtil.updateLogo(grp.getGroupId(), false, true, file);




} catch (PortalException e) {
e.printStackTrace();
} catch (SystemException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}


super.doView(renderRequest, renderResponse);
}

Adding tags programatically after blog entry added in Blogs portlet

Adding tags programatically after blog entry added in Blogs portlet


1. create a hook and add portal properties.
2. In portal properties write the portall property as given below:
value.object.listener.com.liferay.portlet.blogs.model.BlogsEntry=com.test.liferay.portlet.blogs.NewBlogEntryListener
    we are doing for  blog content , so we need to create listener for BlogsEntry model.

3. create the above class -NewBlogEntryListener in the package as mentioned above:
4. Write the code below:


NewBlogEntryListener.java
-------------------------------------- (The below code is for creating tags  and also for sending mail when a blog entry created)

package com.test.liferay.portlet.blogs;

import com.liferay.portal.ModelListenerException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.PrefsPropsUtil;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.util.SubscriptionSender;
import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil;
import com.liferay.portlet.blogs.model.BlogsEntry;
import com.liferay.portlet.blogs.service.BlogsEntryLocalServiceUtil;
import com.liferay.util.PwdGenerator;

public class NewBlogEntryListener implements ModelListener<BlogsEntry> {

@Override
public void onAfterAddAssociation(Object arg0, String arg1, Object arg2)
throws ModelListenerException {
// TODO Auto-generated method stub
}

@Override
public void onAfterCreate(BlogsEntry entry) throws ModelListenerException {
System.out.println("after create method calling");

String fromName = null;
String fromAddress = null;
String toName = null;
String toAddress = null;
String subject = null;
try {
fromName = PrefsPropsUtil.getString(
entry.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
fromAddress = PrefsPropsUtil.getString(
entry.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);

toName = entry.getUserName();
//toAddress = PortalUtil.getUserEmailAddress(entry.getUserId());
toAddress ="nagadevi.nimmagadda@igate.com";

subject = PrefsPropsUtil.getContent(
entry.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

String body = "sample mail code";

System.out.println("fromName"+fromName);
System.out.println("fromAddress"+fromAddress);
System.out.println("toName"+toName);
System.out.println("toAddress"+toAddress);
System.out.println("subject"+subject);
SubscriptionSender subscriptionSender = new SubscriptionSender();

subscriptionSender.setBody(body);
subscriptionSender.setCompanyId(entry.getCompanyId());
subscriptionSender.setContextAttributes(
"[$USER_ID$]", entry.getUserId(), 
"[$USER_SCREENNAME$]",entry.getUserName());
subscriptionSender.setFrom(fromAddress, fromName);
subscriptionSender.setHtmlFormat(true);
subscriptionSender.setMailId(
"user", entry.getUserId(), System.currentTimeMillis(),
PwdGenerator.getPassword());
//subscriptionSender.setServiceContext(PortalUtil.getuser);
subscriptionSender.setSubject(subject);
subscriptionSender.setUserId(entry.getUserId());

//subscriptionSender.addRuntimeSubscribers(toAddress, toName);

//subscriptionSender.flushNotificationsAsync();
System.out.println("mail sent successfully");
ServiceContext serviceContext = new ServiceContext();
serviceContext.setCompanyId(entry.getCompanyId());
try {
AssetTagLocalServiceUtil.addTag(entry.getUserId(), "tag1", null, serviceContext);
AssetTagLocalServiceUtil.addTag(entry.getUserId(), "tag2", null, serviceContext);
String[] assetTagNames = new String[]{"tag1","tag2"};
System.out.println("tag names are :"+assetTagNames.toString());
long[] assetLinkEntryIds = AssetTagLocalServiceUtil.getTagIds(entry.getGroupId(), assetTagNames);
System.out.println("asset link entry ids :"+assetLinkEntryIds.toString());
BlogsEntryLocalServiceUtil.updateAsset(entry.getUserId(), entry, null, assetTagNames, assetLinkEntryIds);
System.out.println("tag added successfully");
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Override
public void onAfterRemove(BlogsEntry arg0) throws ModelListenerException {
// TODO Auto-generated method stub
}

@Override
public void onAfterRemoveAssociation(Object arg0, String arg1, Object arg2)
throws ModelListenerException {
// TODO Auto-generated method stub
}

@Override
public void onAfterUpdate(BlogsEntry arg0) throws ModelListenerException {
// TODO Auto-generated method stub
}

@Override
public void onBeforeAddAssociation(Object arg0, String arg1, Object arg2)
throws ModelListenerException {
// TODO Auto-generated method stub
}

@Override
public void onBeforeCreate(BlogsEntry arg0) throws ModelListenerException {
// TODO Auto-generated method stub
}

@Override
public void onBeforeRemove(BlogsEntry arg0) throws ModelListenerException {
// TODO Auto-generated method stub
}

@Override
public void onBeforeRemoveAssociation(Object arg0, String arg1, Object arg2)
throws ModelListenerException {
// TODO Auto-generated method stub
}

@Override
public void onBeforeUpdate(BlogsEntry arg0) throws ModelListenerException {
// TODO Auto-generated method stub
}

}

Global class loader and Portal class loader


What is meant by Global Class Loader, Portal Class Loader?

Global class Loader : is tomcat/lib and tomcat/lib/ext folders jar files.
Portal class Loader : tomcat/webapps/root/web-inf/lib folder  jar files
(ex: D:\workspace\liferay-developer-studio\liferay-portal-6.2-ee-sp3\tomcat-7.0.42\webapps\ROOT\WEB-INF\lib)

Global class loader jars are available to all the portlet. Make sure when adding any jars in your portal class lader check whether it is exist in global class loader or not. Viceversa for Global class loader.
In this way you can avoid ClassCastException .

In Hook portlet --> If you override portal jsp , you can get portal and global class loaders. But you can't get jars loaded in this HOOK..

How to Invoke classes in portal-impl.jar of liferay


How to Invoke classes in portal-impl.jar of liferay


We can invoke classes in portal-impl.jar using - PortalClassInvoker

PortalClassInvoker.invoke(true, _mergeLayoutSetPrototypeLayoutsMethodKey, group, layoutSet);

Custom notifications implementation in liferay


Implementing Custom Notifications in a Portlet


Liferay custom notifications require a User Notification Handler class that turns the notification into a nice HTML fragment that is displayed to the user. Also Liferay wants us to define the notification types that our portlet or application is creating in a definition file upfront.

<portlet>
<portlet-name>test-example</portlet-name>
<icon>/icon.png</icon>
 <indexer-class>com.liferay.testexample.search.EmployeeSearchIndexer</indexer-class>
<user-notification-definitions>example-user-notification-definitions.xml</user-notification-definitions>
<user-notification-handler-class>com.example.notifications.ExampleUserNotificationHandler</user-notification-handler-class>
<header-portlet-css>/css/main.css</header-portlet-css>
<footer-portlet-javascript>/js/main.js</footer-portlet-javascript>
<css-class-wrapper>test-example-portlet</css-class-wrapper>
</portlet>

So the first thing we need to do is to define the location of our class that extends BaseUserNotificationHandler class and definitions inside liferay-portlet.xml. This can be done in liferay-portlet.xml like this:

The important part is user-notification-definitions and user-notification-handler-class tags. Now we need to actually define our notification inside that example-user-notification-definitions.xml. This file should go into your docroot/WEB-INF/src folder. 
Here is the example-user-notification-definitions.xml :
<?xml version="1.0"?>
<!DOCTYPE user-notification-definitions PUBLIC "-//Liferay//DTD User Notification Definitions 6.2.0//EN" "http://www.liferay.com/dtd/liferay-user-notification-definitions_6_2_0.dtd">
<user-notification-definitions>
<definition>
<notification-type>${com.example.notifications.ExampleUserNotificationHandler.PORTLET_ID}</notification-type>
<description>receive-a-notification-when-example-triggered</description>
<delivery-type>
<name>email</name>
                  <type>${com.liferay.portal.model.UserNotificationDeliveryConstants.TYPE_EMAIL}</type>
<default>false</default>
<modifiable>true</modifiable>
</delivery-type>
<delivery-type>
<name>website</name>
<type>${com.liferay.portal.model.UserNotificationDeliveryConstants.TYPE_WEBSITE}</type>
<default>true</default>
<modifiable>true</modifiable>
</delivery-type>
</definition>
</user-notification-definitions>

So in our example portlet class we can actually add a new notification for the user. We can do it by using UserNotificationEventLocalServiceUtil in either our service builder class or one of our portlet classes.
Here’s how to add notification event: In below we are adding a new employee data to employee persistence and so we are adding an event saying that new employee has added to the site users. So we have to send this notification event to all the site users by adding notification events to all.

employee =EmployeeLocalServiceUtil.addEmployee(employee);        
           
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(themeDisplay.getScopeGroupId());
           
JSONObject payloadJSON = JSONFactoryUtil.createJSONObject();
payloadJSON.put("userId", themeDisplay.getUserId());
payloadJSON.put("employeeId", employee.getEmpId());
payloadJSON.put("additionalData", "Your notification was added!");

 List<User> siteUsers=  UserLocalServiceUtil.getGroupUsers(themeDisplay.getScopeGroupId());
        
        
for(User siteUser : siteUsers){               UserNotificationEventLocalServiceUtil.addUserNotificationEvent(siteUser.getUserId(), com.example.notifications.ExampleUserNotificationHandler.PORTLET_ID, new Date().getTime(), themeDisplay.getUserId(), payloadJSON.toString(), false, serviceContext);
            System.out.println("notification event adding to user : "+siteUser.getScreenName());
          }


So now that we have our notification inside the database we want to actually show it to the user. When we look at the dockbar our notification number gets increased so we can be pretty sure that the notification was added. When you attempt to actually look at the notification you will probably see a blank white box. We need the notification handler class to actually handle the display side of our notification. This current example also handles the behavior like providing Approve and Reject buttons right in our example notification so that our example user could perform an action straight from the dockbar notification.

Here is the class :  ExampleUserNotificationHandler.java

package com.example.notifications;

import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.notifications.BaseUserNotificationHandler;
import com.liferay.portal.kernel.portlet.LiferayPortletResponse;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.model.UserNotificationEvent;
import com.liferay.portal.service.ServiceContext;

import javax.portlet.ActionRequest;
import javax.portlet.PortletURL;
import javax.portlet.WindowState;

public class ExampleUserNotificationHandler extends BaseUserNotificationHandler{

      public static final String PORTLET_ID = "testexample_WAR_testexampleportlet";

      public ExampleUserNotificationHandler() {
            setPortletId(ExampleUserNotificationHandler.PORTLET_ID);
      }
     
      @Override
      protected String getBody(UserNotificationEvent userNotificationEvent,
                  ServiceContext serviceContext) throws Exception {
            JSONObject jsonObject= JSONFactoryUtil.createJSONObject(userNotificationEvent.getPayload());
           
            long employeeId = jsonObject.getLong("employeeId");

            String title = "A new Employee data has been added ";

            String bodyText = "";
           
            LiferayPortletResponse liferayPortletResponse = serviceContext.getLiferayPortletResponse();
           
            PortletURL confirmURL = liferayPortletResponse.createActionURL(com.example.notifications.ExampleUserNotificationHandler.PORTLET_ID);
            confirmURL.setParameter(ActionRequest.ACTION_NAME, "doSomethingGood");
            confirmURL.setParameter("redirect", serviceContext.getLayoutFullURL());
            confirmURL.setParameter("employeeId", String.valueOf(employeeId));
            confirmURL.setParameter("userNotificationEventId", String.valueOf(userNotificationEvent.getUserNotificationEventId()));
            confirmURL.setWindowState(WindowState.NORMAL);
           
            PortletURL ignoreURL = liferayPortletResponse.createActionURL(com.example.notifications.ExampleUserNotificationHandler.PORTLET_ID);
            ignoreURL.setParameter(ActionRequest.ACTION_NAME, "cancelForExample");
            ignoreURL.setParameter("redirect", serviceContext.getLayoutFullURL());
            ignoreURL.setParameter("employeeId", String.valueOf(employeeId));
            ignoreURL.setParameter("userNotificationEventId", String.valueOf(userNotificationEvent.getUserNotificationEventId()));
            ignoreURL.setWindowState(WindowState.NORMAL);
           
           
            String body = StringUtil.replace(getBodyTemplate(), new String[] {
                  "[$CONFIRM$]", "[$CONFIRM_URL$]", "[$IGNORE$]",
                  "[$IGNORE_URL$]", "[$TITLE$]", "[$BODY_TEXT$]" }, new String[] {
                  serviceContext.translate("approve"), confirmURL.toString(),
                  serviceContext.translate("reject"), ignoreURL.toString(),
                  title, bodyText });
     
      return body;
           
           
      }
     
      @Override
      protected String getLink(UserNotificationEvent userNotificationEvent,
                  ServiceContext serviceContext) throws Exception {
            JSONObject jsonObject= JSONFactoryUtil.createJSONObject(userNotificationEvent.getPayload());
           
            long employeeId = jsonObject.getLong("employeeId");
           
            LiferayPortletResponse liferayPortletResponse = serviceContext.getLiferayPortletResponse();
            PortletURL confirmURL = liferayPortletResponse.createRenderURL(com.example.notifications.ExampleUserNotificationHandler.PORTLET_ID);
            confirmURL.setParameter("redirect", serviceContext.getLayoutFullURL());
            confirmURL.setParameter("employeeId", String.valueOf(employeeId));
            confirmURL.setParameter("userNotificationEventId", String.valueOf(userNotificationEvent.getUserNotificationEventId()));
            confirmURL.setWindowState(WindowState.NORMAL);
           
      return confirmURL.toString();
           
           
      }
      protected String getBodyTemplate() throws Exception {
            StringBundler sb = new StringBundler(5);
            sb.append("<div class=\"title\">[$TITLE$]</div><div ");
            sb.append("class=\"body\">[$BODY_TEXT$]<a class=\"btn btn-action ");
            sb.append("btn-success\" href=\"[$CONFIRM_URL$]\">[$CONFIRM$]</a>");
            sb.append("<a class=\"btn btn-action btn-warning\" href=\"");
            sb.append("[$IGNORE_URL$]\">[$IGNORE$]</a></div>");
            return sb.toString();
      }

           
}


com.example.notifications.ExampleUserNotificationHandler.PORTLET_ID string that you use as your notification type has to match an actual portlet ID. So  I have passed the PORTLET_ID as “testexample_WAR_testexampleportlet” which was the portelt I am placing notifications.
Now our code works as like If any employee data is added in to the table a new notification will send to all site users and that notification will be displayed on the notification bar .
After adding new employee a notification will be displayed in the dock bar as given below:
We can see the notification number is increased in the above screen. Click on notification:
As we created the content “A new Employee data has been added with 2 buttons ‘Approve’ and ‘Reject’ is displaying on notification title and body. Once clicking on ‘Approve’ button means the notification has read by the user and decreases its count. And all the notifications will  be available in the “Notifications” portlet which was the market place portlet .

For approve and reject buttons the code we should write in our portlet controller class as given below: TestExample.java
package com.test.example;

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.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.service.UserNotificationEventLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.testexample.model.Employee;
import com.liferay.testexample.service.EmployeeLocalServiceUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;

public class TestExample extends MVCPortlet {
               
                public void addEntity(ActionRequest request, ActionResponse response)
                                                throws Exception {
               
                                ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
                                Employee employee = EmployeeLocalServiceUtil.createEmployee(CounterLocalServiceUtil.increment(Employee.class.getName()));
                               
                                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
                               
                                employee.setFirstName(ParamUtil.getString(request, "firstName"));
                                employee.setFullName(ParamUtil.getString(request, "fullName"));
                                employee.setAge(ParamUtil.getInteger(request, "age"));
                                employee.setJoinedDate(ParamUtil.getDate(request, "joinedDate", sdf));
                                employee.setGender(ParamUtil.getString(request, "gender"));
                               
                                employee.setCompanyId(themeDisplay.getCompanyId());
                                employee.setGroupId(themeDisplay.getScopeGroupId());
                                employee.setUserId(themeDisplay.getUserId());
                               
                                employee =EmployeeLocalServiceUtil.addEmployee(employee);                            
                               
                                ServiceContext serviceContext = new ServiceContext();
        serviceContext.setScopeGroupId(themeDisplay.getScopeGroupId());
                               
                                JSONObject payloadJSON = JSONFactoryUtil.createJSONObject();
                    payloadJSON.put("userId", themeDisplay.getUserId());
                    payloadJSON.put("employeeId", employee.getEmpId());
                    payloadJSON.put("additionalData", "Your notification was added!");
                   
                   
                    List<User> siteUsers=  UserLocalServiceUtil.getGroupUsers(themeDisplay.getScopeGroupId());
                  
                  
                    for(User siteUser : siteUsers){
                                UserNotificationEventLocalServiceUtil.addUserNotificationEvent(siteUser.getUserId(), com.example.notifications.ExampleUserNotificationHandler.PORTLET_ID, new Date().getTime(), themeDisplay.getUserId(), payloadJSON.toString(), false, serviceContext);
                                System.out.println("notification event adding to user : "+siteUser.getScreenName());
                    }
                                response.setRenderParameter("mvcPath","/html/testexample/view.jsp");
                                }
               
                public void doSomethingGood(ActionRequest request, ActionResponse response)
                                                throws IOException, PortletException {

                                ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
                                long groupId = themeDisplay.getScopeGroupId();
                                long employeeId = ParamUtil.getLong(request, "employeeId");
                                long userNotificationEventId = ParamUtil.getLong(request, "userNotificationEventId");
                                try {
                                                UserNotificationEventLocalServiceUtil.deleteUserNotificationEvent(userNotificationEventId);
                                               
                                } catch (PortalException e) {
                                                System.out.println("Failed to remove notification:"+e.getMessage());
                                } catch (SystemException e) {
                                                System.out.println("Failed to remove notification:"+e.getMessage());
                                }

                }
               
                public void cancelForExample(ActionRequest request, ActionResponse response)
                                                throws IOException, PortletException {

                                ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
                                long groupId = themeDisplay.getScopeGroupId();
                                long employeeId = ParamUtil.getLong(request, "employeeId");
                                long userNotificationEventId = ParamUtil.getLong(request, "userNotificationEventId");
                                try {
                                                UserNotificationEventLocalServiceUtil.deleteUserNotificationEvent(userNotificationEventId);
                                               
                                } catch (PortalException e) {
                                                System.out.println("Failed to remove notification:"+e.getMessage());
                                } catch (SystemException e) {
                                                System.out.println("Failed to remove notification:"+e.getMessage());
                                }
                }
               
                               
}