Monday, 29 December 2014

Date Picker using java script

<form action="<%=iteratorURL %>" method="post">
<input type="text" name="fromdate" id="fromdate" readonly="readonly" placeholder="From Date"/>
<input type="text" name="todate"  id="todate" readonly="readonly" placeholder="To Date"/>
</form>

<script type="text/javascript">
 $(document).ready(function(){
       $(function() {
       
           $('#fromdate').datepicker({
               minDate: 0,
               dateFormat: 'mm/dd/yy',
                onClose: function (selectedDate) {
                   $("#todate").datepicker("option", "minDate", selectedDate);
               }
           });
           $('#todate').datepicker({
               minDate: 0,
               dateFormat: 'mm/dd/yy'
              
               /* onClose: function (selectedDate) {
                   $("#ExpectedDateStart").datepicker("option", "", selectedDate);
               } */
           });
              
       });
 });
</script>

 IF YOU WANT TO DISPLAY PREVIOUS  DATE ALSO IN FIRST DATE PICKER BOX THEN USE THIS

<script type="text/javascript">
 $(document).ready(function(){
       $(function() {
       
           $('#fromdate').datepicker({
               //minDate: 0,
               dateFormat: 'mm/dd/yy' ,
                onClose: function (selectedDate) {
                   $("#todate").datepicker("option", "minDate", selectedDate);
               }
           });
           $('#todate').datepicker({
               //minDate: 0,
               dateFormat: 'mm/dd/yy'
              
               /* onClose: function (selectedDate) {
                   $("#ExpectedDateStart").datepicker("option", "", selectedDate);
               } */
           });
              
       });
 });
</script> 

Tuesday, 23 December 2014

HOW TO SAVE PASSWORD IN TEXT FORMAT IN LIFERAY USER TABLE

portal-ext.properties file


passwords.encryption.algorithm=NONE 


save  and restart the server
then create a account and check user table password will store in text .

Sunday, 21 December 2014

Finder Tags in liferay

 Search field with the below drop-down texts:
1. All Bookings
2. Executed Bookings
3. Cancelled Bookings
4. Cancelation Requests.

service.xml
 <entity name="BookingInfo" local-service="true" remote-service="false">
        <column name="bookingId" type="String" primary="true"/>
        <column name="customerId" type="String" />
        <column name="carId" type="String" />
        <column name="carType" type="String" />
        <column name="emailId" type="String" />
        <column name="phNumb" type="String" />
        <column name="fromlocation" type="String" />
        <column name="toLocation" type="String"/>
        <column name="dateOut" type="String" />
        <column name="timeOut" type="String" />
        <column name="dateIn" type="String" />
        <column name="timeIn" type="String" />
        <column name="dateDueIn" type="String" />
        <column name="timeDueIn" type="String" />
        <column name="insurance" type="String" />
        <column name="paymentStatus" type="boolean" />
        <column name="amount" type="String" />
        <column name="carStatus" type="String" />
      
        <column name="cardType" type="String" />
        <column name="cardNumb" type="String" />
        <column name="cardExpMon" type="String" />
        <column name="cardExpYear" type="String" />      
      
        <order>
            <order-column name="bookingId" order-by="desc" />
        </order>
      
        <finder return-type="Collection" name="phNumb">
            <finder-column name="phNumb" />          
        </finder>
      
        <finder return-type="Collection" name="email">
            <finder-column name="emailId" />
            <finder-column name="paymentStatus" />                  
        </finder>
      
  
              
        <finder return-type="Collection" name="carStatus">
            <finder-column name="carStatus" />          
        </finder>

  BookingInfoLocalServiceImpl.java

 public class BookingInfoLocalServiceImpl extends BookingInfoLocalServiceBaseImpl {
     
    public List<BookingInfo> searchByPhNumb(String phNumb) throws SystemException {
      
        List<BookingInfo> booking = bookingInfoPersistence.findByphNumb(phNumb);
      
        return booking;
    }
  
    public List<BookingInfo> searchEmail(String email) throws SystemException {
      
        List<BookingInfo> booking = bookingInfoPersistence.findByemail(email, true);
      
        return booking;
    }
  
    public List<BookingInfo> searchByCarStatus(String carStatus) throws SystemException {
      
        List<BookingInfo> booking = bookingInfoPersistence.findBycarStatus(carStatus);
      
        return booking;
    }
}


