Friday, 20 November 2015

if we create brand than client should be hide (hiding drop down box logic)

<%

 long orgId = OrganizationLocalServiceUtil.getOrganizations(-1, -1).get(0).getOrganizationId();

 List<Organization> organizations = themeDisplay.getUser().getOrganizations();
 if(organizations.size() > 0)
 orgId = organizations.get(0).getOrganizationId();

 String tenet = JobUtil.getOrganizationType(orgId);

  List<Organization> orgs = OrganizationLocalServiceUtil.getSuborganizations(themeDisplay.getCompanyId(), orgId);

boolean brandExits=false;
boolean clientExits=false;

if(tenet.equalsIgnoreCase("regular-organization")){
if(orgs.size() >0){
for(Organization org:orgs){
String organizationType1 = JobUtil.getOrganizationType(org.getOrganizationId());

if(organizationType1.equalsIgnoreCase("client")){
clientExits=true;
}

/*  if(organizationType1.equalsIgnoreCase("brand")){
brandExits=true;
} */
}
}
}
System.out.println("brandExits  " +clientExits);

if(!clientExits){
%>
<style>
#clientType{
display:none;
}
</style>
<%
}
List<Organization> orgList = JobUtil.getOrganizationByCompanyId(themeDisplay.getCompanyId());
String organizationType = JobUtil.getOrganizationType(organizations.get(0).getOrganizationId());
String disabled = "false";

for(Organization org : orgList){
String orgType = JobUtil.getOrganizationType(org.getOrganizationId());
if(Validator.isNotNull(orgType)){
if(orgType.contains("client")){
orgId = org.getOrganizationId();
}
}}
%>

<div id="clientType">
<aui:select label="client" helpMessage="Choose your client" name="clientOrgId">
<%if(organizationType.equalsIgnoreCase("client")){%>
<aui:option value="<%=organizations.get(0).getOrganizationId() %>"><%=organizations.get(0).getName() %></aui:option>
<%}else if(!clientExits){%>
<aui:option value="<%=organizations.get(0).getOrganizationId() %>"><%=organizations.get(0).getName() %></aui:option>
<%}else{%>
<option selected disabled hidden value=''>--select client--</option>

<%for(Organization org : orgList){
String orgType = JobUtil.getOrganizationType(org.getOrganizationId());
System.out.println("orgType is---->"+orgType);
if(Validator.isNotNull(orgType)){
if(orgType.equalsIgnoreCase("client")){%>
<aui:option value="<%=org.getOrganizationId() %>"><%=org.getName() %></aui:option>
<%}}}} %>
</aui:select>
</div>

Captcha to be shown in case of 3 times password failed

Captcha should  be show if password faild 3 times password failed

 This code we need to write inside public class UserLoginActionValidate extends BaseStrutsPortletAction in hook.

String enteredCaptchaText = ParamUtil.getString(actionRequest,"captchaText");
HttpSession httpSession = PortalUtil.getHttpServletRequest(actionRequest).getSession();
int loginAttemptsCount = 0;
try{
String count = (String) httpSession.getAttribute("LIFERAY_SHARED_count");
System.out.println("helloooo=---"+count);
System.out.println("login count-------"+count);
loginAttemptsCount = Integer.parseInt(count);
}
catch(Exception e){

}
System.out.println("login count outside loop-------"+loginAttemptsCount);
try {
PortletSession session = actionRequest.getPortletSession();
session.setAttribute("captcha",0, PortletSession.PORTLET_SCOPE);

if(loginAttemptsCount>3)
{
String captchaText = getCaptchaValueFromSession(session);
if (Validator.isNull(captchaText)) {
// throw new
// Exception("Internal Error! Captcha text not found in session");
SessionErrors.add(actionRequest, "invalid-captcha");
return;
}
if (!captchaText.equals(enteredCaptchaText)) {
System.out.println("IS eroorrrrrr");
// throw new Exception("Invalid captcha text. Please reenter.");
SessionErrors.add(actionRequest, "text-verification-failed");
return;

}}


}/*}*/ catch (NoSuchUserException e) {
SessionErrors.add(actionRequest, "invalid-authentication");
loginAttemptsCount = loginAttemptsCount+1;
System.out.println("loginAttemptsCount"+loginAttemptsCount);
httpSession.setAttribute("LIFERAY_SHARED_count",String.valueOf(loginAttemptsCount));
return;
} catch (CaptchaException e) {
loginAttemptsCount = loginAttemptsCount+1;
System.out.println("loginAttemptsCount"+loginAttemptsCount);
httpSession.setAttribute("LIFERAY_SHARED_count",String.valueOf(loginAttemptsCount));
SessionErrors.add(actionRequest, "invalid-authentication");
return;
}


