Get Journal Articles by Tags and Categories

Many a times we may require to display Journal articles by Tags or by categories. Here is the following API which will help you to get this List and you can display it in your own portlet.

 

 

public static List<JournalArticle> getArticleByTags(long groupId, String tagName)
throws PortalException, SystemException {
AssetEntryQuery assetEntryQuery = new AssetEntryQuery();
long[] anyTagIds = AssetTagLocalServiceUtil.getTagIds(groupId,
new String[] { “my-tag-name”, tagName });
assetEntryQuery.setAnyTagIds(anyTagIds);
List<AssetEntry> assetEntryList = AssetEntryLocalServiceUtil
.getEntries(assetEntryQuery);
List<JournalArticle> journalArticleList = new ArrayList<JournalArticle>();
for (AssetEntry ae : assetEntryList) {
JournalArticleResource journalArticleResourceObj = JournalArticleResourceLocalServiceUtil
.getJournalArticleResource(ae.getClassPK());
JournalArticle journalArticleObj = JournalArticleLocalServiceUtil
.getArticle(groupId,
journalArticleResourceObj.getArticleId());
journalArticleList.add(journalArticleObj);
}
return journalArticleList;
}

 

 

 

private static List<JournalArticle> getArticleByCategories(long groupId,
long categoryId)
throws PortalException, SystemException {

AssetEntryQuery assetEntryQuery = new AssetEntryQuery();
assetEntryQuery.setAnyCategoryIds(new long[] { categoryId });
List<AssetEntry> assetEntryList = AssetEntryLocalServiceUtil.getEntries(assetEntryQuery);
List<JournalArticle> journalArticleList = new ArrayList<JournalArticle>();

for (AssetEntry ae : assetEntryList) {
try {
JournalArticleResource journalArticleResourceObj = JournalArticleResourceLocalServiceUtil.getJournalArticleResource(ae.getClassPK());
JournalArticle journalArticleObj = JournalArticleLocalServiceUtil.getArticle(groupId,journalArticleResourceObj.getArticleId());

} catch (NoSuchArticleResourceException nse) {
_log.error(nse.getMessage());
}
}
return journalArticleList;
}

Create a Scheduler in Liferay 6

This blog will give an understanding on how  we can write a Scheduler to run a cron job for performing a background job on the portal. This scheduler can be used based on your business requirement.

Step 1 : Create a scheduler class in your portlet and specify the path in the liferay-portlet.xml

<portlet>
<portlet-name>myportlet</portlet-name>
<icon>/icon.png</icon>
<scheduler-entry>
<scheduler-description>
This scheduler is used to run my own job
</scheduler-description>
<scheduler-event-listener-class>com.portlet.myportlet.trigger.MyScheduler</scheduler-event-listener-class>
<trigger>
<!– <simple>
<simple-trigger-value>15</simple-trigger-value>
<time-unit>minute</time-unit>
</simple> –>
<cron>
<cron-trigger-value>0 0 0 * * ?</cron-trigger-value>
</cron>
</trigger>
</scheduler-entry>
</portlet>

 

This (<cron-trigger-value>0 0 0 * * ?</cron-trigger-value>) indicates that the scheduler will run every night at 00 hrs.

You can even have a simple scheduler running every hour,minute,seonds by specifying it as

 

<simple>
<simple-trigger-value>15</simple-trigger-value>
<time-unit>minute</time-unit>
</simple>

 

Step 2 : Create a Scheduler class.

The class name specified in the liferay-portlet.xml has to be same as scheduler class

import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageListener;
import com.liferay.portal.kernel.messaging.MessageListenerException;

public class MyScheduler implements MessageListener {

 public void receive(Message arg0) throws MessageListenerException {

//Here is the buisness logic to be written as per your requirement

System.out.println(“scheduler has been started”);

}

}

Based on the entry on the liferay-portlet.xml this will run accordingly.

Hope it helps

 

Webcontent for Email Template

Webcontent for Email Template
This blog will give you an understanding how the journalcontent can be used as a body of the
Email that you want to send as a Notification.

Follow this Steps

step 1:Create a journal Content as per your own requirement.(I name it as Email_Template)

step 2: Specify the name of the JournalArticle in portlet.properties file.So that any point of time you can change the name of the Journal as per your requirement

journal.Emailtemplate=Email_Template

Step 3: Use the following method to invoke the mail trigger which will send an Email with Journal Article

as the body of the email template.

/****** Method to get Journal content as template ******/

public static String getEmailTemplate(long groupId){
String emailTemplate=””;
JournalArticle jae = null;
try{
jae =JournalArticleLocalServiceUtil.getArticleByUrlTitle(groupId,GetterUtil.getString(PortletProps.get(“journal.Emailtemplate”)));
}catch(Exception e){ }

if(Validator.isNotNull(jae)) emailTemplate = jae.getContent();

}

/**************This method should be invoked with appropriate parameters specified  which will send email****/

public void sendMail(String toAddress,long groupId ){

String emailTemplate =””;

String fromAddress = “azam@gmail.com”;
String fromName =”Mohammed azam”;
String subject = “Invitaion for my group”;

emailTemplate  = getEmailTemplate(groupId);

try{
InternetAddress from=new InternetAddress(fromAddress,fromName);
InternetAddress to=new InternetAddress(toAddress,”unknown”);
MailMessage message = new MailMessage(from, to, subject, emailTemplate, true);
MailServiceUtil.sendEmail(message);
}
catch(Exception e){
e.printStackTrace();
}

}

Use the appropriate imports for the above piece of code.