view.jsp

<%@page import="javax.portlet.ActionRequest"%>
<%@page import="javax.portlet.ActionResponse"%>
<%@page import="com.liferay.portal.kernel.util.WebKeys"%>
<%@page import="com.liferay.portal.theme.ThemeDisplay"%>
<%@page import="com.liferay.portal.kernel.dao.search.SearchContainer"%>
<%@page import="com.liferay.portal.kernel.util.ListUtil"%>
<%@page import="com.slayer.service.BookingInfoLocalServiceUtil"%>
<%@page import="com.slayer.model.BookingInfo"%>
<%@page import="java.util.List"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@page import="javax.portlet.PortletURL"%>
<%@ taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui"%>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%>
<portlet:defineObjects />

<style>

.href{
text-decoration: none;
}
</style>

 <%
List <BookingInfo> bookingInfo = BookingInfoLocalServiceUtil.getBookingInfos(0, -1);

PortletURL iteratorURL = renderResponse.createRenderURL();
iteratorURL.setParameter("jspPage", "/html/Admin/bookingdetail/view.jsp");

String select = "all" ;
String abc = "all";

select = renderRequest.getParameter("select");
 abc =(String) request.getAttribute("select");
if(select==null){
    select="all";
   
    bookingInfo = BookingInfoLocalServiceUtil.getBookingInfos(0, -1);
}if(abc==null){
    abc = "all";
}if(select.equalsIgnoreCase("cancelReq") || abc.equalsIgnoreCase("cancelReq")){
    select ="cancelReq";
    bookingInfo = BookingInfoLocalServiceUtil.searchByCarStatus("cancelReq");
}
if(select.equalsIgnoreCase("Cancelled") || abc.equalsIgnoreCase("Cancelled")){
    select ="Cancelled";
    bookingInfo = BookingInfoLocalServiceUtil.searchByCarStatus("Cancelled");
}

if(select.equalsIgnoreCase("Executed")||abc.equalsIgnoreCase("Executed")){
    select="Executed";
    bookingInfo=BookingInfoLocalServiceUtil.searchByCarStatus("Executed");
}
%>

<div>
<form action="<%=iteratorURL %>" method="post">
<select name="select">
<option value="all" <%if(select.equalsIgnoreCase("all")){ %> selected="selected" <%} %>>All Bookings</option>
<option value="Executed" <%if(select.equalsIgnoreCase("Executed")){ %> selected="selected" <%} %> >Executed Bookings</option>
<option value="cancelled" <%if(select.equalsIgnoreCase("Cancelled")){ %> selected="selected" <%} %> > Cancelled Bookings</option>
<option value="cancelReq" <%if(select.equalsIgnoreCase("cancelReq")){ %> selected="selected" <%} %> >Cancellation Requests</option>

</select>
<input type="submit" value="show">
</form>
</div>




 <div>
    <liferay-ui:search-container delta="10" emptyResultsMessage="Sorry. There are no items to display." iteratorURL="<%=iteratorURL%>">
        <liferay-ui:search-container-results  total="<%=bookingInfo.size()%>"
            results="<%=ListUtil.subList(bookingInfo, searchContainer.getStart(), searchContainer.getEnd())%>" />
        <liferay-ui:search-container-row modelVar="info" className="BookingInfo">
            <liferay-ui:search-container-column-text name="Booking Id" property="bookingId"/>
            <liferay-ui:search-container-column-text name="Car Type" property="carType"/>
            <liferay-ui:search-container-column-text name="Email Id" property="emailId"/>
            <liferay-ui:search-container-column-text name="Pick Up Date & Time" value="<%= info.getDateOut() + \"  \" + info.getTimeOut() %>"/>
            <liferay-ui:search-container-column-text name=" Drop Off Date & Time" value="<%= info.getDateDueIn() + \"  \" + info.getTimeDueIn() %>"/>
            <liferay-ui:search-container-column-text name=" Actual Drop Off Date & Time" value="<%= info.getDateIn() + \"  \" + info.getTimeIn() %>"/>
           
            <liferay-ui:search-container-column-text name="Status" property="carStatus"/>
       
            <liferay-ui:search-container-column-text name="Amount" value="<%=\" $ \"  + info.getAmount() %>"/>
       
        <%
            if(select.equalsIgnoreCase("cancelReq")){
        %>
        <liferay-ui:search-container-column-jsp path="/html/Admin/bookingdetail/actionBookingDetails.jsp" name="Action">
            </liferay-ui:search-container-column-jsp>
       
        <%}%>
       
        </liferay-ui:search-container-row>
        <liferay-ui:search-iterator searchContainer="<%=searchContainer%>" />
    </liferay-ui:search-container>           
   