originalStrutsPortletAction.processAction(originalStrutsPortletAction,
portletConfig, actionRequest, actionResponse);
}


Step2-some code we need to write in login.jsp

<%
int loginfailedcount = 0;
try{
HttpSession httpSession = request.getSession(false);
String count = (String) httpSession.getAttribute("LIFERAY_SHARED_count");
System.out.println("helloooo=---"+count);
System.out.println("login count-------"+count);
loginfailedcount = Integer.parseInt(count);
}
catch(Exception e){}
%>


  <%
  System.out.println("themeDisplay.getUser().getFailedLoginAttempts()-----"+themeDisplay.getUser().getFailedLoginAttempts());
               if(loginfailedcount > 3){ %>
<portlet:resourceURL var="captchaURL">
<portlet:param name="struts_action" value="/login/captcha"/>
</portlet:resourceURL>

<liferay-ui:captcha url="<%= captchaURL %>" />
<%} %>

Tuesday, 17 November 2015

Thursday, 29 October 2015

Thursday, 1 October 2015

hook





DynamicQuery in Liferay


Liferay provides very powerful tool service-builder in-order to deal with custom database entity.
It generates many methods to retrieve results from database just like you can have your own finder methods on entity.

Intro and Why?
But, this not suffice all we may need. Many times we would need complex result set from database table by performing aggregate SQL operations such as max,avg etc, and also in clause, and/or operations or we would need to fetch some of fields rather the whole entity object[database entity mapped object].

Here, DynamicQuery would be useful.

How?

Dealing with Liferay's built in entities like Users, Organizations, Assets, AssetCategories
As DynamicQuery API looks for current classloader, for access, but as you are dealing with Portal level class [User.class], you have to specify portalClassLoader as below.

 ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();  
 DynamicQuery query = DynamicQueryFactoryUtil.forClass(User.class, portalClassLoader);  


Dealing with custom entity within portlet.

DynamicQuery dynamicQuery=DynamicQueryFactoryUtil.forClass(Application.class);

Here we have just got dynamicQuery object and having applied any query criteria.
Lets do that.

Following util classes would be useful for it.

PropertyFactoryUtil.java, RestrictionsFactoryUtil.java, ProjectionFactoryUtil.java, OrderFactoryUtil.java

Lets understand by example.

 DynamicQuery dynamicQuery=DynamicQueryFactoryUtil.forClass(CustomEntity.class);  
 dynamicQuery.add(RestrictionsFactoryUtil.eq("status", "active"));  
 dynamicQuery.addOrder(OrderFactoryUtil.asc("name"));  
 dynamicQuery.setLimit(0, 5) ;  
 List<CustomEntity> list=ApplicationLocalServiceUtil.dynamicQuery(dynamicQuery);  

Though above example is self-explanatory, let me tell that it will return list of 5 objects[of CustomEntity] who has status field as active and results will be ordered[ascending] by name field.

Above things can be easily achieved by finder on status field and having order on name in service.xml

Lets add some more complexity in our query.
Say, You need list of 5 CustomEntity having name starts with"ABC" and status as active and order by name.

Here you go.

 DynamicQuery dynamicQuery=DynamicQueryFactoryUtil.forClass(CustomEntity.class);  
 dynamicQuery.add(RestrictionsFactoryUtil.and(RestrictionsFactoryUtil.eq("status", "active"),RestrictionsFactoryUtil.ilike("name", "ABC")));  
 dynamicQuery.addOrder(OrderFactoryUtil.asc("name"));  
 dynamicQuery.setLimit(0, 5) ;  
 List<CustomEntity> list=ApplicationLocalServiceUtil.dynamicQuery(dynamicQuery);  


You can also add criteria like greater than, less than, in clause etc using RestrictionsFactoryUtil.

Let say now you need just some of tuples rather whole customEntity object.

dynamicQuery.setProjection(ProjectionFactoryUtil.projectionlist().add(ProjectionFactoryUtil.property("name")).add(ProjectionFactoryUtil.property("age")));

By setting projection as above, output result would be list of array of Objects.[with name,age values].


ProjectionFactoryUtil can be utilized to have aggregate functions like min,max,avg,distinct,count etc.













Wednesday, 30 September 2015

Liferay internationalization custom portlet

https://www.liferay.com/documentation/liferay-portal/6.1/development/-/ai/localize-your-portlet

Saturday, 26 September 2015

How to Add Liferay User inside Organization by programatically? How to assign role to user and organization by programatically

this code is working for me, i thing it will help you to user creation and create the role 

