Showing posts with label portlet. Show all posts
Showing posts with label portlet. 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
}

}

Interportlet Communication using Public Render Parameters



Interportlet Communication using Public Render Parameters

Create two portlets named as PortletA and PortletB with classes PortletActionA, PortletActionB.

IN PortletA , do below things:
-----------------------------------
portlet.xml --> IN portlet configuration mention the below line :
<supported-public-render-parameter>firstName</supported-public-render-parameter>

after ending the portlet tag give the below lines:
 <public-render-parameter>
        <identifier>firstName</identifier>
          <qname xmlns:x="http://sun.com/params">x:firstName</qname>
    </public-render-parameter>
  

Repeat the above thing in PortletB also...


In Portlet A:-

PortletActionA Class:-

set the render parameter as below like:
public void portletAActionURL(ActionRequest actionRequest, ActionResponse actionResponse){

System.out.println("portletA callign");

actionResponse.setRenderParameter("firstName", "devi");
}


In PortletB :-


doview() method write below code:

String firstname =renderRequest.getParameter("firstName");

System.out.println("firstname == "+firstname);
renderRequest.setAttribute("firstname", firstname);



Then u will observe the value in your jsp as

renderRequest.getAttribute("firstName") and print this..

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..