Showing posts with label Liferay. Show all posts
Showing posts with label Liferay. Show all posts

Friday, 28 August 2015

Using the "liferay-ui:input-date" tag

Just a simple example to use the liferay-ui:input-date tag in our forms.

1. Firtly we need to import the required tag.
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>

2. If you need to show the default selected date as Today. We need a Calendar object to get these values for our form.
<%
// To set today's date as default for the calendar.
Calendar today = Calendar.getInstance();
%>

3. Now for the actual form. The Liferay UI Date element is created here with the necessary parameters.
<label>
    Date of Birth
    <liferay-ui:input-date name="dobDate" 
        dayValue="<%= today.get(Calendar.DAY_OF_MONTH) %>" dayParam="dobDay"
        monthValue="<%= today.get(Calendar.MONTH) %>" monthParam="dobMonth"
        yearValue="<%= today.get(Calendar.YEAR) %>" yearParam="dobYear" />
</label>
The dayValue, monthValue and yearValue attributes are displayed to the user as soon as the form is loaded.
dayParam, monthParam and yearParam are the attributes representing the data when it is sent to the server side.
I have also set the name attribute which will send the selected date in MM/dd/yyyy format to the server.

4. Now for the server side, to retrieve the data from the user. This is the first way to fetch the data, below I have provided another way to do the same.
// Method 1
// We can fetch the date either by separate Day, Month and Year parameter.
int dobDay = ParamUtil.getInteger(actionRequest, "dobDay");
int dobMonth = ParamUtil.getInteger(actionRequest, "dobMonth");
int dobYear = ParamUtil.getInteger(actionRequest, "dobYear");

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, dobDay);
calendar.set(Calendar.MONTH, dobMonth);
calendar.set(Calendar.YEAR, dobYear);

System.out.println("Method 1: " + calendar.getTime());
In our Portlet class, the dobDay, dobMonth and dobYear will provide the Day, Month and Year respectively. We can set this to a Calendar object and retrieve the Date object with the calendar.getTime() method.

5. Now for method 2.
// Method 2
// With the input String from the selected date.
try {
    String dobDateString = ParamUtil.getString(actionRequest, "dobDate");
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    Date dobDate = sdf.parse(dobDateString);

    System.out.println("Method 2: " + dobDate);
}
catch (ParseException pe) {
    pe.printStackTrace();
}
Here we'll use the name parameter to fetch the same value. Using the SimpleDateFormat to parse the string we can retrieve the Date object.

Please find attached the entire source for the same in the below link.
calendar-portlet.zip

Hope all of this makes sense.

Saturday, 8 August 2015

Setting up Liferay mail server with Gmail

To setup Liferay with Gmail to send mail to users. (Eg. When they register, forget their password, etc.) We need to configure the Mail server setting in the Control Panel.

Firstly, Liferay is considered as a Less secure app in Gmail. To allow Liferay to use Gmail as a mail server, we need to enable the feature. Below link is from Google Support that shows how to enable this feature. It is as simple as selecting a radio button.
Gmail Support - Allowing less secure apps to access your account

Now continuing with the configuration. Go to
Control Panel -> Server Administration -> Mail
Here we need to fill details for the Outgoing SMTP Server to send mail from Liferay.

SMTP settings for Gmail can be found in the below page.
Google Apps SMTP settings to send mail from a printer, scanner, or app

Here's how to use the settings in liferay:

Outgoing SMTP Server: smtp.gmail.com
Outgoing Port: 465
Use a Secure Network Connection: Checked
User Name: Your Gmail Mail ID
Password: Your Gmail password

Save the settings and you're done.

Below is a screenshot of my mail settings for reference.

Thursday, 4 June 2015

Modifying Liferay Database Connection


Example of the connection to MySQL Database
jdbc.default.driverClassName=com.mysql.jdbc.Driver
jdbc.default.url=jdbc:mysql://localhost/lportal?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false
jdbc.default.username=gautham
jdbc.default.password=passw0rd

The username and Password is common for all the connections and has to be set.
jdbc.default.username=
jdbc.default.password=