</div>

Friday, 19 December 2014

Change Password Logic



public void changePassword(ActionRequest actionRequest,
            ActionResponse actionResponse) throws IOException, PortletException {

        String oldPassword = actionRequest.getParameter("oldPassword");
        String newPassword = actionRequest.getParameter("newPassword");
        String confirmPassword = actionRequest.getParameter("confirmPassword");
       
        ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

        User user = themeDisplay.getUser();
        String email = user.getEmailAddress();
       
        boolean sendMail = false;
       
        try {
           
            RegCustomer regCustomer = RegCustomerLocalServiceUtil.getRegCustomer(email);
            if(regCustomer.getPassword().equals(oldPassword)){           
            regCustomer.setPassword(newPassword);
           
            UserServiceUtil.updatePassword(user.getUserId(), newPassword, confirmPassword, false);
           
            regCustomer = RegCustomerLocalServiceUtil.updateRegCustomer(regCustomer);
            sendMail = true;
            }
           
         else if(!regCustomer.getPassword().equals(oldPassword)){
                SessionMessages.add(actionRequest, "request_processed", "Wrong Old Password");
            }

        } catch (Exception e) {
            try {
                BusinessUser businessUser =  BusinessUserLocalServiceUtil.getBusinessUser(email);
                if(businessUser.getPassword().equals(oldPassword)){
                businessUser.setPassword(newPassword);
               
                UserServiceUtil.updatePassword(user.getUserId(), newPassword, confirmPassword, false);
               
                BusinessUserLocalServiceUtil.updateBusinessUser(businessUser);
                sendMail = true;
                }
                  else if(!businessUser.getPassword().equals(oldPassword)){
                    SessionMessages.add(actionRequest, "request_processed", "Wrong Old Password");
                }
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }

Adding image ,dispalying preview and storing it in to Database


 addCarCharges.jsp

<%@page import="com.slayer.service.ImageContentLocalServiceUtil"%>
<%@page import="com.slayer.model.ImageContent"%>
<%@page import="com.liferay.portal.model.Image"%>
<%@page import="com.liferay.portal.service.ImageLocalServiceUtil"%>
<%@page import="com.slayer.service.CarChargesLocalServiceUtil"%>
<%@page import="com.slayer.model.CarCharges"%>
<%@page import="javax.portlet.ActionRequest"%>
<%@page import="javax.portlet.PortletURL"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<%@ taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui"%>
<%@taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme"%>
<liferay-theme:defineObjects />
<portlet:defineObjects />
<head>
</head>
<style>
 .label{
vertical-align: middle;
 padding-top: 7%; 
}
/* form div {
height: 20px;
margin-top: 15px;
}   */
#buttn{
margin-left: 185px;
 width: 135px;

}
.w40{
 font-family: Helvetica,Arial,Verdana,sans-serif;
font-size: 12px;
text-align:right;
width: 20%;
float: left;
}
.w60{
font-size: 12px;

width: 80%;
float: left;
}
.textfield{
  width:130px;
height:18px;
padding-top: 5px;
  border-radius:4px;
  border:1px solid #649A32;
  box-shadow: 1px 1px 2px #649A32;
  float:left;
  margin-bottom:5px;
  margin-left:7px;
  }
 
</style>


 <div class="protlet-header border-bot">Add Car Charges</div>
<%
    PortletURL backUrl = renderResponse.createRenderURL();

    PortletURL addChargesUrl = renderResponse.createActionURL();
    addChargesUrl.setParameter(ActionRequest.ACTION_NAME,
            "addCarCharges");

    CarCharges car = null;

    String cartype = renderRequest.getParameter("type");
    String type = "", dailyRental = "", weeklyRental = "", dailyDamageWaiver = "", weeklyDamageWaiver = "";

   

    String imgPath = request.getContextPath() + "/html/Admin/cardetail/defaultCar.jpg";
    if (cartype != null) {
        try {
            car = CarChargesLocalServiceUtil.getCarCharges(cartype);
            type = car.getType();
            dailyRental = car.getDailyRental();
            weeklyRental = car.getWeeklyRental();
            dailyDamageWaiver = car.getWeeklyDamageWaiver();
            weeklyDamageWaiver = car.getDailyDamageWaiver();
            imgPath = themeDisplay.getPathImage() + "/image?img_id="+ car.getImageId();
        } catch (Exception e) {

        }
    }

   

   
%>

<!-- <div class="protlet-header border-bot">
Upload The Image Of Size 500*320 px(Resize Images Online For Better Quality)<br/>http://www.simpleimageresizer.com/upload
</div> -->

<script type="text/javascript">

    function PreviewImage()
    {   
   
        var img=document.getElementById("addimage").value;
        if(img==null && ""){
            alert("sgjkdfsd fsgf");
    }
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("addimage").files[0]);

        oFReader.onload = function (oFREvent) {
            document.getElementById("uploadPreview").src = oFREvent.target.result;
        };
    }
   
    function formValidate()
    {
    if(document.getElementById("addimage").value=="")
    {
        alert("No Image Selected");
        return false;
    }
    }
