Sunday, November 13, 2016

Fetching Tag Based Documents or Web Contents from Assets

Sometimes we will have the requirement like we need to fetch the documents which are specifically tagged with some tag name. Then no worries below code will help you to fetch the tag based documents from DLFile and also to fetch the tag based web content from Journal Article.

Java Code :-

String[] tagNames = {"get announcements"};

// Getting the ids of journalarticle and DLFille
 long[] requiredClassIds = {PortalUtil.getClassNameId(JournalArticle.class.getName()), PortalUtil.getClassNameId(DLFileEntry.class.getName())};

AssetEntryQuery assetEntryQuery = new AssetEntryQuery();
          assetEntryQuery.setAllTagIds(AssetTagLocalServiceUtil.getTagIds(groupId, tagNames));
         assetEntryQuery.setClassNameIds(requiredClassIds);

List assetEntryList = AssetEntryLocalServiceUtil.getEntries(assetEntryQuery);

for (AssetEntry ae : assetEntryList) {
      if(JournalArticle.class.getName().equalsIgnoreCase(ae.getClassName())){

           JournalArticle wc = JournalArticleLocalServiceUtil.getArticle(groupId, String.valueOf(ae.getClassPK() - 2));

             System.out.println("AnnouncementsPortlet : render : found web content name ::"+wc.getUrlTitle());

   } else if(DLFileEntry.class.getName().equalsIgnoreCase(ae.getClassName())){

    DLFileEntry dl =  DLFileEntryLocalServiceUtil.getDLFileEntry(ae.getClassPK());

    }

}

         

Monday, September 26, 2016

Multiple database connection in Liferay

Liferay allows us to connect to multiple database at the same time. Follow the below steps for that.

1. In portal-ext.properties file make a entry.

--------------------------------------------------------------------

// default entry for default database connection

jdbc.default.driverClassName=com.mysql.jdbc.Driver
jdbc.default.username=root
jdbc.default.password=root
jdbc.default.url=jdbc\:mysql\://localhost/defaultdb?useUnicode\=true&characterEncoding\=UTF-8&useFastDateParsing\=false

// new entries for external db connection it will be connected by giving a entry in ext-spring.xml

jdbc.external.driverClassName=com.mysql.jdbc.Driver
jdbc.external.username=root
jdbc.external.password=root
jdbc.external.url=jdbc:mysql://localhost/externaldb?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false

--------------------------------------------------------------------

2) As we are using service-builder, it means that you need new tables other than liferay default DB. So it requires for you to create new plugins project and in that you need to create service.xml under webapps/WEB-INF and with the help of ANT(ant build-service) or MAVEN (mvn liferay:build-service) you will able to create full structure for your service. But still it is pointing to the default DB. 

Note:- In externaldb you have to create tables manualy.


Now you need to create a new file ext-spring.xml under WEB-INF/src/META-INF dir. Inside META-INF folder you will find couple of xml files whose entry will be there in liferay portal.properties.If you notice the order of xml file loading in portal.properties file, then you will find that the last file is ext-spring.xml is loaded. So we will now create ext-spring.xml and putting all transaction,datasource and sessionfactory related changed on that file as below :-

--------------------------------------------------------------------
<?xml version="1.0"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<aop:config>
<aop:pointcut id="transactionOperation" expression="bean(*Service.impl)" />
<aop:advisor advice-ref="transactionAdvice" pointcut-ref="transactionOperation" />
</aop:config>

<bean id="basePersistence" abstract="true">
<property name="dataSource" ref="anotherDataSource" />
<property name="sessionFactory" ref="anotherSessionFactory" />
</bean>

<bean id="transactionAdvice" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="anotherTransactionManager" />
<property name="transactionAttributeSource">
<bean class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource">
<constructor-arg>
<bean class="com.liferay.portal.spring.annotation.PortalTransactionAnnotationParser" />
</constructor-arg>
</bean>
</property>
</bean>

<bean id="anotherHibernateSessionFactory" class="com.liferay.portal.spring.hibernate.PortletHibernateConfiguration" lazy-init="true">
<property name="dataSource" ref="anotherDataSource" />
</bean>

<bean id="anotherSessionFactory" class="com.liferay.portal.dao.orm.hibernate.SessionFactoryImpl" lazy-init="true">
<property name="sessionFactoryImplementor" ref="anotherHibernateSessionFactory" />
</bean>

