RSS

How to Visualize a SDK Liferay portlet in panel control with other roles than Administrator

Version Liferay-5.2.3
For a SDK portlet to be visualizer in panelControl we just need add two lines in lifeay-portlet.xml :

<control-panel-entry-category>content</control-panel-entry-category>
<control-panel-entry-weight>12.0</control-panel-entry-weight>

The first line indicates that this portlet will be available in the Control Panel under that category, and the second indicate the position of the portlet in that category.
But this portlet only will be visualized by administrators users, to define other roles wee need to create a class that extends BaseControlPanelEntry and there control the roles, wee must indicate this class in liferay-portlet.xml:

<control-panel-entry-class>
com.portlet.struts.TagsControlPanelEntry
</control-panel-entry-class>  

Then create the roles in liferay-portlet.xml:

<role-mapper>
 <role-name>ROL_EDITOR</role-name>
 <role-link>ROL_EDITOR</role-link>
</role-mapper>

The class that control the roles:


package com.portlet.struts;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.liferay.portal.model.Organization;
import com.liferay.portal.model.Portlet;
import com.liferay.portal.model.Role;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.service.OrganizationLocalServiceUtil;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portlet.BaseControlPanelEntry;

public class TagsControlPanelEntry extends BaseControlPanelEntry {
 private static Log log = LogFactory.getLog(TagsControlPanelEntry.class);
 
 public boolean isVisible(PermissionChecker permissionChecker,
   Portlet portlet) throws Exception {

  long groupId ;
  
  try {
   List org = OrganizationLocalServiceUtil.getUserOrganizations(permissionChecker.getUserId());
   groupId = org.get(0).getGroup().getGroupId();
  } catch (Exception e1) {
   log.error("Caught:" + e1);
  }
  
  String roles[] = new String[2];
  try {
   roles = portlet.getRolesArray();
  } catch (Exception e) {
   log.error("Caught:" + e);
  }

  List userRoles = null;
  try {
   userRoles = RoleLocalServiceUtil.getUserGroupRoles(
     permissionChecker.getUserId(), groupId);
  } catch (Exception e) {
   log.error("Caught:" + e);
  }

  try {
   for (int i = 0; i < roles.length; i++) {

    for (Role userRole : userRoles) {
     if (userRole.getName().equals(roles[i])) {
      return true;
     }
    }
   }
  } catch (Exception e) {
   log.error("Caught:" + e);
  }

  return false;
 }

}

This class just gets the roles defined in portlet and verify if the user have some role defined in the portlet, this class search for organization roles in the user.
And now all the users with role "ROL_EDITOR" have the permission to see the portlet.

How to create scheduler in portlet with Quartz

Version Liferay-5.2.3
Using Liferay SDK, create a scheduler job in a portlet with Quartz

First create a class that contains actual task that needs to be executed:

package com.portlet.struts;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class SabiasQueJob implements org.quartz.Job{
   private static Log log = LogFactory.getLog(SabiasQueJob.class);
   
   public SabiasQueJob() {}

   public void execute(org.quartz.JobExecutionContext arg0) throws org.quartz.JobExecutionException {
    try {
   System.out.println("THIS IS THE ACTUAL TASK!");
   
  } catch (Exception e) {
   log.error("Portlet, Caught:" + e);
  }
    }

}


Second write a class that implements Scheduler interface.

package com.portlet.struts;

import com.liferay.portal.kernel.job.Scheduler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

public class SabiasQueSchedulerInterface implements Scheduler {
 private static Log _log = LogFactory
   .getLog(SabiasQueSchedulerInterface.class);

 public void NewSchedule() throws Exception {
  SchedulerFactory sf = new StdSchedulerFactory();
  org.quartz.Scheduler sched = sf.getScheduler();

  JobDetail jd2 = new JobDetail("myjob",
    org.quartz.Scheduler.DEFAULT_GROUP, SabiasQueJob.class);
  CronTrigger trigger = new CronTrigger("mytrigger",
    org.quartz.Scheduler.DEFAULT_GROUP, "myjob",
    org.quartz.Scheduler.DEFAULT_GROUP, "0 0 0 * * ?");

  sched.scheduleJob(jd2, trigger);

  sched.start();

 }

 public void schedule() {
  if (_log.isInfoEnabled()) {
   _log.info("Schedule");
  }

  try {
   NewSchedule();
  } catch (Exception ex) {
   _log.error(ex);
  }
 }

 public void unschedule() {
  if (_log.isInfoEnabled()) {
   _log.info("Unschedule");
  }
 }

}

This job is executed every day at 00h00m.For more detail and examples of Quartz see: Quartz

Last just register your scheduler in liferay-portlet.xml