</script>

<div>
<form action="<%=addChargesUrl.toString() %>" method="post" id="form" enctype="multipart/form-data">
   <div style="height:150px; ">
   
    <div class="label w40">
        <label>Add Image:</label>
    </div>
    <div class="w60">
        <img id="uploadPreview" src="<%=imgPath %>"
            style="width: 180px; height: 134px;" />
    </div>
    </div>
    <div class="w40 "><pre>  </pre></div>
<div class="w60">
        <input id="addimage" type="file" name="addimage"
            onchange="PreviewImage();" readonly="readonly" />
    </div>
   
<div class="w40"><label class="label">Type:</label></div>
<div class="w60">
<input class="textfield"
        data-msg-required="Please Enter The Type."
        data-rule-required="true"
        type="text" name="type"  id="type" value="<%=type%>"/></div>

<div class="w40"><label class="label">Daily Rental/Per Day:</label></div>
<div class="w60">
<input class="textfield"
       data-msg-required=" Enter Daily Rental/Per Day."
       data-rule-required="true"
       data-rule-number="true"
       type="text" name="dailyRental" id="dailyRental" value="<%=dailyRental%>"/></div>

<div class="w40"><label class="label">Weekly Rental/Per Day:</label></div>
<div class="w60">
<input  class="textfield"
       data-msg-required="Enter Weekly Rental/Per Day."
       data-rule-required="true"
       data-rule-number="true"
        type="text" name="weeklyRental" id="weeklyRental" value="<%=weeklyRental %>"/></div>
<div class="w40"><label class="label">Daily DamageWaiver/Per Day:</label></div>
<div class="w60">
<input  class="textfield"
        data-msg-required="Enter Daily DamageWaiver/Per Day."
        data-rule-required="true"
        data-rule-number="true"
        type="text" name="dailyDamageWaiver" id="dailyDamageWaiver" value="<%= dailyDamageWaiver%>"/></div>
<div class="w40"><label class="label">Weekly DamageWaiver/Per Day:</label></div>
<div class="w60">
<input   class="textfield"
        data-msg-required="Enter Weekly DamageWaiver/Per Day."
        data-rule-required="true"
        data-rule-number="true"
        type="text" name="weeklyDamageWaiver" id="weeklyDamageWaiver" value="<%=weeklyDamageWaiver %>"/></div>
<div class="w40"></div>
<div class="w60">
<input  id="buttn"  type="submit" value="Submit"/>
<a href="<%= backUrl%>" style="text-decoration: none; margin-left: 15px;"><input  type="button" value="Back" style=" width: 100px;"></a>
</div>
</form>
</div>






 Action class
CarDetailPortlet.java 


package com.test;