<bean id="anotherTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" lazy-init="true">
<property name="dataSource" ref="anotherDataSource" />
<property name="globalRollbackOnParticipationFailure" value="false" />
<property name="sessionFactory" ref="anotherHibernateSessionFactory" />
</bean>

<bean id="anotherDataSource" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
<property name="targetDataSource">
<bean class="com.liferay.portal.dao.jdbc.util.DataSourceFactoryBean">
<property name="propertyPrefix" value="jdbc.external." />
</bean>
</property>      
    </bean>

</beans>

--------------------------------------------------------------

3) Now you need to modify the existing service.xml as follows :-

---------------------------------------------------------------------------

<service-builder package-path="com.external.liferay">
<namespace>external</namespace>
<entity data-source="anotherDataSource" local-service="true" name="externaldb" remote-service="false" session-factory="anotherSessionFactory" tx-manager="anotherTransactionManager">
......
......
</entity>
</service-builder>

---------------------------------------------------------


The data-source value specifies the data source target that is set to the persistence class. The default value is the Liferay data source. This is used in conjunction with session-factory. 

The session-factory value specifies the session factory that is set to the persistence class. The default value is the Liferay session factory. This is used in conjunction with data-source. 

The tx-manager value specifies the transaction manager that Spring uses. The default value is the Spring Hibernate transaction manager that wraps the Liferay data source and session factory. 

If the local-service value is true, then the service will generate the local interfaces for the service. The default value is false.

If the remote-service value is true, then the service will generate remote interfaces for the service. The default value is true.

You can use the local-service and remote-service attribute according to your needs.











Sunday, June 12, 2016

Friendly URL in Liferay

Hi we have one of the beautiful concept is friendly URL in Liferay.

Suppose if we have URL like this in every render URL of Liferay.:-

http://localhost:8080/web/guest/home?p_p_id=mydetails_WAR_mydetailsportlet&p_p_lifecycle=0&p_p_state=normal&p_p_mode=view&p_p_col_id=column-2&p_p_col_pos=1&p_p_col_count=3&_mydetails_WAR_mydetailsportlet_mvcPath=%2Fhtml%2Fmypath%2Fmydetails.jsp
The following are the General Parameters and its values in Portlet URL
p_p_id: current portlet id
p_p_state: window sate
p_p_mode: portlet mode either view/edit
p_p_lifecycle: this is life cycle of portlet  0/1/2
0: render phase or render URL
1: action phase or action URL
2: server resource URL

We can generate friendly URL like below :-

http://localhost:8080/web/guest/home/-/mydetails/addmydetails
(i)   Friendly url when we access jsp pages(rendering from one jsp to another).
(ii)  Friendly Url when we call action url.
(iii) Friendly Url when we call action url passing parameter(Id).

Friendly URL Implementation
  1. Configure URL routes in xml file
  2. Friendly URL Implementation Java class
  3. Configure the Friendly URL information in liferay-portlet.xml file.

-----------------------------------------------------------------------------------------------------------------

Create one liferay plugin project name as per your requirement, in our case it's Mydetails plugin project with Mydetails portlet

Step 1 : Paste below code in mypage.jsp

<%@page import="com.liferay.portal.kernel.util.ParamUtil"%>

<%@page import="javax.portlet.PortletURL"%>

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

<portlet:defineObjects />

<%

long mydetaiId = 123;

PortletURL addMydetailsURL = renderResponse.createRenderURL();

addMydetailsURL.setParameter("jspPage", "/html/crud/addmydetails.jsp");


PortletURL editMydetailsURL = renderResponse.createActionURL();

editMydetailsURL.setParameter("mydetaiId", Long.toString(mydetaiId));

editMydetailsURL.setParameter(actionRequest.ACTION_NAME, "editMydetails");

%>

<p style="border:1px solid green;">Friendly Url Implementation. </p>
<a href="<%=addMydetailsURL.toString()%>">Add Details</a>
<a href="<%=editMydetailsURL.toString()%>" >Edit Details</a>


Step 2 :    create one jsp page addmydetails.jsp and paste below code.


<%@page import="javax.portlet.PortletURL"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />

<%
PortletURL  addMydetailsActionURL = renderResponse.createActionURL();
addMydetailsActionURL.setParameter(actionRequest.ACTION_NAME, "addMydetails");
%>

