Wednesday, 29 October 2014

confirmation box in liferay

In this post I am submitting a form by using aui-modal property.
In my jsp I am having one form and on click it will call a function and that function will either submit form if user submit and cancel submit form if it is cancel by the user.
I m writing here only form not its contents, my main intention is to describe the confirmation pop up.

my jsp


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

<portlet:defineObjects />
<liferay-theme:defineObjects />

<%

String valueExpandStr = "null";
PortletURL updateUserPassword = renderResponse.createActionURL();
updateUserPassword.setParameter(ActionRequest.ACTION_NAME, RegisterConstants.UPDATE_USER_PASSWORD);

%>
<aui:form name="fm" method="POST" action="<%=updateUserPassword.toString()%>" >

<%-- put html content inside here of your form  --%>

<aui:button value="Save" key="save"  onClick="javascript:showAddNoteDialog();"/>

</aui:form>
<div class="yui3-skin-sam">
  <div id="modal"></div>
</div>

<script>

function showAddNoteDialog(){


 YUI().use('aui-modal', function(Y) {
   var modal = new Y.Modal(
     {
       bodyContent: '<label for="feedback/suggestions" ><liferay-ui:message key="sureToEditProfileInformation"/></label>',
       centered: true,
       headerContent: '<h3><label for="formsofinteraction"><liferay-ui:message key="confirmationBox"/></label></h3>',
       modal: true,
       render: '#modal',
       width: 500
     }
   ).render();
    modal.addToolbar(
         [
           {
             label: '<liferay-ui:message key="Cancel"/>',
             on: {
               click: function() {
                modal.hide();
               }
             }
           },
           {
             label: '<liferay-ui:message key="Submit"/>',
             on: {
               click: function() {
                modal.hide();
                document.getElementById("<portlet:namespace/>fm").submit();
               }
             }
           },
           ]
   );
 }
);
   }
</script>
Here you can observe, first button is cancel button which will not does any thing and just hide the pop up and submit button will submit our form.
here I created one div of id modal, it is compulsory to render our pop up.


Friday, 26 September 2014

Select single check box in the presence of multiple checkbox

<input type="checkbox"  name="adsearchPolitical" id="adsearchPolitical" onClick="unselectCheckbox(this);"/>
Political<br />
<input type="checkbox" name="adsearchSocial" id="adsearchSocial" onClick="unselectCheckbox(this);"/>
Social<br />
<input type="checkbox" name="adsearchEconomy" id="adsearchEconomy" onClick="unselectCheckbox(this);"/>
Economy<br />

<script>
function unselectCheckbox(objct)
{
var obj = objct.checked;//saving initial value
document.getElementById("adsearchPolitical").checked=false;
document.getElementById("adsearchSocial").checked=false;
document.getElementById("adsearchEconomy").checked=false;
if(obj==false)
objct.checked=false;
else
objct.checked=true;
}
</script>


NOTE:
if we take var obj = ojbct ;
then if we change the value object object and try to access the previous value of obj then its value already change bcz here obj act as pointer to objct.
That’s y I use
obj=objct.checked;

now this time obj will contains simple value either true or false.

Monday, 22 September 2014

Remove user from usergroup programmatically in liferay, delete user from user group in liferay

In this post I am describing how to remove a user from a user group.
If there is a group and a user is a member of a group then we can delete a member from that group.
In this example I am printing number of members in a group with member details, beside of each user details one delete link is there. If user click on it then javascript function will executes and then by using ajax call we are calling serveResource method and passing userid and groupid.

my jsp page

userremovegroup.jsp

<%@page import="com.liferay.portal.kernel.util.Validator"%>
<%@ taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@page import="com.liferay.portal.model.User"%>
<%@page import="com.liferay.portal.kernel.util.GetterUtil"%>
<%@page import="javax.portlet.PortletURL"%>
<%@ page import="javax.portlet.PortletSession" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui" %>
<portlet:defineObjects />
<liferay-theme:defineObjects />

<%@page import="com.liferay.portal.service.AddressLocalServiceUtil"%>
<portlet:resourceURL var='myInfo' id='myInfo' />