import java.io.File;
import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.model.Image;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ImageLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.slayer.model.CarAvailability;
import com.slayer.model.CarCharges;
import com.slayer.model.CarDetails;
import com.slayer.model.ImageContent;
import com.slayer.model.impl.CarAvailabilityImpl;
import com.slayer.model.impl.CarChargesImpl;
import com.slayer.model.impl.CarDetailsImpl;
import com.slayer.model.impl.ImageContentImpl;
import com.slayer.service.CarAvailabilityLocalServiceUtil;
import com.slayer.service.CarChargesLocalServiceUtil;
import com.slayer.service.CarDetailsLocalServiceUtil;
import com.slayer.service.ImageContentLocalServiceUtil;

/**
 * Portlet implementation class CarDetailPortlet
 */
public class CarDetailPortlet extends MVCPortlet {
   

        public void addCarCharges(ActionRequest actionRequest, ActionResponse actionResponse)
                                      throws IOException, PortletException, SystemException
        {
            UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
           
            String type=ParamUtil.getString(uploadRequest, "type");
            String dailyRental=ParamUtil.getString(uploadRequest, "dailyRental");
            String weeklyRental=ParamUtil.getString(uploadRequest, "weeklyRental");
            String dailyDamageWaiver=ParamUtil.getString(uploadRequest, "dailyDamageWaiver");
            String weeklyDamageWaiver=ParamUtil.getString(uploadRequest, "weeklyDamageWaiver");
           
           
        File addimage = uploadRequest.getFile("addimage");

           
            CarCharges charge=null;
            try {
                charge = CarChargesLocalServiceUtil.getCarCharges(type);
               
            } catch (Exception e2) {
                // TODO Auto-generated catch block
                charge = new CarChargesImpl();
                Long imageId= CounterLocalServiceUtil.increment();
                charge.setImageId(imageId.toString());
            }
           
                                       
           
            Long id =Long.parseLong(charge.getImageId());
           
            charge.setType(type);
            charge.setDailyRental(dailyRental);
            charge.setWeeklyRental(weeklyRental);
            charge.setWeeklyDamageWaiver(weeklyDamageWaiver);
            charge.setDailyDamageWaiver(dailyDamageWaiver);
            charge.setWeeklyDamageWaiver(weeklyDamageWaiver);
            charge.setTotalCars(0);
            charge.setTotalBookedCars(0);
//            System.out.println("hhhhhhhhhhhhhhhhhhhhhhhhhhh"+charge);
           
            try {
                CarChargesLocalServiceUtil.updateCarCharges(charge);   
                ImageLocalServiceUtil.updateImage(id, addimage);
            } catch (SystemException e) {
                e.printStackTrace();
           
            }catch(PortalException e1){
                e1.printStackTrace();
            }
               
       
               
    }


















 

Sunday, 14 December 2014

Forgot Password implementation in Liferay


Hooking  login.jsp  And redirect to forgot password page which is hidden. I created forgot password portlet and added it to forgot password page .

And also removed Create Account link and forgot password link.
I create forgot password button which will redirect to forgot password page where we can enter email-Id  when we send it, it will fetch password from data base and send it to that email-Id .



<%
StringBundler forgotPasswordURL = null;
try{
       forgotPasswordURL = new StringBundler(7); //to create url for forget password page
     
               forgotPasswordURL.append(themeDisplay.getURLPortal()); //http://localhost:8080
forgotPasswordURL.append("/web/guest/forgot-password");
}
      catch(Exception e){
System.out.println("exception1");
}
%>
<a class="button" href="<%= forgotPasswordURL %>">Forgot Password</a>


Create a portlet  forgot password

view.jsp

<%@page import="com.liferay.portal.kernel.util.Validator"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<%@page import="javax.portlet.PortletURL" %>
<%@page import="javax.portlet.ActionRequest" %>
<portlet:defineObjects />

<%
 

  PortletURL forgotPasswordURL = renderResponse.createActionURL();
      forgotPasswordURL.setParameter(ActionRequest.ACTION_NAME,"fetchPassword");
    String userFound = (String)renderRequest.getAttribute("userFound");
   if(Validator.isNotNull(userFound)){
    if(userFound.equalsIgnoreCase("false")){
    %>
    <h3>Please signup, you are not register user.</h3>
    <%
    }
    else{
    %>
    <h3>Please check your mail, password sent to your mail.</h3>
    <%
    }
   }
   
    %>

<aui:form action="<%=forgotPasswordURL %>" method="post">

    <aui:input  name="emailId" id="emailId" lable="Email-Id" type="text" >
  <aui:validator name="required" />
  <aui:validator name="email"/>
    </aui:input>
 