<h1> Add Details</h1>

<form action="<%=addMydetailsActionURL.toString()%>"  method="POST">
My Details Id<br/>
<input  type="text" name="<portlet:namespace/>mydetailsId" value=""/><br/>
My Name<br/>
<input type="text" name="<portlet:namespace/>myname" value=""/><br/>
<input type="submit" value="Add My Details"/>
</form>
Step 3 :-

Add below tags with mentioned value liferay-portlet.xml 


<friendly-url-mapper-class>com.liferay.portal.kernel.portlet.DefaultFriendlyURLMapper</friendly-url-mapper-class> <friendly-url-mapping>myFriendlyUrl</friendly-url-mapping> <friendly-url-routes>com/test/routes.xml</friendly-url-routes> 


 <?xml version="1.0"?>
<!DOCTYPE liferay-portlet-app PUBLIC "-//Liferay//DTD Portlet Application 6.2.0//EN" "http://www.liferay.com/dtd/liferay-portlet-app_6_2_0.dtd">

<liferay-portlet-app>
    
    <portlet>
        <portlet-name>my-details</portlet-name>
        <icon>/icon.png</icon>
<friendly-url-mapper-class>com.liferay.portal.kernel.portlet.DefaultFriendlyURLMapper</friendly-url-mapper-class>
      <friendly-url-mapping>myFriendlyUrl</friendly-url-mapping>
<friendly-url-routes>com/myxml/routes.xml</friendly-url-routes>
        <header-portlet-css>/css/main.css</header-portlet-css>
        <footer-portlet-javascript>
            /js/main.js
        </footer-portlet-javascript>
        <css-class-wrapper>my-details-portlet</css-class-wrapper>
    </portlet>
    <role-mapper>
        <role-name>administrator</role-name>
        <role-link>Administrator</role-link>
    </role-mapper>
    <role-mapper>
        <role-name>guest</role-name>
        <role-link>Guest</role-link>
    </role-mapper>
    <role-mapper>
        <role-name>power-user</role-name>
        <role-link>Power User</role-link>
    </role-mapper>
    <role-mapper>
        <role-name>user</role-name>
        <role-link>User</role-link>
    </role-mapper>
</liferay-portlet-app>
Step 4: create one xml file inside /web-inf/src/com/myxml folder with name routes.xml and paste below code.


  <?xml version="1.0"?>

<!DOCTYPE routes PUBLIC "-//Liferay//DTD Friendly URL Routes 6.2.0//EN" 

"http://www.liferay.com/dtd/liferay-friendly-url-routes_6_2_0.dtd">

<routes>

 <!-- Friendly url when we access jsp pages(rendering from one jsp to another) -->

 <route>

     <pattern>/page/{jspPageName}>/pattern>

     <generated-parameter name="jspPage">/html/crud/{jspPageName}.jsp>/generated-parameter>

 </route>

<!-- Friendly Url when we call action url -->

 <route>

     <pattern>/action/{actionName}>/pattern>

     <generated-parameter name="javax.portlet.action">{actionName}>/generated-parameter>

     <ignored-parameter name="p_auth"/>

     <ignored-parameter name="p_p_id"/>

     <implicit-parameter name="p_p_lifecycle">1>/implicit-parameter>

     <implicit-parameter name="p_p_state">normal>/implicit-parameter>

     <implicit-parameter name="p_p_mode">view>/implicit-parameter>

 </route>

    

 <!-- Friendly Url when we call action url passing parameter(Id)-->

  <route>

     <pattern>/action/{actionName}/mydetailsId/{mydetaiId:\d+}>/pattern>

     <generated-parameter name="javax.portlet.action">{actionName}>/generated-parameter>

     <generated-parameter name="mydetaiId">{mydetaiId}>/generated-parameter>

     <ignored-parameter name="p_auth"/>

     <ignored-parameter name="p_p_id"/>

     <implicit-parameter name="p_p_lifecycle">1>/implicit-parameter>

     <implicit-parameter name="p_p_state">normal>/implicit-parameter>

     <implicit-parameter name="p_p_mode">view>/implicit-parameter>

  </route>
</routes>  
Step 5:  Paste below code in java class Mydetails.java


package com.mypath;

import java.io.IOException;

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

import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * Portlet implementation class Mydetails
 */