Below is the list of Databases that liferay can connect to. Use the appropriate properties for your database.
DB2
jdbc.default.driverClassName=com.ibm.db2.jcc.DB2Driver
jdbc.default.url=jdbc:db2://localhost:50000/lportal:deferPrepares=false;fullyMaterializeInputStreams=true;fullyMaterializeLobData=true;progresssiveLocators=2;progressiveStreaming=2;
Derby
jdbc.default.driverClassName=org.apache.derby.jdbc.EmbeddedDriver
jdbc.default.url=jdbc:derby:lportal
Hypersonic
jdbc.default.driverClassName=org.hsqldb.jdbcDriver
jdbc.default.url=jdbc:hsqldb:${liferay.home}/data/hsql/lportal
Ingres
jdbc.default.driverClassName=com.ingres.jdbc.IngresDriver
jdbc.default.url=jdbc:ingres://localhost:II7/lportal
MySQL
jdbc.default.driverClassName=com.mysql.jdbc.Driver
jdbc.default.url=jdbc:mysql://localhost/lportal?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false
Oracle
jdbc.default.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.default.url=jdbc:oracle:thin:@localhost:1521:xe
P6Spy
jdbc.default.driverClassName=com.p6spy.engine.spy.P6SpyDriver
jdbc.default.url=jdbc:mysql://localhost/lportal?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false
PosgreSQL
jdbc.default.driverClassName=org.postgresql.Driver
jdbc.default.url=jdbc:postgresql://localhost:5432/lportal
SQL Server
jdbc.default.driverClassName=net.sourceforge.jtds.jdbc.Driver
jdbc.default.url=jdbc:jtds:sqlserver://localhost/lportal
Sybase
jdbc.default.driverClassName=net.sourceforge.jtds.jdbc.Driver
jdbc.default.url=jdbc:jtds:sybase://localhost:5000/lportal

All the above details are available in the portal.properties file.
Search for "# MySQL" to find MySQL connection properties. Similarly you can search for your own database name to get the properties.

Feel free to post a comment.

Sunday, 31 May 2015

Liferay, Reset Admin password.

If you forget or lose your Liferay Admin user and have access to your Liferay Schema / Database, you can execute the below query to reset your password.

Note: You will have to restart the server for the changes to take place.
UPDATE 
  user_ 
SET 
  password_ = '1234',
  passwordEncrypted = '0',
  passwordReset = '1',
  status = 0 
WHERE 
  emailaddress = 'test@liferay.com';
password_ is the new password that you are setting. You can use this to log in with the Admin credentials.
emailaddress should be the email Address of the Admin User.

Hope this worked for you. Do post a comment if you face any issues.

Wednesday, 12 November 2014

Liferay Search Container

The below is the complete code to display the list of Users. Explanation of the code is given below.
<%@page import="com.liferay.portal.kernel.util.ListUtil"%>
<%@page import="com.liferay.portal.service.UserLocalServiceUtil"%>
<%@page import="com.liferay.portal.model.User"%>

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.List"%>

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

<portlet:defineObjects />

<%
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
%>

<liferay-ui:search-container delta="5" var="usersContainer"
 emptyResultsMessage="No Data to Display." >
 
 <%
 List<User> users = UserLocalServiceUtil.getUsers(-1, -1);
 List<User> usersResults = ListUtil.subList(
  users, usersContainer.getStart(), usersContainer.getEnd());
 
 int totalUsers = UserLocalServiceUtil.getUsersCount();
 %>
 
 <liferay-ui:search-container-results results="<%= usersResults %>" 
  total="<%= totalUsers %>" />
 
 <liferay-ui:search-container-row className="com.liferay.portal.model.User" 
  keyProperty="userId" modelVar="user">
  
  <liferay-ui:search-container-column-text name="User ID" 
   property="userId" />
  
  <liferay-ui:search-container-column-text name="First Name"
   property="firstName" />
  
  <liferay-ui:search-container-column-text name="Email Address"
   property="emailAddress" />
  
  <liferay-ui:search-container-column-text name="Created Date"
   value="<%= sdf.format(user.getCreateDate()) %>" />
  
 </liferay-ui:search-container-row>
 
 <liferay-ui:search-iterator paginate="true" />
 