    <aui:button type="submit" value="send" />
</aui:form>

Acion Class

ForgotPassword.java


package com.test;

import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import org.apache.log4j.Logger;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.slayer.model.BusinessUser;
import com.slayer.model.RegCustomer;
import com.slayer.service.BusinessUserLocalServiceUtil;
import com.slayer.service.RegCustomerLocalServiceUtil;

/**
 * Portlet implementation class forgotPassword
 */
public class forgotPassword extends MVCPortlet {
private static final Logger log = Logger.getLogger(forgotPassword.class);

public void fetchPassword(ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException,PortletException
{
RegCustomer regCustomer = null;
BusinessUser businessUser = null;
String userFound = "false";
String emailId= ParamUtil.getString(actionRequest,"emailId");
//log.info("email ID  is "+emailId);
try{
 businessUser = BusinessUserLocalServiceUtil.getBusinessUser(emailId);
 //log.info("Bbuser: "+businessUser);
 userFound = "businessUser";
}
catch(Exception e){
 //log.error(e);
 try{
 regCustomer = RegCustomerLocalServiceUtil.getRegCustomer(emailId);
 //log.info("regCustomer: "+regCustomer);
 userFound = "regCustomer";
 }
 catch (Exception e1) {
 log.error(e1);
 }
}
//log.info("userFound: "+userFound);
if(userFound.equalsIgnoreCase("false")){
actionRequest.setAttribute("userFound", userFound);
}
else if(userFound.equalsIgnoreCase("businessUser")){
actionRequest.setAttribute("userFound", userFound);
log.info("B: pwd: "+businessUser.getPassword());
}
else if(userFound.equalsIgnoreCase("regCustomer")){
actionRequest.setAttribute("userFound", userFound);
log.info("U: pwd: "+regCustomer.getPassword());
}
}
}



I fetch data from two table BusinessUser and  RegCustomer




Friday, 12 December 2014

How to remove default success message in liferay

Add the shaded code in your portlet.xml file

<portlet>
<portlet-name>forgotpassword</portlet-name>
<display-name>forgot Password</display-name>
<portlet-class>com.test.forgotPassword</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/forgotpassword/view.jsp</value>

</init-param>
<init-param>
                   <name>add-process-action-success-action</name>
                   <value>false</value>
             </init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
</supports>

<portlet-info>
<title>forgot Password</title>
<short-title>forgot Password</short-title>

<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
<security-role-ref>
<role-name>guest</role-name>
</security-role-ref>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>

you can also change session message through action class

SessionMessages.add(actionRequest, "request_processed", "your msg will be here");

addProcessActionSuccessMessage= false;

Wednesday, 10 December 2014

what are the thing we can customize in portal-ext.properties file

##
## Company
##

#
# This sets the default web id. Omniadmin users must belong to the company
# with this web id.
#
company.default.web.id=liferay.com

#
# The portal can authenticate users based on their email address, screen
# name, or user id.
#
company.security.auth.type=emailAddress
#company.security.auth.type=screenName
#company.security.auth.type=userId

#
# Set this to true to ensure users login with https.
#
company.security.auth.requires.https=false

#
# Set the following to true to allow users to select the "remember me"
# feature to automatically login to the portal.
#
company.security.auto.login=true

#
# Set the following to the maximum age (in number of seconds) of the browser
# cookie that enables the "remember me" feature. A value of 31536000
# signifies a lifespan of one year. A value of -1 signifies a lifespan of a
# browser session.
#
# Rather than setting this to 0, set the property
# "company.security.auto.login" to false to disable the "remember me"
# feature.
#
company.security.auto.login.max.age=31536000

#
# Set the following to true to allow users to ask the portal to send them
# their password.
#
company.security.send.password=true

#
# Set the following to true to allow strangers to create accounts and
# register themselves on the portal.
#
company.security.strangers=true

#
# Set the following to true if strangers can create accounts with email
# addresses that match the company mail suffix. This property is not used
# unless "company.security.strangers" is also set to true.
#
company.security.strangers.with.mx=true

#
# Set the following to true if strangers who create accounts need to be
# verified via email.
#
company.security.strangers.verify=false

#
# Set the following to true to allow community administrators to use their
# own logo instead of the enterprise logo.
#
company.security.community.logo=true

Monday, 8 December 2014

Ajax Call Country Region


<%@page import="javax.portlet.ActionResponse"%>
<%@ include file="/html/reg/init.jsp" %>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<%@page import="com.liferay.portal.model.Country"%>
<%@page import="com.liferay.portal.service.CountryServiceUtil"%>

<portlet:defineObjects />

<%
  PortletURL formURL=renderResponse.createActionURL();
  formURL.setParameter(ActionRequest.ACTION_NAME, RegConstants.ACTION_FORM );
 
