Sunday, 22 November 2015

comprator and comprable example

comprator and comprable example

http://www.codejava.net/java-core/collections/sorting-arrays-examples-with-comparable-and-comparator

Friday, 20 November 2015

java assignment

1. For any given date(in MM/DD/YYYY format) calculate 10th working day(exclude Saturdays, Sundays and span holidays) and display the 10th Working day.(Get SPAN holidays from http://ispan.com/Lists/Holiday/AllItems.aspx

2.            Employee Maintenance System
Write a program to read the following parameters for each Employee.
a.            First name
b.            Last name
c.             Date of Join (dd/mm/yyyy)
d.            Date of Birth
e.            Gender (M or F)
f.             Temporary (True or false)
g.            Department (ASG/Sales/Engineering/Support/Accounts)
h.            Salary
i.      Designation(Java developer, Application Tester, Quality analyser, Project Manager etc)

After you read the input for about 10 records, display the below options to the user to choose from.

1.            Display employees in Ascending order of their Last name
2.            Display employees for the given Department (Note: selecting the option 2, should ask the user to enter Department name and then display the employees pertaining to that department)
3.            Display the age of all employees
4.            Display the permanent employees
5.            Display the employees with salary > 10000.
6.            Search for an Employee (First name starts with)
7.      Display employees who belongs to only engineering department and Male employee
8.      Calculate average salary of all employees.
9.            Exit

3.            Shop Maintenance:
Note: Hardcode the products data in the program.

Show the following menu when the application starts.

***************************************************
        *                             Welcome to <shop name> Shop                                    *
        ***************************************************
1.            Display Products
2.            Search Product
3.            Purchase Product
4.            Display shopping cart
5.            Print Invoice
6.            Exit

1. Display Products :

        ************************************************************************************
        SKU#              Product Name                                   Stock                     Price                Manufacturer                                     **
        ************************************************************************************
        Xxx                 Xxxxxxxx                                             xx                           xxxx.xx                 xxxxxxxxxxxx


Enter the item SKU number to purchase the item.

Note: Once the item SKU has been entered and the item is in stock, it has to be reduced by 1 in the quantity of products.

2.  Search Product :

Enter the product SKU or Name (starts with) :

Product you have searched for :

<Display products header and product details to be displayed.>

No match found for the given input.

3. Purchase Product :

Enter the item SKU number to purchase the item :

Note: Once the item SKU has been entered and the item is in stock, it has to be reduced by 1 in the quantity of products.

4. Display Shopping cart

       ************************************************************************************
        SKU#              Product Name                                   Quantity              Price                    Manufacturer                                 **
        ************************************************************************************
       Xxx                  Xxxxxxxx                                             xx                           xxxx.xx                 xxxxxxxxxxxx
       Xxx                  Xxxxxxxx                                             xx                           xxxx.xx                 xxxxxxxxxxxx
*************************************************************************************                                                                              
Total                                                                                      xx                           xxxx.xx
*************************************************************************************
5.  Print Invoice

                                                                                <Shop Name>
                                                                                <Address 1>
Invoice Details
               *************************************************************************************
             SKU#              Product Name                       Quantity              Price                                          Tax                                                   **
              **************************************************************************************
                Xxx                  Xxxxxxxx                                    xx                           xxxx.xx                                 <10% tax amount>
                Xxx                  Xxxxxxxx                                    xx                           xxxx. xx                                 <10% tax amount>
            ***************************************************************************************                                                                              
           Total (Incl of Tax 10%: xx)                                 xx                           xxxx.xx(without tax)      <10% tax amount>       xxxx.xx(total with Tax)    
           ***************************************************************************************

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.