<liferay-portlet-app>
    <portlet>
        <portlet-name>eventosSearch-portlet</portlet-name>
        <scheduler-class>com.portlet.struts.SabiasQueSchedulerInterface</scheduler-class>
    </portlet>
    <role-mapper>
        <role-name>administrator</role-name>
        <role-link>Administrator</role-link>
    </role-mapper>
</liferay-portlet-app>

Inter-Portlet Communication

IPC using client side java script

The client-side mechanism to communicate portlets is based on events, uses events instead of direct js calls accross portlets is very important
since it's not possible to know at deployment time which other portlets will be available in a given page.By firing/triggering an event one portlet just notifies that something has happened,
and then one or more of the other portlets in the page might be listening and act accordingly.

API used for doing client side PPC is follows,
1.Liferay.trigger(eventName, data) :
            Trigger an event in which n number of listners can catch the event and act according to the event.
2.Liferay.bind(eventName, function, [scope]) :
            Listen in for any arbitrary event (it could be anything the developer decides, or an existing one)

Bellow is the snippet for PPC using Javascript based IPC

Prerequesite:
1. create two jsp portlet using create.bat/sh of plugin sdk
         a. create.bat ipctrigger "Triggring Portlet"
         b. create.bat ipclistener "Listening Portlet"
2. deploy these newly created portlets to the server by running "ant deploy"
3. Add the above portlets in to a Portal Page, "IPC Demo"
4. Make sure that both the portlets are appearing fine.
5. Keep the listening portlet on the right side.


IPC using client side java script - Example 1


Example1: Updating a label inside listener portlet using a link provided in the triggering portlet.

snippet-1: insert the below code in to docroot/view.jsp of ipctrigger-portlet.

<script>
jQuery(
        function () {
          jQuery('a.update_label').click(
            function(event) {
              Liferay.trigger('updateLabel');
              return false;
            }
          );
          jQuery('a.remove_label').click(
            function(event) {
              Liferay.trigger('removeLabel');
              return false;
            }
          );
          
          // you'll put the snippet for next example here
        }
);
</script>
<br/><a class="update_label">Update Label Using PPC</a>
<br/><a class="remove_label">Remove Label Using PPC</a>


snippet-2: insert the below code in to docroot/view.jsp of ipclistener-portlet.

<script>
        Liferay.bind(
           'updateLabel',
           function(event) {
             jQuery('label.ppc_label_info').html('The portlet is invoked.......');
           }
        );
        Liferay.bind(
           'removeLabel',
           function(event) {
             jQuery('label.ppc_label_info').html('');
           }
        );
        
        // you'll put the snippet for next example here
        
</script>
<br/><label class="ppc_label_info" />

Redeploy these portlets and check how they work.

IPC using client side java script - Example 2

Example2: Passing a data using PPC.


snippet-1: insert the below code in to docroot/view.jsp of ipctrigger-portlet (inside the <script> tag)


function send() {
   
 var value = jQuery('input.ppc_text').val();
 Liferay.trigger('retrieveValue', {key: value});
 return false;
   }

<input type="text" class="ppc_text" value="Sample Data" />
<br/><input type="button" onclick="send()" class="ppc_button" value="Update Label" ></input>

snippet-2: insert the below code in to docroot/view.jsp of ipclistener-portlet (inside the <script> tag).

Liferay.bind(
           'retrieveValue',
           function(event, data) {
             jQuery('label.ppc_label_info1').html('Input:' + data.key);
           }
        );

<br/><label class="ppc_label_info1" />

From: Liferay

How to create scheduler in portlet

Version Liferay-5.2.3
Using Liferay SDK, create a scheduler job in a portlet.

First create a class that contains actual task that needs to be executed:

package com.portlet;

import com.liferay.portal.kernel.job.IntervalJob;
import com.liferay.portal.kernel.job.JobExecutionContext;
import com.liferay.portal.kernel.job.JobExecutionException;
import com.liferay.portal.kernel.util.Time;


public class SyncDataJob implements IntervalJob{
 public SyncDataJob() {
  _interval = Time.DAY;
 }
 public long getInterval() {
  return _interval;
 }
 public void execute(JobExecutionContext context)
  throws JobExecutionException {
  try {
   System.out.println("THIS IS THE ACTUAL TASK!");
  }
  catch (Exception e) {
  }
 }
 private long _interval;
}

Second write a class that implements Scheduler interface.

package com.portlet.struts;

import com.portlet.SyncDataJob;
import com.liferay.portal.kernel.job.JobSchedulerUtil;
import com.liferay.portal.kernel.job.Scheduler;

public class EventHistoricoAction implements Scheduler {

 public void schedule() {

  JobSchedulerUtil.schedule(_testIntervalJob);
 }

 public void unschedule() {

  JobSchedulerUtil.unschedule(_testIntervalJob);
 }


 private SyncDataJob _testIntervalJob = new SyncDataJob();

}