private Organization CreateRegularOrg(String name, long companyId,ActionRequest actionRequest) throws PortalException, SystemException {
     
ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
Company company = CompanyLocalServiceUtil.getCompany(companyId);
ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();
serviceContext.setCompanyId(companyId);
Organization org = null;
try {
List<Address> addresses = UsersAdminUtil.getAddresses(actionRequest);
List<EmailAddress> emailAddresses = UsersAdminUtil.getEmailAddresses(
actionRequest);
List<OrgLabor> orgLabors = UsersAdminUtil.getOrgLabors(actionRequest);
List<Phone> phones = UsersAdminUtil.getPhones(actionRequest);
List<Website> websites = UsersAdminUtil.getWebsites(actionRequest);

org = OrganizationServiceUtil.addOrganization(
0, tenantName, "regular-organization", 19014, 19, 12017,
StringPool.BLANK, true, addresses, emailAddresses, orgLabors, phones,
websites, serviceContext);
System.out.println("org=======11111111============"+org);

/*org = OrganizationServiceUtil.addOrganization(0, tenantName,"regular-organization", true, 19014, 19, 12017,StringPool.BLANK, true, serviceContext);*/
org.setCompanyId(companyId);
org = OrganizationLocalServiceUtil.updateOrganization(org);


//Group group = GroupLocalServiceUtil.getCompanyGroup(themeDisplay.getCompanyId());
Group group = GroupLocalServiceUtil.getOrganizationGroup(themeDisplay.getCompanyId(), org.getOrganizationId());
System.out.println("Company ID from Theme Display -> "+themeDisplay.getCompanyId());
System.out.println("Company ID from Group -> "+group.getCompanyId());
System.out.println("Org ID from Group -> "+group.getOrganizationId());
group.setCompanyId(companyId);
GroupLocalServiceUtil.updateGroup(group);

System.out.println("org===========22222222222========"+org);
         
} catch (PortalException e) {
e.printStackTrace();
} catch (SystemException e) {
e.printStackTrace();
}

return org;
}