import javax.mail.internet.InternetAddress;
import com.liferay.mail.service.MailServiceUtil;
import com.liferay.portal.kernel.mail.MailMessage;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portlet.journal.model.JournalArticle;
import com.liferay.portlet.journal.service.JournalArticleLocalServiceUtil;
import com.liferay.util.portlet.PortletProps;

Connect to different database through service.xml. Liferay6

Hi

Suppose you want to access datas from another database using liferay service.ml.

Then you can do this by the following steps.

  1. Create Service.xml
  2. Create ext-spring.xml file path /WEB-INF/src/META-INF/ext-spring.xml

Service.xml entry looks like this

<service-builder package-path=”com.test”>

    <author>azam</author>
<namespace>test</namespace>
<entity name=”Training” local-service=”true” table=”training” remote-service=”true” data-source=”myDatasource”>
<column name=”userId” type=”long” primary=”true”></column>
<column name=”firstName” type=”String”></column>
<column name=”lastName” type=”String”></column>
</entity></service-builder>

Run Build-service
Here we are telling the service.xml that this entity will use the userdefined datasource “myDatasource” instead of pointing it into liferay defaultdatasource.
this entry has to be created in the ext-spring.xml file

<?xml version=”1.0″?>

<beans xmlns=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; default-destroy-method=”destroy” default-init-method=”afterPropertiesSet” xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”&gt;
<bean id=”myDatasource” lazy-init=”true”  class=”org.springframework.jdbc.datasource.DriverManagerDataSource”>
<property name=”driverClassName” value=”com.mysql.jdbc.Driver” />
<property name=”url” value=”jdbc:mysql://localhost/training?useUnicode=true”/>
<property name=”username” value=”root” />
<property name=”password” value=”root” />
</bean>
<bean id=”liferayHibernateSessionFactory”   class=”com.liferay.portal.spring.hibernate.PortletHibernateConfiguration”>
<property name=”dataSource” ref=”myDatasource” />
</bean>
</beans>

Deploy the portlet
Now your portlet will fetch datas from different database table through the liferay service API.

Submiting the form using alloy-ui ajax

Well i was looking out to submit the form without refreshing the page in Liferay 6. I used Alloy to submit the form

Here is the code that i wrote in jsp file

<portlet:actionURL var=”ajaxURL” windowState=”<%= LiferayWindowState.EXCLUSIVE.toString()%>” />

<aui:script use=”aui-io-request,aui-node” >
Liferay.provide(
window,
‘submitForm’,
function() {
var A = AUI();
A.io.request(‘<%= ajaxURL %>’,{
method: ‘POST’,
form: { id: ‘<portlet:namespace />fm’ },
on: {
success: function(){
alert(“succefully submitted”);
}
}
});
});

</aui:script >

<form action=”<portlet:actionURL/>” method=”POST” id=”<portlet:namespace />fm” name=”<portlet:namespace />fm” >

<input type=”text” name=”<portlet:namespace />firstName”/>

<input type=”submit” value=”submit form”/>

 

Dynamic Query in Liferay6 plugin portlet

This blog is basically for the developers who are new to liferay and they find it difficult to use the dynamic query.

Many a times we may require a data which cannot be accessed by Liferay API.

Liferay provides several ways to define complex queries used in retrieving database data.

The solution is to use the dynamic query.Liferay provides access to Hibernate’s Dynamic Query API.

Advantages of using dynamic query

To perform operation like add,or,max, min,like. etc.
Optimising the query.
Minimal coding.
Accessing the complex data.

A sample queries.
Returning the whole list without restriction.

List results = new ArrayList();
DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(Library.class);
results.addAll(LibraryLocalServiceUtil.dynamicQuery(dynamicQuery));
The above query returns list of all Library objects.
Now to add restriction to our dynamic query.
Liferay provides util class called RestrictionsFactoryUtil where in it provides many api to add restictions to our query.
few API are   like, eq, ne , isNull, isNotnull etc.
Restriction is like where attribute what we write in SQL query eg: “select * from library where authorName=’james’;”.
DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(Library.class);
dynamicQuery.add(RestrictionsFactoryUtil.like(“bookName”, “java”));
dynamicQuery.add(RestrictionsFactoryUtil.eq(“author”, “james”));
List results = LibraryLocalServiceUtil.dynamicQuery(dynamicQuery);
The above query returns list of library objects whose author name is james and bookname is like “java”.
By using ProjectionFactoryUtil for dynamic query
The operations that can be performed using ProjectionFactoryUtil are avg,max,min, distinct etc.
DynamicQuery dynamicQuery=DynamicQueryFactoryUtil.forClass(Library.class,PortalClassLoaderUtil.getClassLoader());
dynamicQuery.setProjection(ProjectionFactoryUtil.max(“price”));
List results = LibraryLocalServiceUtil.dynamicQuery(dynamicQuery);
By using DetachedCriteria for the dynamic query.

The operations that can be performed using DetachedCriteria are add,addorder etc.
DetachedCriteria dCriteria = DetachedCriteria.forClass(Library.class);
dCriteria.add(Restrictions.eq(“bookname”, “java”));
dCriteria.addOrder(Order.desc(“price”));
DynamicQuery dynamicQuery = new DynamicQueryImpl(dCriteria);
List results = LibraryLocalServiceUtil.dynamicQuery(dynamicQuery);
The above query returns list of library objects whose bookname is java in a desc order of price.
The packages imports are given below use it appropriately
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
import com.liferay.portal.kernel.dao.orm.Projection;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.DetachedCriteria;
import com.liferay.portal.dao.orm.hibernate.DynamicQueryImpl;