            /*Edit regestration form */
 
  REGForm regForm = new REGFormImpl();
  long regId =ParamUtil.getLong(request, "bookId");
 
  if (regId > 01){
   regForm = REGFormLocalServiceUtil.fetchREGForm(regId);
  }
%>


<aui:form name="fm" method="POST" action="<%=formURL.toString()%>">
<%-- <aui:input name="redirectURL" type="hidden"
    value="<%=renderResponse.createRenderURL().toString()%>"/> --%>
   
  <aui:input name="regId" type="hidden" value="<%=regForm.getRegId() %>"/>
 
  <aui:input name="userName" label="User Name" value="<%=regForm.getUserName()%>">
          <aui:validator name="required"/>      
   </aui:input>
 
   <aui:input name="email" label="Email Id" value="<%=regForm.getEmail() %>">
         <aui:validator name="required"/>
         <aui:validator name="email"/>
   </aui:input>
 
   <aui:input name="dob" label="Date Of Birth" id="dob"  value="<%=regForm.getDob()%>" >
          <aui:validator name="date"/>
   </aui:input>      
   <aui:input name="contact" label="Contact No" value="<%=regForm.getContact() %>">
             <aui:validator name="number"/>
             <aui:validator name="minLength">10</aui:validator>
              <aui:validator name="maxLength">10</aui:validator>
   </aui:input>
   <aui:select name="countryId" id="countryId" label="country"
                onChange="javascript:listRegions(this)"/>
   <aui:select  name="regionId" id="regionId" label="City" />
     

 
  <%--   <aui:input type="file" name="uploadResume" size="75"/>  --%>
 
   <aui:button type="submit" value="Submit"/>
</aui:form>

 <aui:script>
     Liferay.Util.focusFormField(
          document.<portlet:namespace/>fm.<portlet:namespace/>userName);
         
 </aui:script>
 <aui:script>
AUI().ready(function(A){
var frm = document.<portlet:namespace/>fm;
var countries = frm.<portlet:namespace/>countryId;

Liferay.Service(
'/country/get-countries',
{ active: true },
function(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var name = obj[key].name;
var countryId = obj[key].countryId;
countries.options[key] = new Option(name,countryId);
}
}
}
);
});

function listRegions(country) {
var frm = document.<portlet:namespace/>fm;
var regions = frm.<portlet:namespace/>regionId;

var _countryId = country.value;

regions.disabled = (_countryId <= 0);

if (_countryId <= 0) {
regions.selectedIndex = 0;
} else {
// calling regions of this country
var payload = {
countryId: _countryId,
active: true
};

Liferay.Service.Portal.Region.getRegions(payload,
function(data) {

regions.options.length = data.length;
for (var i=0; i<(data.length-1); i++) {
var rgn = data[i];
regions.options[i] =
new Option(rgn.name, rgn.regionId);
}

}
);
}
}
</aui:script>


<%
    PortletURL listRegsURL=renderResponse.createRenderURL();
    listRegsURL.setParameter("jspPage","/html/reg/list.jsp");
%>
   &nbsp;|&nbsp;
   <a href="<%= listRegsURL.toString()%>">Show All Register Detail &raquo;</a>

Saturday, 8 November 2014

How to reuse (instanceable) my custom portlet more than one time in my page

Way to get more than one instance of a portlet

 Open liferay-portlet.xml file

 edit the file

<portlet>
<portlet-name>AddOnDirectory</portlet-name>
<icon>/icon.png</icon>

<instanceable>false</instanceable> --- modified this to 

<instanceable>true</instanceable>

 Then deploy to server. After that add your portlet instance as many you want on a page.

hook


Saturday, 1 November 2014

How to customize create user in liferay using Hook

In post this we will customize  Liferay Create account functionality using Liferay hooks.