private User addOrgUser(Organization org, String tenantAdminName,String tenantAdminEmailId, ActionRequest actionRequest)
throws PortalException, SystemException {
Contact contact =null;
ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
System.out.println("org.getCompanyId()  " +org.getCompanyId());
//Role role = RoleLocalServiceUtil.getRole(org.getCompanyId(), "Organization Administrator");
String greeting="Welcome Admin";
User user=null;
try {
user = UserLocalServiceUtil.createUser(CounterLocalServiceUtil.increment());
;
user.setFirstName(tenantAdminName);
user.setEmailAddress(tenantAdminEmailId);
user.setScreenName(tenantAdminName);
user.setCompanyId(org.getCompanyId());
user.setCreateDate(new Date());
user.setModifiedDate(new Date());
user.setGreeting(greeting);
user.setLanguageId(themeDisplay.getLanguageId());
user.setTimeZoneId(themeDisplay.getTimeZone().getDisplayName());
user.setPassword("test");
//insert contact for user
long idContact = CounterLocalServiceUtil.increment(Contact.class.getName());
contact = ContactLocalServiceUtil.createContact(idContact);
contact.setCompanyId(org.getCompanyId());
contact.setCreateDate(new Date());
contact.setUserName(tenantAdminName);
contact.setUserId(user.getUserId());
contact.setModifiedDate(new Date());
contact.setFirstName("contact-"+contact.getContactId());
contact.setLastName("contact-"+contact.getContactId());
contact.setMiddleName("contact-"+contact.getContactId());
contact.setPrefixId(0);
contact.setSuffixId(0);
contact.setJobTitle(StringPool.BLANK); 
contact.setBirthday(new Date());
contact=ContactLocalServiceUtil.addContact(contact); 
user.setContactId(contact.getContactId());
UserLocalServiceUtil.addOrganizationUser(org.getOrganizationId(),user);
User createdUser = UserLocalServiceUtil.addUser(user);

//Insert Group for a user
ClassName clsNameUser = ClassNameLocalServiceUtil.getClassName("com.liferay.portal.model.User");
long classNameId=clsNameUser.getClassNameId();
long gpId = CounterLocalServiceUtil.increment(Group.class.getName()); 
Group userGrp = GroupLocalServiceUtil.createGroup(gpId);
//User userCreated = UserLocalServiceUtil.getUserByScreenName(org.getCompanyId(), tenantAdminName);
userGrp.setClassNameId(classNameId);
userGrp.setClassPK(createdUser.getUserId());
userGrp.setCompanyId(org.getCompanyId());
userGrp.setName(String.valueOf(createdUser.getUserId()));
System.out.println("group name===========");
userGrp.setFriendlyURL("/tenantAdminName");
userGrp.setCreatorUserId(PortalUtil.getUserId(actionRequest));
userGrp.setActive(true);
Group addedGroup = GroupLocalServiceUtil.addGroup(userGrp);
//Create AssetEntry 
long assetEntryId = CounterLocalServiceUtil.increment(AssetEntry.class.getName());
AssetEntry ae = AssetEntryLocalServiceUtil.createAssetEntry(assetEntryId);
ae.setCompanyId(org.getCompanyId());
ae.setClassPK(createdUser.getUserId());
ae.setGroupId(addedGroup.getGroupId());
ae.setClassNameId(classNameId);
ae.setTitle(tenantAdminName);
ae.setUserId(createdUser.getUserId());
AssetEntryLocalServiceUtil.addAssetEntry(ae);
// role with user
long userid[] = {user.getUserId()};
long groupId = OrganizationLocalServiceUtil.getOrganization(
   org.getCompanyId(), org.getName()).getGroup().getGroupId();
System.out.println("group id--->"+groupId);
//UserLocalServiceUtil.addRoleUsers(role.getRoleId(), userid);
long roleId = RoleLocalServiceUtil.getRole(
   org.getCompanyId(),"Organization Administrator").getRoleId();
System.out.println("role id--->"+roleId);
UserGroupRoleLocalServiceUtil.addUserGroupRoles(
createdUser.getUserId(), groupId, new long[] { roleId });
long adminRoleId = RoleLocalServiceUtil.getRole(
   org.getCompanyId(),"Administrator").getRoleId();
RoleLocalServiceUtil.addUserRole(createdUser.getUserId(), adminRoleId);

long powerUserRoleId = RoleLocalServiceUtil.getRole(
   org.getCompanyId(),"Power User").getRoleId();
System.out.println("role id--->"+roleId);
RoleLocalServiceUtil.addUserRole(createdUser.getUserId(), powerUserRoleId);
/*UserGroupRoleLocalServiceUtil.addUserGroupRoles(
createdUser.getUserId(), groupId, new long[] { roleId });*/
//long roleids[]={role.getRoleId(),rolePu.getRoleId()};
//UserLocalServiceUtil.addRoleUser(roleId, userId);
//UserGroupRoleLocalServiceUtil.addUserGroupRoles(user.getUserId(), user.getGroupId(), roleids);
//Insert ResourcePermission for a User
/*long resPermId = CounterLocalServiceUtil.increment(ResourcePermission.class.getName());
ResourcePermission rpEntry = ResourcePermissionLocalServiceUtil.createResourcePermission(resPermId);
rpEntry.setCompanyId(org.getCompanyId());
rpEntry.setName("com.liferay.portal.model.User");
rpEntry.setRoleId(role.getRoleId());
rpEntry.setScope(4);
rpEntry.setActionIds(31);
rpEntry.setPrimaryKey(userid[0]);
ResourcePermissionLocalServiceUtil.addResourcePermission(rpEntry); */

//Insert Layoutset for public and private 
long layoutSetIdPub = CounterLocalServiceUtil.increment(LayoutSet.class.getName());
LayoutSet layoutSetPub=LayoutSetLocalServiceUtil.createLayoutSet(layoutSetIdPub);
layoutSetPub.setCompanyId(org.getCompanyId());
layoutSetPub.setPrivateLayout(false);
layoutSetPub.setGroupId(addedGroup.getGroupId());
layoutSetPub.setThemeId("classic");
try{
LayoutSetLocalServiceUtil.addLayoutSet(layoutSetPub); 
}catch(SystemException se){

}

long layoutSetIdPriv= CounterLocalServiceUtil.increment(LayoutSet.class.getName());
LayoutSet layoutSetPriv=LayoutSetLocalServiceUtil.createLayoutSet(layoutSetIdPriv);
layoutSetPriv.setCompanyId(org.getCompanyId());
layoutSetPriv.setPrivateLayout(true);
layoutSetPriv.setThemeId("classic");
layoutSetPriv.setGroupId(addedGroup.getGroupId());
try{
LayoutSetLocalServiceUtil.addLayoutSet(layoutSetPriv); 
}catch(SystemException se){ 
se.printStackTrace();
}
} catch (SystemException e) {
e.printStackTrace();
}

return user;

}



// Calling CreateRegularOrg method and addOrgUser method

Organization org = null;
org = CreateRegularOrg(tenantName, company.getCompanyId());
            System.out.println("calling org========================================"+org);
         
            addOrgUser(org, tenantAdminName,tenantAdminEmailId,actionRequest);