Tuesday 29 December 2015

Employee custom portlet Example

init.jsp

<%@taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui" %>
<%@ taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
<%@taglib uri="http://liferay.com/tld/theme" prefix="theme" %>
<%@taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@page import="java.util.List"%>
<%@page import="com.liferay.portal.kernel.util.ListUtil"%>
<%@page import="com.liferay.arav.service.aravLocalServiceUtil"%>
<%@page import="com.liferay.arav.model.arav"%>
<%@page import="com.liferay.arav.model.impl.aravImpl"%>
<theme:defineObjects></theme:defineObjects>

add.jsp
<%@ include file="/html/arav/init.jsp" %>
<portlet:actionURL var="addActionURL" name="employeeDetails">
<portlet:param name="action" value="employee"/>
</portlet:actionURL>
<aui:form action="<%= addActionURL %>" method="post" name="sub">
<aui:input name="name" type="text"></aui:input>
<aui:select multiple="false" name="designation">
<aui:option value="developer">Developer</aui:option>
<aui:option value="tester">Tester</aui:option>
<aui:option value="manager">Manager</aui:option>
</aui:select></br>
<b>dateofbirth</b></br>
<liferay-ui:input-date formName="dob" yearRangeEnd="2000" yearRangeStart="1950"
yearValue="1990" monthValue="3" dayValue="20" dayParam="d1" monthParam="m1"
yearParam="y1">
</liferay-ui:input-date></br></br>
<aui:button type="submit" value="Add Employee"></aui:button>
<a href="<portlet:renderURL/>">&laquo; Go Back</a>
</aui:form>view.jsp
<%@ include file="/html/arav/init.jsp" %>
<portlet:renderURL var="employeeURL">
<portlet:param name="jspPage" value="/html/arav/add.jsp"></portlet:param>
</portlet:renderURL>
<portlet:renderURL var="listEmployeeURL" >
<portlet:param name="jspPage" value="/html/arav/list.jsp"></portlet:param>
</portlet:renderURL>
<aui:a href="<%= employeeURL %>"><b>ADD EMPLOYEE DETAILS</b></aui:a>
<aui:a href="<%= listEmployeeURL %>"><b>EMPLOYEE DETAILS</b></aui:a>
list.jsp
<%@ include file="/html/arav/init.jsp" %>
<%
List<arav> list = aravLocalServiceUtil.getaravs(-1, -1); %>
<liferay-ui:search-container delta="10" emptyResultsMessage="No
Employee details available">
<liferay-ui:search-container-results results="<%=
ListUtil.subList(list, searchContainer.getStart(),searchContainer.getEnd()) %>"
total="<%= list.size() %>" />
<liferay-ui:search-container-row
className="com.liferay.arav.model.arav"
modelVar="aravinth">
<liferay-ui:search-container-column-text property=
"name" />
<liferay-ui:search-container-column-text property="designation" />
<liferay-ui:search-container-column-text property="dob" />
<liferay-ui:search-container-column-text property="age" />
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
<a href="<portlet:renderURL/>">&laquo; Go Back</a>ACTION.JAVA
package com.liferay.arav;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import com.liferay.arav.model.arav;
import com.liferay.arav.model.impl.aravImpl;
import com.liferay.arav.service.aravLocalServiceUtil;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class aravAction
*/
public class aravAction extends MVCPortlet {
public void employeeDetails (ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException {
String name = ParamUtil.getString(actionRequest, "name");
String designation = ParamUtil.getString(actionRequest, "designation");
System.out.println(name);
System.out.println(designation);
String date=ParamUtil.getString(actionRequest,"d1");
System.out.println(date);
Integer month=ParamUtil.getInteger(actionRequest,"m1")+1;
System.out.println(month);
String year=ParamUtil.getString(actionRequest,"y1");
System.out.println(year);
String mo=month.toString();
String a=date+"/"+mo+"/"+year;
Date ar=new Date(a);
System.out.println(a);
ThemeDisplay themedisplay = (ThemeDisplay)
actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
arav arav = new aravImpl();
long aravId = 0l;
arav.setName(name);
arav.setDesignation(designation);
arav.setDob(ar);
Calendar cal=Calendar.getInstance();
int currentyear=cal.get(Calendar.YEAR);
int birthyear=ParamUtil.getInteger(actionRequest,"y1");
long age=currentyear-birthyear;
System.out.println(age);
arav.setAge(age);
try {aravId = CounterLocalServiceUtil.increment (arav.class.getName());
arav.setAravId(aravId);
aravLocalServiceUtil.addarav(arav);
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
service.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 6.1.0//EN"
"http://www.liferay.com/dtd/liferay-service-builder_6_1_0.dtd">
<service-builder package-path="com.liferay.arav">
<author>esquare2</author>
<namespace>arav</namespace>
<entity name="arav" local-service="true" remote-service="false">
<!-- PK fields -->
<column name="aravId" type="long" primary="true" />
<!-- Audit fields -->
<column name="companyId" type="long" />
<column name="userId" type="long" />
<column name="userName" type="String" />
<column name="createDate" type="Date" />
<column name="modifiedDate" type="Date" />
<!-- Other fields -->
<column name="name" type="String" />
<column name="designation" type="String" />
<column name="dob" type="Date" />
<column name="age" type="long" />
<!-- Order -->
<order by="desc">
<order-column name="dob" />
</order>
<!-- Finder methods >
<finder name="Field2" return-type="Collection">
<finder-column name="field2" />
</finder> -->
</entity>
</service-builder>

Assign roles programmatically

 Role role = RoleLocalServiceUtil.getRole(company.getCompanyId(), usery[0]);
         UserLocalServiceUtil.addRoleUser(role.getRoleId(), user.getUserId());
         UserLocalServiceUtil.updateUser(user);

Sunday 27 December 2015

AUI Select Option disable

<option selected disabled hidden value=''>--select brand--</option>

<aui:select label="Brand" helpMessage="Choose your brand" name="brandOrgId" >
<option selected disabled hidden value=''>--select brand--</option>
<option value='1'>1</option>
<option value='2'>2</option>
</aui:select>

Date Picker

AUI Date Picker:

To Use AUI we need to import

<%@ taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui"%>

Then add your input field:

<aui:input type="text" name="datepicker" id="datepicker" />

Then add this script:
<aui:script>
AUI().use('aui-datepicker', function(A) {
new A.DatePicker({
trigger : '#<portlet:namespace/>datepicker',
popover : {
zIndex : 1
}
});
});
</aui:script>


Liferay UI DatePicker:

We need to import:
<%@taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>

Then add your input field
<liferay-ui:input-date formName="dob" yearRangeEnd="2000" yearRangeStart="1950"
yearValue="1990" monthValue="3" dayValue="20" dayParam="d1" monthParam="m1"
yearParam="y1"/>


Jquery DatePicker:

To Use Jquery Date Picker we need to import

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">


Then add your input field
   <input type="text" id="datepicker">

Then add this script:
  <script>
  $(function() {
    $( "#datepicker" ).datepicker();
  });
  </script>

Corrency symbol for all country

Code to get currency symbol:

    Currency currency = null;
    Locale locale = null;
    String currencySymbol = null;
  /*Get List of available countries from liferay country table*/
    List<Country> countryCode = CountryServiceUtil.getCountries();
   
    for(Country country:countryCode)
    {
        try{
            locale = new Locale.Builder().setRegion(country.getA2()).build();
            currency = Currency.getInstance(locale);   
               currencySymbol = currency.getSymbol(locale);
              System.out.println("currency symbol is......"+currencySymbol);}
        catch(Exception e){
            System.out.println("exception..."+e);
        }
    }

Validator class

Validator class(com.liferay.portal.kernel.util.Validator) provides us some utility methods to validate data and to check format of data.

Most frequently methods are:

Validator.isNotNull(String s)
Validator.isNull(String s)

And Instead of String we can also use long value,object,array,etc..

Ex:
String countryName = "India";
if(Validator.isNotNull(countryName))
System.out.println("country name is ****"+countryName);

Validator.equals(char c1,char c2)

And Instead of char we can use double,boolean Values

Ex:
char c1 = 'a';
char c2 = 'a';
if(Validator.equals(c1,c2))
System.out.println("c1 and c2 are equal");

And also we have many important methods to validate url,uri,number,password,email address,phone numbers.
You can press ctrl+space after validator and you can check all available methods.

This Validation helps us more during server side validation.

Thursday 17 December 2015

Using liferay-ui:ratings tag for your custom entity for Ratting functionality

 <liferay-ui:ratings
                       className="<%= Product.class.getName() %>"
                       classPK="<%= prod.getProductId() %>"/><

Tuesday 15 December 2015

Liferay ui tab

liferay-ui:tabs
This tag is usefull for generating tab based view for your content.
It renders as:

tag:
  <portlet:renderURL var="portletURL"></portlet:renderURL>  
   <liferay-ui:tabs param="currTAB" names="tab1,tab2,tab3" refresh="<%= true %>" url="<%=portletURL.toString() %>">  
       <liferay-ui:section>  
        <%@ include file="tab1.jsp" %>  
       </liferay-ui:section>  
       <liferay-ui:section>  
        <%@ include file="tab2.jsp" %>  
       </liferay-ui:section>  
       <liferay-ui:section>  
        <%@ include file="tab3.jsp" %>  
       </liferay-ui:section>  
   </liferay-ui:tabs>  

names is the labels of your tabs. Depending on your names attributes [comma separated], number of tabs would be generated. Inside liferay-ui:tabs tag, liferay-ui:section will serve as content of any tab. 
Tab names and its content are matched per order they are defined.
refresh:false, page will not refresh when you click on any tab.
true, page will get refreshed whenever clicking on any tab.

liferay-ui:input-date
You may need form to have date field as input.
To serve you, liferay comes up with input-date tag with liferay-ui tag library.
It renders as:
tag:
 <liferay-ui:input-date yearRangeEnd="2017" yearRangeStart="2000" dayParam="day" monthParam="month" yearParam="year"/>  
yearRangeStart yearRangeEnd attributes specifies year start-end.
dayParam,monthParam,yearParam these attributes' value would be name of select components so you can get it's value at server side.
By default current date would be shown, you can change default behavior by attributes dayValue, monthValue, yearValue.
You may want to have null[blank] selection of your date[day or month or year], then you can make any of attributes[ dayNullable,monthNullbale,yearNullable monthAndYearNullbale] as true


liferay-ui:calendar
This tag is useful when you want to show calendar like ui as shown below.
It renders as:

tag:
 <liferay-ui:calendar year="2013" month="1" headerPattern="dd/MM/yyyy" day="3"/>  

day,month,and year specifies which date you want to have calendar shown.
headerPattern specifies date pattern shown at header of calendar.

Liferay Ratting and comment Example

Step1-->for star

<liferay-ui:ratings-score score="5"/>


Step2---> for comment

 <liferay-ui:discussion classPK="12724" userId="20198" className="<%=Product.class.getName() %>"
             formAction="fm"></liferay-ui:discussion>


Wednesday 2 December 2015

Ajax example using spring mvc

Write in jsp page

http://www.opensource-techblog.com/2015/07/aui-ajax-in-liferay-portlet.html

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

<portlet:resourceURL id="findState" var="findState" ></portlet:resourceURL>

<script type="text/javascript">
$(document).ready(function(){

$( "#country" ).change(function() {
 $.ajax({
       url: "${findState}" ,
       type: 'POST',
       datatype:'json',
       data: {
 countryName: $("#country").val()
  },
           success: function(data){
           var content= JSON.parse(data);
           $('#state').html('');// to clear the previous option
           $.each(content, function(i, state) {
               $('#state').append($('<option>').text(state.name).attr('value', state.stateId));
           });
       }
   });
  });
});
</script>

<b>Change the Country State Change By Ajax</b> <br><br>
Country:
<select id="country" name="country">
<option value="select">Select Country</option>
<option value="india">India</option>
<option value="usa">USA</option>
</select>

<br><br>
State:
<select id="state" name="state">
</select>


SController.java

package com.test;

import java.io.IOException;

import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import org.springframework.web.portlet.bind.annotation.ResourceMapping;

import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.util.ParamUtil;


@Controller(value = "AjaxController")
@RequestMapping("VIEW")
public class AjaxController {
@RenderMapping
public String handleRenderRequest(RenderRequest request,RenderResponse response, Model model) {
return "view";
}

@ResourceMapping(value="findState")
    public void findStateForCountry(ResourceRequest request, ResourceResponse response) throws IOException  {
String countryName = ParamUtil.getString(request, "countryName");

JSONArray stateArray = JSONFactoryUtil.createJSONArray();
JSONObject stateObject,stateObject2;
if(countryName.equalsIgnoreCase("india"))
{
stateObject = JSONFactoryUtil.createJSONObject();
stateObject.put("stateId", "1");
stateObject.put("name", "Delhi");

stateObject2 = JSONFactoryUtil.createJSONObject();
stateObject2.put("stateId", "2");
stateObject2.put("name", "Gujrat");


}
else{

stateObject = JSONFactoryUtil.createJSONObject();
stateObject.put("stateId", "21");
stateObject.put("name", "LA");

stateObject2 = JSONFactoryUtil.createJSONObject();
stateObject2.put("stateId", "22");
stateObject2.put("name", "California");
}
   stateArray.put(stateObject);
   stateArray.put(stateObject2);
   response.getWriter().println(stateArray);
}



}


Tuesday 1 December 2015

Ajax calling example

<portlet:resourceURL var="SubmitURL"  />
      <input type="text" name="txt1" id="txt1" />
   <input   type="button" onclick="helpful();"  value="Submit" />  
 
   function helpful()
 {
 var textvalue=document.getElementById('txt1').value;
    $.ajax ({
     
        url:'<%=SubmitURL%>',
        type: 'POST',
        data : ({
           textVal: textvalue
           
             }),
        success: function()
        {           alert('success');
           
         }
    });
 
 
}

final String textValue= resourceRequest.getParameter("textVal");

Diffrence between Liferay Portal v6.2 and Liferay Portal v6.1

 Liferay Portal v6.2 and  Liferay Portal v6.1

Ans-In the Liferay 6.2 CE Version you will see all the things are very much organized or Categorize form then the previous version. 

 

·                     1>Look & Feel :- When I downloaded the latest tomcat bundle of liferay 6.2 CE, the first thing I noticed is there is a change in the Default Liferay theme. Liferay is now upgraded to Alloy 2.0.

2>Dockbar :- The Second thing

In Liferay 6.2 they have made it more Categorize form. They have Categorize Admin(Control Panel)and MySites which all comes together in GOTO Section in liferay 6.1 version.

 

3>Control Panel :- There was a Major Change in the Control Panel Section. It was divided into Four Sections
Users - It contains User, UserGroup, Password Policies, Roles, Organization etc in this section.
Sites - It contains Sites,Sites Template,Page Template,Blogs,Wiki, Document and Media etc in this section.
Apps - It contains Market Place,Plugins Configuration, Plugins Installation etc in this section.
Configuration - It contains Portal Settings,Custom Fields,Server Administration and Portal Instances in this section.   

4>Sites


There are couple of changes and also new portlets are added at site level.
Recycle Bin :- The name itself speaks a lot. You all knows what the Recycle Bin do in Windows or Trash in Mac. The same feature liferay has implemented here.

5>New Template Script Editor with Auto complete :- Good to have this. It was hectic to write scripts in previous versions. It will make life easier.

Q2-How to install liferay with eclipse?
Ans-
1.      Install JDK and setting required environment variables (JAVA_HOME, path)
2.      Download MySQL server and Start MySQL server
3.      Download and unzip the Tomcat Bundle Liferay Portal :
4.      Install the Liferay IDE extension in Eclipse
> Help > Install New Software > Add
Name: Liferay IDE Stable
URL: http://releases.liferay.com/tools/ide/latest/stable/
5.      Add in Eclipse the Liferay Plugin SDK instance previously installed:
> Windows > Preferences > Liferay > Installed Plugins SDKs > Add >
6.      Add in Eclipse a Tomcat Runntime Environment based on the Liferay Portal previously installed:
> Windows > Preferences > Server > Runtime Environment > Add > Liferay,Inc > Liferay v6.2 CE (Tomcat 7)
7.      Configure database setting in portal-ext.properties file and place properties file in Liferay Home(bundles) directory.
8.      Configure Liferay Tomcat sever information in Plugins SDK properties file.
9.      Start Eclipse and configure liferay prospective
10. Configure Plugins SDK in Eclipse
11. Configure Liferay Tomcat Server in Eclipse
12. Start Tomcat from Eclipse and access liferay portal
13. Complete required basic configurations for liferay portal (This is only for first time)
14. Start Liferay Application Development

Q-How to connect mysql with liferay eclipse?
Ans-Follow the below steps->
1.    Create a new liferay server (Point it to the liferay portal).
2.    Start the server.
3.    When the server will start hit the localhost:8080.
4.    A page will be displayed for the database configuration and user configuration.
5.    provide the db name and usename and password.
6.    Once you provide that, liferay will use that database.(Obviously that DB should be in your database)
Else you can create a portal-setup-wizard.properties file in \liferay-portal-6.2.0-ce-ga1 directory. Then add the following entries.
admin.email.from.name=Test Test
jdbc.default.password=root
liferay.home=D:/5555555/liferay-portal-6.2.0-ce-ga1
admin.email.from.address=test@liferay.com
jdbc.default.driverClassName=com.mysql.jdbc.Driver
jdbc.default.username=root
jdbc.default.url=jdbc:mysql://localhost/project_monitor_liferay?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false
setup.wizard.enabled=false



Q diffrence between hot deployment and deployment?
ans-hot deployment means direct deployment
ex- Hook
deployment means restart the server
ex- EXT