Last just register your scheduler in liferay-portlet.xml

<liferay-portlet-app>
    <portlet>
        <portlet-name>eventosSearch-portlet</portlet-name>
        <scheduler-class>com.portlet.struts.EventHistoricoAction</scheduler-class>
    </portlet>
    <role-mapper>
        <role-name>administrator</role-name>
        <role-link>Administrator</role-link>
    </role-mapper>
</liferay-portlet-app>

Convert pdf to images

This is a method thar convert de first page of a pdf file into an image using the open source library of IcePdf from IceSoft:


import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.imageio.ImageIO;
import javax.portlet.PortletPreferences;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.dispatcher.DefaultActionSupport;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.portlet.interceptor.PortletPreferencesAware;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.PDimension;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

private void generaImagenes(String urlDoc, String fileName) {
boolean control = true;
File file2 = new File(request.getSession().getServletContext()
.getRealPath("/thumbnails"));

String absoluteFile3 = file2.getAbsoluteFile().toString();
File folder = new File(absoluteFile3);
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
if (listOfFiles[i].getName().equals(fileName + ".png")) {
control = false;

}
}
}
if (control == true) {
Document document = new Document();

try {
URL files = new URL(urlDoc);

document.setUrl(files);

} catch (PDFException ex) {
System.out.println("Error parsing PDF document " + ex);

} catch (PDFSecurityException ex) {
System.out.println("Error encryption not supported " + ex);

} catch (FileNotFoundException ex) {
System.out.println("Error file not found " + ex);

} catch (IOException ex) {
System.out.println("Error handling PDF document " + ex);

}

float userRotation = 0;
float userZoom = 1;
PDimension pdfDimension = document.getPageDimension(1,
userRotation, userZoom);

float height = pdfDimension.getHeight();

float scale = (37000 / height) / 100;

float rotation = 0f;

// Paint each pages content to an image and write the image
// to file

BufferedImage image = (BufferedImage) document.getPageImage(0,
GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX,
rotation, scale);
RenderedImage rendImage = image;
// capture the page image to file
try {

File file = new File(request.getSession().getServletContext()
.getRealPath("/thumbnails")
+ File.separatorChar + fileName + ".png");

String absoluteFile2 = file.getAbsoluteFile().toString();
absoluteFile2 = absoluteFile2.replaceAll("bin", "");

file = new File(absoluteFile2);
file = file.getAbsoluteFile();
System.out.println("Generando: " + fileName + ".png");

ImageIO.write(rendImage, "png", file);

} catch (IOException e) {
e.printStackTrace();
}
image.flush();

// clean up resources
document.dispose();
}

}

IceSoft
0 comments

Posted in , ,

Using Liferay-ui:tabs

Example how use liferay-ui:tabs in a jsp:


<%
String tabs1 = ParamUtil.getString(request, "tabs1", "");

PortletURL portletURL = renderResponse.createRenderURL();
portletURL.setWindowState(WindowState.NORMAL);

portletURL.setParameter("tabs1", tabs1);

String tabNames = "Generales,Correo";
%>

<liferay-ui:tabs
names="Generales,Correo"
url="<%= portletURL.toString() %>"
/>

<c:if test='<%= tabs1.equals("Generales") || (tabs1.equals("")) %>'>

....Your code....

</c:if>

<c:if test='<%= tabs1.equals("Correo") %>'>

....Your code....

</c:if>

Using PortletPreferences in Liferay

How to saving a portlet preferences in liferay:

private PortletPreferences portletPreferences;
private String criterioBusca="Something";

portletPreferences.setValue("criterioBusca", criterioBusca);
portletPreferences.setValue("fecha", fecha);
portletPreferences.setValue("categoriaHistorico", categoriaHistorico);
portletPreferences.store();

Getting the values from preferences:

private String fecha = "";
fecha = portletPreferences.getValue("fecha", null);

DynamicQuery Liferay

Getting a list of TagsAsset using DynamicQuery


public List getTagsAsset(Date inicio, Date fin) {
List results = Collections
.synchronizedList(new ArrayList());

ClassLoader loader = PortalClassLoaderUtil.getClassLoader();

DynamicQueryFactory fc = DynamicQueryFactoryUtil
.getDynamicQueryFactory();

DynamicQuery dq0 = fc.forClass(TagsAsset.class, loader).add(
PropertyFactoryUtil.forName("groupId").eq(
PortalUtil.getScopeGroupId(request)))
.add(
PropertyFactoryUtil.forName("publishDate").between(
inicio, fin));

try {
results = TagsEntryLocalServiceUtil.dynamicQuery(dq0);
} catch (SystemException e) {
e.printStackTrace();
}
return results;
}

Design your iPhone app with Adobe Fireworks

Ajax Framework DWR

0 comments

Posted in ,