In this page we have to add a field. We will add a field  named as "Social Security Number"



Step 1: Creation of custom Field 

   We are customizing  user registration. Therefore we are going to create a new custom field for the Entity User. Create the custom field from control panel as below. Our key is ssn.



we have to set appropriate permission for the custom field. Because the guest user i.e., at the time of creating new account this field will be viewed and updated.Set the permission as shown in the screen shot



Step 2: Create language hook in our example-hook project. The key should be ssn in the language file .



   Put ssn=Social Security Number  in language_en.properties file

    
      Before deploy language hook



     After deploy language hook


Step 3: Create JSP hook 


Open create_account.jsp and add this code

 <div class="exp-ctrl-holder">
    <liferay-ui:custom-attribute
        className="<%= User.class.getName() %>"
        classPK="<%= 0 %>"
        editable="<%= true %>"
        label="<%= true %>"
        name="ssn"
    /> 
 </div>

The above code will render one input box with label Social Security Number.

   

 The name attribute in the above code we have given the same key ssn as we entered in the control panel in the Step 1. The benefit of this tag is that we don’t need to do any other thing to persist the data. Once the form is submitted the data entered in the expando field will be also saved in the expando column in the database.

Step 4: Validation of the newly added field 

We have added the field and now we are able to persist the data also. But we need to do some server side validation also. Say SSN should be always numeric. To achieve this we can override struts action by hook.

Creating Struts action



Open  CustomCreateAccountAction.java file and put this code

package com.proliferay.demo;
 
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
 
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.struts.BaseStrutsPortletAction;
import com.liferay.portal.kernel.struts.StrutsPortletAction;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.expando.model.ExpandoColumnConstants;
 
/**
 *
 * @author Hamidul Islam
 *
 * Discover more in
 * www.proliferay.com
 *
 */
 
public class CustomCreateAccountAction extends BaseStrutsPortletAction{
 
    /**
     * This is the custom process action
     *
     * In this process action we are reading custom field which is entered from create account form
     *
     * After reading the custom field we are calling the original process action
     */
    public void processAction(
            StrutsPortletAction originalStrutsPortletAction,
            PortletConfig portletConfig, ActionRequest actionRequest,
            ActionResponse actionResponse)
        throws Exception {
         
         
        String ssnValue = (String)PortalUtil.getExpandoValue(actionRequest, "ExpandoAttribute--" + "ssn" + "--", ExpandoColumnConstants.STRING, ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX);
        System.out.println("##################ssnValue###########################################"+ssnValue);
        if(!Validator.isNumber(ssnValue)){
            SessionErrors.add(actionRequest,"wrong-ssn");
            return;
        }
         
         
        originalStrutsPortletAction.processAction(
            originalStrutsPortletAction, portletConfig, actionRequest,
            actionResponse);
    }
     
     
    /**
     * After process action this method is invoked
     *
     * From inside of this method we are again calling the original render method
     */
    public String render(
            StrutsPortletAction originalStrutsPortletAction,
            PortletConfig portletConfig, RenderRequest renderRequest,
            RenderResponse renderResponse)
        throws Exception {
 
        return originalStrutsPortletAction.render(
                originalStrutsPortletAction, portletConfig, renderRequest, renderResponse);
 
    }
 
}


Note 1: We overridden  struts /login/create_account
Note 2: To read custom attribute value we have used  PortalUtil.getExpandoValue
Note 3: Our custom field key is ssn. When its rendered by liferay-ui:custom-attribute the                name of the field would be like this ExpandoAttribute–ssn–

Note 4: We have added the below code in create_account.jsp for displaying error message

<liferay-ui:error key=”wrong-ssn” message=”The SSN number is not correct”/>



The final liferay-hook.xml

<?xml version="1.0"?>
<!DOCTYPE hook PUBLIC "-//Liferay//DTD Hook 6.2.0//EN" "http://www.liferay.com/dtd/liferay-hook_6_2_0.dtd">
 
<hook>
    <language-properties>
        content/language.properties
    </language-properties>
    <custom-jsp-dir>/custom_jsps</custom-jsp-dir>
    <struts-action>
        <struts-action-path>/login/create_account</struts-action-path>
        <struts-action-impl>com.proliferay.demo.CustomCreateAccountAction</struts-action-impl>
    </struts-action>
</hook>