<aui:script>

   
   function deleteMemberFromGroupFunc(userId,groupId)
   {
    var myInfoUrl = "<%= myInfo.toString() %>";
var A = AUI();
   
    var io = A.io.request(myInfoUrl, {
method: 'GET',
dataType: "json",
data:
{
    userIdVal : userId,
    groupIdVal : groupId,
    groupMemberDeleteVal : "true"
},
on: {
success: function() 
{
location.reload();
},
failure: function() 
{
}
}
});
alert("uid: "+userId+"     gid: "+groupId)  ;  
   }
   
</aui:script>







<%

User userr = themeDisplay.getUser();
List<UserGroup> userUserGroups = UserGroupLocalServiceUtil.getUserUserGroups(userr.getUserId());
if(!userUserGroups.isEmpty())
{
Iterator userUserGroupItr = userUserGroups.iterator();
UserGroup userUserGroup = (UserGroup)userUserGroupItr.next();
long classPK = userUserGroup.getUserGroupId();
String className= UserGroup.class.getName();
List<Address> addressList= AddressLocalServiceUtil.getAddresses(themeDisplay.getCompanyId(), UserGroup.class.getName(), classPK);
Iterator addressListIterator = addressList.iterator();


while(addressListIterator.hasNext()){
 Address addressDetailList =(Address)addressListIterator.next();
 %>


 Street1:<%=addressDetailList.getStreet1()%><br />
 Street2:<%=addressDetailList.getStreet2()%><br />
 City:<%=addressDetailList.getCity()%><br /> 
 Zip:<%=addressDetailList.getZip()%><br />
 
 
 <%
}

List<User> userList=UserLocalServiceUtil.getUserGroupUsers(userUserGroup.getUserGroupId());
 Iterator userListIterator = userList.iterator();
 %>
<table class="table table-striped table-hover" >
<thead>
  <th>Name</th>
  <th>Email</th>
  <th>Gender</th>
  <th>Action</th>
</thead>
 <%
 while(userListIterator.hasNext()){
 User userIdListDetails =(User)userListIterator.next();
 //System.out.println("the userids from"+userIdListDetails.getUserId());
 //long userId = userIdList.getUserId();
 User user1 = UserLocalServiceUtil.fetchUser(userIdListDetails.getUserId());
 %>
<tr>
<td><%= user1.getFullName()%></td>
<td><%= user1.getEmailAddress()%></td>
<td><%= user1.getMale() %></td>
<td>
<a href="#" onclick="deleteMemberFromGroupFunc(<%= userIdListDetails.getUserId() %>,<%= userUserGroup.getUserGroupId() %>);">Delete user</a>
</td>
</tr>
 <%
 
}
}
%><%
 

%>
</table>




action class 

DeleteAction.java

public class DeleteAction extends MVCPortlet {

public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException {
boolean deleteGroupMember = Boolean.parseBoolean(PortalUtil.getOriginalServletRequest(httpReq).getParameter("groupMemberDeleteVal"));
long companyId = PortalUtil.getCompanyId(resourceRequest);
long userIdVal = 0l; 
long groupIdVal = 0l;
if(deleteGroupMember) { try{ userIdVal=Long.parseLong(PortalUtil.getOriginalServletRequest(httpReq).getParameter("userIdVal")); groupIdVal=Long.parseLong(PortalUtil.getOriginalServletRequest(httpReq).getParameter("groupIdVal")); 
 }
 catch(NumberFormatException e) 
 { 
 System.out.println("err by asif"); 
 }
 System.out.println("@@ userIdVal: "+userIdVal+"\n@@ groupIdVal: "+groupIdVal); 
 try
 {
 UserLocalServiceUtil.deleteUserGroupUser(groupIdVal, userIdVal); 
 }
 catch (PortalException e) 
{
 System.out.println("portalexception"); e.printStackTrace(); 
 } 
 catch( SystemException e) 
 { 
 System.out.println("systemexception"); 
 e.printStackTrace(); 
 }
 }
}
}

Sunday, 21 September 2014

add user group programmatically in liferay

In this post I will discuss how to add group by using our program.

my jsp page
     userGroup.jsp