public class Mydetails extends MVCPortlet {
 
 public void addmydetails(ActionRequest actionRequest,
   ActionResponse actionResponse) throws IOException, PortletException {
   
  System.out.println("inside addmydetails...");
 }
 
 public void editmydetails(ActionRequest actionRequest,
   ActionResponse actionResponse) throws IOException, PortletException {
   
  System.out.println("inside editmydetails...");
  } 
} 


Tuesday, January 5, 2016

Custom Font in Liferay Theme

Note :- Whenever you want to use a custom font in liferay theme , import that particular custom font from '.vm' file rather than using from css file ,if  you import from css file then the changes will not reflect in 'IE' browser

Sunday, December 13, 2015

Getting current page URL in VM file liferay

The below example will help you to fetch the current URL of the page by using Group and display different images based upong the URL. 

<div id="nav" class="nav">
#set ($groupService = $serviceLocator.findService("com.liferay.portal.service.GroupLocalService"))
#set ($group = $groupService.getGroup($getterUtil.getLong($group_id)))
#set ($groupurl = $group.getFriendlyURL())
#set ($groupurl2 = "/web"+$groupurl+"/my-account" )
#set ($groupurl3 = "/web"+$groupurl+"/my-profile" )

#if ($is_signed_in)

#if ($theme_display.getURLCurrent().contains($groupurl2))

#else
<a href="/web$groupurl/my-account">
<img alt="$logo_description" src="$images_folder/mts/myaccount.png" width="100%" />
</a>
#end

#if ($theme_display.getURLCurrent().contains($groupurl3))

#else
<a href="/web$groupurl/my-profile">
<img alt="$logo_description" src="$images_folder/mts/myprofile.png" width="100%" />
</a>
#end

#end
</div>

Monday, July 6, 2015

Reading the parameters from URL in Liferay

In Liferay some times we will face an issue to read the parameters from the URL (it may be actionURL or renderURL), it will give null value when you try to read the parameters with simple 'actionRequest' or 'renderRequest' in such scenario we need to read the parameters from the 'OriginalServletRequest'. the below example clearly shows how to read those parameters.

imports :-
import javax.servlet.http.HttpServletRequest;
import com.liferay.portal.util.PortalUtil;
import javax.portlet.ActionRequest;

java code :-

HttpServletRequest originalRequest  = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(actionRequest));

String STATUS = originalRequest.getParameter("STATUS");

//actionRequest for action method and renderRequest for rendermethod.

jsp code :- suppose you need to read in your jsp page then read the parameter in the following way.

HttpServletRequest originalRequest  = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(renderRequest));

String STATUS = originalRequest.getParameter("STATUS");

Note:- Suppose we are reading the parameters from the URL which are passing by any third party server(ex: payment gateways) in such type of scenarios, we need to read the parameters in the above way.

Locale message in javascript of .jsp and in .js

As continue to my previous blog, sometimes we get requirement to display locale message in 'Notifications' or 'Alerts'. It is easy to diplay in jsp page in labels but how to display in alerts then the below is an example which will help you on this type of requirement.

example :-
.jsp code :-
 
function modeAlert(){
        alert("<liferay-ui:message key="payment"/>");
    }

.js code :- 

 Liferay.Language.get('key');

--------------------------------------------------------------------------

Path for Language properties file :-  src/content/Language_en_US.properties

Language_en_US.properties :-  ex: (Key : Vlaue)
  
  payment: Payment 

Language_ms_MY.properties :-  ex: (Key : Vlaue)

  payment: Pembayaran

When ever you use the above key(first way or second way) depending upon the current locale the value will be diplayed.

WEB-INF/Portlet.xml :- The entry in the portlet.xml is also mandatory then only you can able to see the values otherwise you can see only key as output.

<portlet>
<portlet-name>request</portlet-name>
<display-name>Request</display-name>
<portlet-class>com.Request</portlet-class>
<init-param>
</init-param>
<supports>
</supports>
<supported-locale>en_US</supported-locale>
<supported-locale>ms_MY</supported-locale>
<resource-bundle>content.Language</resource-bundle>
<portlet-info>
  </portlet-info>
 </portlet>

Liferay DXP JNDI Data Source Cofiguration

 This Blog will help us to learn about the JNDI Data Source Configuration in Liferay DXP. We have tested this with Liferay 7.3 with Tomcat. ...