</liferay-ui:search-container>

The SimpleDateFormat is used to format the Created Date column that we will be showing in the Search Container.
<%
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
%>

The <liferay-ui:search-container> Tag, initializes the Search Container. Note the usersContainer variable name that has been assigned to it. This will be used to get the Start and End position of the Search Container.
<liferay-ui:search-container delta="5" var="usersContainer"
 emptyResultsMessage="No Data to Display." >

The list of Users present in liferay is retrieved. ListUtil.subList picks out only the Users that have to be displayed in the Search Container based on the usersContainer.getStart() and usersContainer.getEnd() position.
<%
List<User> users = UserLocalServiceUtil.getUsers(-1, -1);
List<User> usersResults = ListUtil.subList(
 users, usersContainer.getStart(), usersContainer.getEnd());

int totalUsers = UserLocalServiceUtil.getUsersCount();
%>

The list and total number of users present in Liferay is assigned to the <liferay-ui:search-container-results> tag.
<liferay-ui:search-container-results results="<%= usersResults %>" 
 total="<%= totalUsers %>" />

Create a <liferay-ui:search-container-row> which will contain the Columns and display the Data to the User.
<liferay-ui:search-container-row className="com.liferay.portal.model.User" 
 keyProperty="userId" modelVar="user">

Now to select what data to be displayed to the User. The Columns that need to be displayed are specified below. I have selected the User ID, First Name, Email Address and Created Date. The property represents the name given in the Service Builder. This is the variable name present in the User Class.
<liferay-ui:search-container-column-text name="User ID" 
 property="userId" />

<liferay-ui:search-container-column-text name="First Name"
 property="firstName" />

<liferay-ui:search-container-column-text name="Email Address"
 property="emailAddress" />

<liferay-ui:search-container-column-text name="Created Date"
 value="<%= sdf.format(user.getCreateDate()) %>" />

The Iterator Tag is Required. Without it, the Search container will not work as expected.
<liferay-ui:search-iterator paginate="true" />

Tuesday, 23 September 2014

Importing Liferay Projects of Different Versions

Let's say we have a Liferay project developed in Liferay version 6.1.1 and you need to import the project in Liferay 6.1.3.
Things that need to be changed are:
  1. The licenses and liferay-version properties in the liferay-plugin-package.properties file.
  2. You may have to change few classes or methods that may not be available in the new/old version.
I have a Liferay CE v6.1.1 portlet that needs to be imported in Liferay EE v6.1.3. In the <portlet>/WEB_INF/liferay-plugin-package.properties file, we find the below properties.
licenses=LGPL
liferay-versions=6.1.1

To import the project in your Liferay IDE, easiest way is to open up the <portlet>/WEB_INF/liferay-plugin-package.properties file from an existing portlet and copy values of licenses and liferay-versions properties to the project that needs to be imported.
I'm using Liferay EE v6.1.3 and found the below values:
licenses=EE
liferay-versions=6.1.20+
We'll have to update the values in the portlet that has to be imported.
Feel free to post Comments.

Monday, 22 September 2014

Liferay 6.1, resolving SASS: Invalid CSS Error

I found this error when using Bootstrap in my Liferay 6.1 CE theme. Every time a page loads with the theme, a huge error log was created with SASS Exception. This is the solution that worked for me.

1. Download the below file and Replace the file in liferay-portal-6.1.1-ce-ga2\tomcat-7.0.27\webapps\ROOT\WEB-INF\lib folder.
ruby-gems.jar