<%@page import="com.liferay.portal.service.UserLocalServiceUtil"%>
<%@page import="com.liferay.portal.kernel.util.Validator"%>
<%@page import="com.liferay.portal.service.GroupLocalServiceUtil"%>
<%@page import="com.liferay.portal.model.Group"%>
<%@page import="com.liferay.portal.service.UserGroupLocalServiceUtil"%>
<%@page import="com.liferay.portal.model.UserGroup"%>
<%@page import="com.liferay.portal.service.RegionServiceUtil"%>
<%@page import="com.liferay.portal.model.Region"%>
<%@page import="java.text.Format"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@page import="com.liferay.portal.service.PhoneLocalServiceUtil"%>
<%@page import="com.liferay.portal.model.Phone"%>
<%@page import="com.liferay.portal.model.Contact"%>
<%@page import="com.liferay.portal.model.Address"%>
<%@page import="com.liferay.portal.service.AddressLocalServiceUtil"%>
<%@page import="com.liferay.portal.model.User"%>

<%@page import="com.liferay.portal.service.CountryServiceUtil"%>
<%@page import="com.liferay.portal.model.Country"%>
<%@page import="java.util.List"%>
<%@page import="com.register.common.RegisterConstants"%>
<%@page import="javax.portlet.ActionRequest"%>
<%@page import="javax.portlet.PortletURL"%>
<%@ taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@page import="com.liferay.portal.kernel.util.ListUtil"%>
<%@page import="com.liferay.portal.kernel.util.StringPool"%>
<%@page import="java.util.Iterator"%>



<%
PortletURL updateUserPassword = renderResponse.createActionURL();
updateUserPassword.setParameter(ActionRequest.ACTION_NAME,"addUserGroup");
%>


<aui:form name="fm" method="POST" action="<%=updateUserPassword.toString()%>" >


<aui:input name="group_Name" label="groupName">
</aui:input>


<aui:input name="group_street1" label="street1" >
</aui:input>

<aui:input name="group_street2" label="street2" >
</aui:input>

<aui:input name="group_postalCode" label="postalCode" >
</aui:input>

<aui:input name="group_city" label="city" >
</aui:input>

<aui:select name="group_countryId" label="country"/>

<aui:select name="group_regionId" label="state" />

<aui:input name="group_phoneNumber">
</aui:input>

</aui:form>


my action class
      NewGroupAdd.java


import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PortalClassInvoker;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Address;
import com.liferay.portal.model.Contact;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.User;
import com.liferay.portal.model.UserGroup;
import com.liferay.portal.model.UserGroupRole;
import com.liferay.portal.service.AddressLocalServiceUtil;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.PhoneLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextFactory;
import com.liferay.portal.service.UserGroupLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.register.common.CommonUtil;
import com.register.common.RegisterConstants;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletSession;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletRequest;
import com.mail.MailUtil;
import org.apache.log4j.Logger;

public class NewGroupAdd extends MVCPortlet {

public void addUserGroup(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException, SystemException
{
ServiceContext serviceContext = ServiceContextFactory.getInstance(User.class.getName(), actionRequest);
String groupName = ParamUtil.getString(actionRequest, "group_Name");
String groupStreet1 = ParamUtil.getString(actionRequest, "group_street1");
String groupStreet2 = ParamUtil.getString(actionRequest, "group_street2");
String groupZipcode = ParamUtil.getString(actionRequest, "group_postalCode");
String groupCity = ParamUtil.getString(actionRequest, "group_city");
String groupPhoneNumber = ParamUtil.getString(actionRequest, "group_phoneNumber");
long groupCountryId = ParamUtil.getLong(actionRequest, "group_countryId");
long groupRegionId = ParamUtil.getLong(actionRequest, "group_regionId");

try {
userGroup = UserGroupLocalServiceUtil.addUserGroup(themeDisplay.getUserId(), themeDisplay.getCompanyId(), groupName, "", serviceContext);
} catch (PortalException e) {
_log.error(e);
} catch (SystemException e) {
_log.error(e);
}

try {
UserGroupLocalServiceUtil.addUserUserGroup(user.getUserId(), userGroup.getUserGroupId());
     } catch (SystemException e) {
_log.error(e);
    }
int businessAddressTypeId = CommonUtil.getAddressTypeId("business");
int businessPhoneTypeId = CommonUtil.getPhoneTypeId("business");
try {
userGroupAddress = AddressLocalServiceUtil.addAddress(user.getUserId(), UserGroup.class.getName(), userGroup.getUserGroupId(),
groupStreet1, groupStreet2, "", groupCity, groupZipcode, groupRegionId,
groupCountryId, businessAddressTypeId, true, true, serviceContext);

} catch (PortalException e) {
_log.error(e);
} catch (SystemException e) {
_log.error(e);
}



}
}

Whenever used any object first check that it is null or not then used that object specially when we are reading data from jsp to action class, some time bcz of spelling mistakes we are getting null value and if we use that object/string then null pointer exception generate.




Saturday, 20 September 2014

add user to a usergroup programmatically liferay

This simple code in which I am adding a user in a user group.
This post also having the code of adding user if it user doesn't exist.
my jsp page code

<%
PortletURL updateUserPassword = renderResponse.createActionURL();
updateUserPassword.setParameter(ActionRequest.ACTION_NAME, "addUserGrouppublic ");
User userr = themeDisplay.getUser();
List<UserGroup> userUserGroups = UserGroupLocalServiceUtil.getUserUserGroups(userr.getUserId());
if(!userUserGroups.isEmpty())
{
Iterator userUserGroupItr = userUserGroups.iterator();
UserGroup userUserGroup = (UserGroup)userUserGroupItr.next();
long classPK = userUserGroup.getUserGroupId();

}
%>

<aui:form name="fm" method="POST" action="<%=updateUserPassword.toString()%>" >

 <aui:input name="groupID1" type="hidden" value="<%= userUserGroup.getUserGroupId() %>" />
<div id="phone-fields">
    <div class="lfr-form-row lfr-form-row-inline">
      <div class="row-fields" style="display:flex;">
        <aui:input fieldParam='groupMemberName1' id='groupMemberName1' name="groupMemberName1" label="group-member-name" />
        <aui:input fieldParam='groupMemberEmail1' id='groupMemberEmail1' name="groupMemberEmail1" label="group-member-email" />
        <aui:select id="groupMemberGender1" name="groupMemberGender1" label="group-member-gender">
          <aui:option value="male" label="group-member-female"></aui:option>
          <aui:option value="female" label="group-member-male"></aui:option>
        </aui:select>
    <aui:input fieldParam='groupMemberJob1' id='groupMemberJob1' name="groupMemberJob1" label="group-member-job" />
      </div>
    </div>
  </div>
</aui:form>


action class
AddUser.java{
public void addUserGrouppublic (ActionRequest actionRequest, ActionResponse actionResponse)
  throws PortalException, SystemException
{
    User usr = themeDisplay.getUser();
User loggedUser = null;
        try {
loggedUser = PortalUtil.getUser(actionRequest);
} catch (PortalException e1) {
e1.printStackTrace();
} catch (SystemException e1) {
e1.printStackTrace();
}
long companyId = PortalUtil.getCompanyId(actionRequest);
 Locale locale =PortalUtil.getLocale(actionRequest);
String groupMemberName = (actionRequest.getParameter("groupMemberName1"); 
String groupMemberEmail = (actionRequest.getParameter("groupMemberEmail1");
String groupMemberGender = actionRequest.getParameter("groupMemberGender1");
String groupMemberJob = (actionRequest.getParameter("groupMemberJob1"); 
long userGroupId = Long.parseLong((actionRequest.getParameter("groupID1")));
boolean female = true;
if(Validator.isNotNull(groupMemberGender)) if(groupMemberGender.equalsIgnoreCase("male")) female = false;
try {
try {
usr = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(), groupMemberEmail);
} catch(NoSuchUserException ne){
//if user doesn't exist then enter this catch
//System.out.println("outer>>>..NoSuchUserException");
//ne.printStackTrace();
usr = UserLocalServiceUtil.createUser(CounterLocalServiceUtil.increment(User.class.getName()));
usr.setEmailAddress(groupMemberEmail);
usr.setFirstName(groupMemberName);
usr.setLastName(groupMemberName);
usr.setScreenName(groupMemberName+"_"+CounterLocalServiceUtil.increment(User.class.getName()));
try {
usr = UserLocalServiceUtil.addUser(loggedUser.getUserId(), companyId, true, "", "", true, "", groupMemberEmail, 0l,"", locale, groupMemberName, "", groupMemberName, 0, 0, female, 01, 04, 1987, "", new long[]{}, new long[]{}, new long[]{}, new long[]{}, true, serviceContext);
} catch (PortalException e) {
//System.out.println("outer>>>..PortalException");
e.printStackTrace();
}
}
catch (PortalException e) {
//System.out.println("inner>>>..PortalException");
e.printStackTrace();
}
//System.out.println("HELLOO>>>>>"+usr.getUserId()+">>>>>>>>>>"+userGroupId);
UserGroupLocalServiceUtil.addUserUserGroup(usr.getUserId(), userGroupId);
}
catch (SystemException e) {
//System.out.println("outer>>>..SystemException");
e.printStackTrace();
}

}

Liferay auto fields, adding multiple fields in Liferay, multiple elements adding dynamically

Hi in this post I just post my code of auto field.
Auto field related post is there in net but I faced some problem so I am posting my code that will helpful for me in future and may be helpful for others.

my jsp page code

<%
PortletURL updateUserPassword = renderResponse.createActionURL();
updateUserPassword.setParameter(ActionRequest.ACTION_NAME, "updateUserPassword");
%>

<aui:form name="fm" method="POST" action="<%=updateUserPassword.toString()%>" >


<div id="phone-fields">
    <div class="lfr-form-row lfr-form-row-inline">
      <div class="row-fields" style="display:flex;">
        <aui:input fieldParam='groupMemberName1' id='groupMemberName1' name="groupMemberName1" label="group-member-name" />
        <aui:input fieldParam='groupMemberEmail1' id='groupMemberEmail1' name="groupMemberEmail1" label="group-member-email" />
        <aui:select id="groupMemberGender1" name="groupMemberGender1" label="group-member-gender">
          <aui:option value="male" label="group-member-female"></aui:option>
          <aui:option value="female" label="group-member-male"></aui:option>
        </aui:select>
    <aui:input fieldParam='groupMemberJob1' id='groupMemberJob1' name="groupMemberJob1" label="group-member-job" />
      </div>
    </div>
  </div>
</aui:form>
here id="phone-fields" is the id of div that we will pass to our aui script that will take care to add duplicate fields.
Inside my div 4 fields is there so if we press plus button then these 4 fields will create again and again with different ids.

<aui:script>

AUI().use('liferay-auto-fields',function(A) {
 new Liferay.AutoFields(
       {
           contentBox: '#phone-fields',
           fieldIndexes: '<portlet:namespace />phonesIndexes'
       }
   ).render();
   });
</aui:script>



So jsp is complete now I want to read its value in action class.


public void updateUserPassword(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException, SystemException
{
String numberOfRowsString = actionRequest.getParameter("phonesIndexes");
String[] indexOfRows = numberOfRowsString.split(",");

for( int i=0; i<indexOfRows.length ; i++) //getting value of each row
{
 String groupMemberName = (actionRequest.getParameter("groupMemberName"+indexOfRows[i])).trim(); //as field name constant but there indexes are changes
String groupMemberEmail = (actionRequest.getParameter("groupMemberEmail"+indexOfRows[i])).trim();
String groupMemberGender = actionRequest.getParameter("groupMemberGender"+indexOfRows[i]);
String groupMemberJob = (actionRequest.getParameter("groupMemberJob"+indexOfRows[i])).trim();//deleting leading and trailing space from string
long userGroupId = Long.parseLong((actionRequest.getParameter("groupID1")));

}

variable indexOfRows  will get indexes of rows that user added from jsp.
One row is always there. If user added 5 rows then the value is
{1,2,3,4,5}.
This may be the case user added 4 rows then deleted one row, suppose second row then the value in
indexOfRows is {1,3,4}. We just use fix name(id) of element and then adding indexes to it will get values.


Thanks and regards
md asif aftab


Tuesday, 18 February 2014

Service builder fails because large number of tables

Hi this problem arises because number of different problem.
I faced this problem because of two different reasons, one I already post in my blog and the second reason is sdk unable to create that specific memory.
To avoid this problem you have to modify build-common-plugin.xml file and the path of the file
\liferay-plugins-sdk-6.1.1\build-common-plugin.xml
and the modifications are
from
<jvmarg value="-Xms256m" />
<jvmarg value="-Xmx1024m" />
to
<jvmarg value="-Xms128m" />
<jvmarg value="-Xmx512m" />
some one said that tables will create at time of deployment not at the time of service building but it is wrong service builder must requires space.

may be this is helpful.
Thanks
 

Wednesday, 12 February 2014

Service Builder generated exceptions.

Hi
   In this post I will discuss the problem that I face at the time building the service. This problem arises because of addition of the given below table

<entity name="SB_ErrorCodes" local-service="true" remote-service="false" table="ErrorCodes">
      <column name="ErrorCode" type="int" primary="true" />
     <column name="ErrorDesc" type="String" />
     <column name="ObjectType" type="String" />
    <column name="ObjectId" type="int" />
</entity>

The error on console after service build operation is
BUILD FAILED
D:\liferayWorksapce\liferay-plugins-sdk-6.1.1\build-common-plugin.xml:274: Service Builder generated exceptions.

   If we check then there is no error in table, then what's the problem. The problem is
    We can't have Entities containing "Error" or "Package" in their name, because they mess up with the build process - it's triggering the error handling.
Below is the link of prblem.
https://issues.liferay.com/browse/LPS-27710

Hope this will helpful for others.
Thanks asif aftab

Tuesday, 11 February 2014

More than one database connection with liferay

Hi
  Today my post will describe how to connect with more than one database in Liferay. We can connect simultaneously another database too, means at a time we can connect/access lportal the default database and other database.
      

Step 1: First we have to modify our portal-ext.properties file.
The snippet is

 ###  #MS SQL SERVER CONFIGURATION TO CONNECT OTHER DATABASE
    
      jdbc.anotherdbconfig.driverClassName=net.sourceforge.jtds.jdbc.Driver
      jdbc.anotherdbconfig.url=jdbc:jtds:sqlserver://localhost:1433/mydatabase
      jdbc.anotherdbconfig.username=sa
      jdbc.anotherdbconfig.password=Password

Here I am using MS SQL SERVER EXPRESS 2008 r2
default user name is "sa"
and place of Password you have to provide your own password
and as usual after modification in portal-ext.properties file you have to restart the server then you can feel the change.

Step 2: Create one plugin portlet or you can also use your existing one, then create service builder.      Here my service builder code is
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="webcom.service.layer">
    <author>asif</author>
    <namespace>webcom</namespace>

    <entity name="Asif" local-service="true" remote-service="false" table="asif" data-source="anotherDataSource"  session-factory="anotherSessionFactory">

        <!-- PK fields -->

        <column name="rollId" type="long" primary="true" />

        <!-- Audit fields -->

        <column name="FatherName" type="String" />
        <column name="MotherName" type="String" />
        <column name="Name" type="String" />
   
    </entity>
   
</service-builder>
name="Asif" will describe the name of entity or table class inside your portal and table="asif" is a command to the service builder to create a table of this name only. If you don't use table="somename" then the table name in database is "namespace_entityname".
Then build the service
Now the most important work is to create a file by name ext-spring.xml
the path /docroot/web-inf/src/META-INF/ext-spring.xml
this docroot is the very first folder in your portlet project in which your all class file will exist.

<?xml version="1.0" encoding="UTF-8"?>

<beans
    default-destroy-method="destroy"
    default-init-method="afterPropertiesSet"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
>

       <bean id="anotherDataSource" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
              <property name="targetDataSource" ref="anotherDataSourceWrapper" />
       </bean>
   
       <bean id="anotherDataSourceImpl" class="com.liferay.portal.dao.jdbc.spring.DataSourceFactoryBean">
              <property name="propertyPrefix" value="jdbc.anotherdbconfig." />
       </bean>
      
       <bean id="anotherDataSourceWrapper" class="com.liferay.portal.dao.jdbc.util.DataSourceWrapper">
              <constructor-arg ref="anotherDataSourceImpl" />
       </bean>
     
       <bean class="com.liferay.portal.dao.jdbc.util.DataSourceSwapper">
              <property name="liferayDataSourceWrapper" ref="anotherDataSourceWrapper" />
       </bean>
      
       <bean id="anotherHibernateSessionFactory" class="com.liferay.portal.kernel.spring.util.SpringFactoryUtil"
              factory-method="newBean">
              <constructor-arg value="com.liferay.portal.spring.hibernate.PortletHibernateConfiguration" />
              <constructor-arg>
                     <map>
                           <entry key="dataSource" value-ref="anotherDataSource" />
                     </map>
              </constructor-arg>
       </bean>
      
       <bean id="anotherSessionFactory" class="com.liferay.portal.kernel.spring.util.SpringFactoryUtil" factory-method="newBean">
              <constructor-arg
                     value="com.liferay.portal.dao.orm.hibernate.PortletSessionFactoryImpl" />
              <constructor-arg>
                     <map>
                           <entry key="dataSource" value-ref="anotherDataSource" />
                           <entry key="sessionFactoryClassLoader" value-ref="portletClassLoader" />
                           <entry key="sessionFactoryImplementor" value-ref="anotherHibernateSessionFactory" />
                     </map>
              </constructor-arg>
       </bean>

</beans>
anotherdbconfig. Is the propertyPrefix which we have mention in ext-spring.xml file

Now we have to provide this information to entity which we have configured in service.xml .
In enity tag we have two attributes from that we can explitly said about datasource and session factory information .

<entity name="TableFromAnotherDataSource" table="TableFromAnotherDataSource"  
 local-service="true" remote-service="true" data-source="anotherDataSource"  
session-factory="anotherSessionFactory">
           <column name="IFADSId" type="long" primary="true" />
           <column name="Description" type="String" />
  </entity>
Note: When we use other data source for plugin portlet when we run service builder then tables creation script is not create so we have to create table manually in database if the table is new.
If you need create table script you can see in the class entityModelImpl.java

public static final String TABLE_SQL_CREATE = "create table TableFromAnotherDataSource (IFADSId LONG not null primary key,Description VARCHAR(75) null)";

You can also find data source and session factory that is used by your Entity class
public static final String DATA_SOURCE = "anotherDataSource";
public static final String SESSION_FACTORY = "anotherSessionFactory"; 

Hope this will helpful for you.














Tuesday, 21 January 2014

Configuring Mail server in Liferay , Mail server configuration in liferay, could not connect to smtp host localhost port 25


Add this lines of code in your portal-ext.properties

    mail.session.mail.pop3.host=pop.gmail.com
    mail.session.mail.pop3.password=PASSWORD
    mail.session.mail.pop3.port=110
    mail.session.mail.pop3.user=USER
    mail.session.mail.imap.host=imap.gmail.com
    mail.session.mail.imap.port=993
    mail.session.mail.store.protocol=imap
    mail.session.mail.transport.protocol=smtp
    mail.session.mail.smtp.host=smtp.gmail.com
    mail.session.mail.smtp.password=PASSWD
    mail.session.mail.smtp.user=USERID@gmail.com
    mail.session.mail.smtp.port=465
    mail.session.mail.smtp.auth=true
    mail.session.mail.smtp.starttls.enable=true
    mail.session.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
  
     * Please user your password in place of PASSWD and your gmail user id in place of USERID.
     By three different ways we can configure mail server in Liferay. I am using Liferay 6.2 and initially I got an error that could not connect to smtp host localhost port 25 in liferay by using different code. So I used above code and my mail server is configured properly and my application is able to send mail to the user in forgot password case.
And please see this link. This link help me to solve the issue.
https://www.permeance.com.au/web/tim.telcik/home/-/blogs/how-do-i-configure-liferay-portal-to-use-google-mail
Thanks
asif aftab

Wednesday, 1 January 2014

MS SQL Server Management studion Express 2008 r2 connection with Liferay 6.2

Hi
First brief description
1) I am using Liferay 6.2.
2) I want to connect with MS SQL Server Management Studio Express 2008 r2 (This is similar to MS SQL Server but with  lots of limitations).

Error: That I got was
IOExcpetion: refuse to connect.


Now the solution is
1) Configuration of MS SQL Server connection in portal-ext.properties file

   

      jdbc.default.driverClassName=net.sourceforge.jtds.jdbc.Driver

      jdbc.default.url=jdbc:jtds:sqlserver://localhost:1433/lportal

      jdbc.default.username=sa (this is default login name )

      jdbc.default.password=your password


    
The main thing is we have to change the port of tcp/ip to 1433 the default port of MS SQL Server Management Studio Express 2008 r2.
Start menu of windows then

 

1. MS SQL Server 2008 r2 -> configuration tool -> SQL Server configuration manager -> yes(pop up)

  then on extreme left select there is a tree structure then

2. SQL Server network configuration -> Protocols for sql server -> rt click on tcp/ip and enable it

3. Double click on tcp/ip then one pop up will display

4. Select IP Adrees tab, lots of IPAdress block you can see and inside this block you can see one label IP Address value having different values. You have to check which IP Adress having value 127.0.0.1 then change its tcp port value to 1433.

5. Some time tcp port is not enable so please enable and also makes ip4 and all ip tcp port value

is 1433(default port of sql server express 2008 r2).

Hence try to connect, this time this will work.
Thanks
asif aftab