2. Add the following lines to your portal-ext.properties file
scripting.jruby.load.paths=\
  classpath:/META-INF/jruby.home/lib/ruby/site_ruby/1.8,\
  classpath:/META-INF/jruby.home/lib/ruby/site_ruby/shared,\
  classpath:/gems/chunky_png-1.2.6/lib,\
  classpath:/gems/compass-0.12.2/lib,\
  classpath:/gems/fssm-0.2.9/lib,\
  classpath:/gems/sass-3.2.1/lib,\
  ${java.io.tmpdir}/liferay/ruby/gems/chunky_png-1.2.6/lib,\
  ${java.io.tmpdir}/liferay/ruby/gems/compass-0.12.2/lib,\
  ${java.io.tmpdir}/liferay/ruby/gems/fssm-0.2.9/lib,\
  ${java.io.tmpdir}/liferay/ruby/gems/sass-3.2.1/lib

Restart the server and all SASS errors will have disappeared.
If it still hasn't gone, you might have to stop Liferay, clean the liferay-portal-6.1.1-ce-ga2\tomcat-7.0.27\temp, liferay-portal-6.1.1-ce-ga2\tomcat-7.0.27\work and C:\Users\{YOUR.USER.NAME}\AppData\Local\Temp directories and Start the Liferay server.

Credits go to Kan Zhang for the info. Link to Original Post below:
Resolve the "Sass::SyntaxError: Invalid CSS" error in Liferay 6.1

Wednesday, 17 September 2014

Liferay, Display Docbar based on User Role

Firstly go to Control Panel > Roles and create a Role Dockbar. This is the Name that will be used to check if the Dockbar has to be displayed to the User.

In the portal_normal.vm file, present in the theme, we have to modify the below lines. Right now, dockbar is visible to anybody who signs in. We need to change it so that it is visible to users with a specific role.
#if ($is_signed_in)
 #dockbar()
#end
This makes the com.liferay.portal.service.UserService available in the Velocity Template. It is assigned to the $userService variable.
#set($userService = $serviceLocator.findService("com.liferay.portal.service.UserService"))
This line Calls the hasRoleUser method, to check if the user has the Role Dockbar assigned to him.
#set($docbarVisible = $userService.hasRoleUser($company_id, "Dockbar", $user_id, true))
The below line checks if the user is Signed In AND has the role Dockbar OR if the User is the Company Admin.
#if ($is_signed_in && ($docbarVisible || $permissionChecker.isCompanyAdmin()))
Final Code
#set($userService = $serviceLocator.findService("com.liferay.portal.service.UserService"))
#set($docbarVisible = $userService.hasRoleUser($company_id, "Dockbar", $user_id, true))

#if ($is_signed_in && ($docbarVisible || $permissionChecker.isCompanyAdmin()))
 #dockbar()
#end
Now all that is left out is to assign few users the Dockbar role to verify that the Users will have access to the Dockbar. Hope the entire thing makes sense.
Feel free to post your comments.

Wednesday, 28 May 2014

Setting the Initial Text of Liferay UI Input Editor

Include the below line at the top of the page to access the liferay-ui elements.
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
The below line adds the Text Editor to the page.
<liferay-ui:input-editor initmethod="initDefaultMessage" name="textEditor" ></liferay-ui:input-editor>
This code adds content that as soon as the editor is initialized.
Note the <portlet:namespace /> tag in the function name.
<script type="text/javascript">
function <portlet:namespace />initDefaultMessage() {
    return 'Text to test';
}
</script>

Wednesday, 26 February 2014

Hide Liferay Default Messages

Liferay by default displays a Success or Error message when a form is submitted.
If you wish to hide the default message that Liferay displays when a form is submitted, add the below lines of code to your Methods in your Portlet Class.

For Liferay 6.1 & below, both messages are hidden with the line of code below.
SessionMessages.add(actionRequest, PortalUtil.getPortletId(actionRequest) + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);

For Liferay 6.2, we have to hide Success as well as Error Messages separately.
// Hide default Success Message
SessionMessages.add(actionRequest, PortalUtil.getPortletId(actionRequest) + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_SUCCESS_MESSAGE);

// Hide default Error Message
SessionMessages.add(actionRequest, PortalUtil.getPortletId(actionRequest) + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);
OR
We can add the below lines to the portlet.xml file to remove all such messages from our portlet.
<init-param>
  <name>add-process-action-success-action</name>
  <value>false</value>
</init-param>

Comments / suggestions are always welcome.