Monday, 11 May 2015

what are MVC advantages

what are MVC advantages>>
1) Clear architecture design
2) Easy to expand the architecture
3)Multiple view like  pdf, csv, json, xml


Saturday, 9 May 2015

Hibernate n+1 solution

Hibernate n+1 solution.
Hiberntae has n+1 problame to solve this we can use the
1) Join
2)Criteria query
========================================
Let say i have one "client " and many "product" relationship here is one to many we use but when we
try to fetch the client records it also fetch product records by default lazily.

<<<<We need to use this query for to resoled this pro blame>>>
-------------------------------------------------------------
"from Client client join fetch client.product Product"
-------------------------------------------------------------
<<<<<Hibernate will Gen rate SQL query like this.>>>>>
-------------------------------------------------------------
Select * From Client client Left Outer Join Product product ON product.product_id =client.product_id
-------------------------------------------------------------

Other way is to use Criteria Query
Criteria cr =session.createCriteria(Client.class);
cr.setFetchMode("product",FetchMode.EAGER);


Thursday, 7 May 2015

email jquery validation


radio button validation in jquery

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>

<html>
<head>

<script>
$(document).ready(function(){
$('#companySelect').change(function () {
var selectedValue = $(this).prop('value');
if (selectedValue == '--Please Select') {
$('#officeName').empty();
} else {
$.post('${pageContext.request.contextPath}/docmanager/admin/officeListjson', selectedValue, function(data) {
$('#officeName').empty();
$.each(data, function(index,value) {
//alert("index"+index +"-value="+value.officeId);
$('#officeName').append($("<option></option>").val(value.officeId).html(value.officeName));
});
}, 'json');
}
});

$("form[id='createUserForm']").submit(function() {
   $(this).ajaxSubmit({
    dataType: "json",
    //success: dialogSaveStatusCheck,
    success: function(data) {
       if(data.success == 'true') alert('Saved Successfully..');
       else alert('Failed adding person: ' + data.success + ', ' + data.errorMessage);
     },
  error: formSaveError
   });
   return false;
});

$('#btnSubmit').click(function(e) {
var isValid = true;
if ( $('#fName').val() == '' )
{
             isValid = false;
              $('#fName').css({
                   "border": "1px solid red",
                   "background": "#FFCECE"
               });
}
var fName = $('#fName').val();
if(validateFNameSize(fName)){
//$('#fNameErr').hide();
}
else {

$("#fNameErr").text("Invalid First Name")
            $('#fNameErr').css({
                "border": "1px solid red",
                "background": "#FFCECE"
            });
         
            e.preventDefault();
             $('#fName').focus();
        }

if ( $('#lName').val() == '' )
{ isValid = false;
              $('#lName').css({
                   "border": "1px solid red",
                   "background": "#FFCECE"
               });
}
var lName = $('#lName').val()
if(validateLNameSize(fName)){
//$('#fNameErr').hide();
}
else {

$("#lNameErr").text("Invalid Last Name")
           $('#lNameErr').css({
               "border": "1px solid red",
               "background": "#FFCECE"
           });
         
           e.preventDefault();
            $('#LName').focus();
       }



if ( $('#email').val() == '' )
{
isValid = false;
            $('#email').css({
                 "border": "1px solid red",
                 "background": "#FFCECE"
             });
}

if ( $('#login').val() == '' )
{
isValid = false;
            $('#login').css({
                 "border": "1px solid red",
                 "background": "#FFCECE"
             });
}
var login = $('#login').val()
if(validatelogin(login)){
//$('#fNameErr').hide();
}
else {

$("#login").text("Invalid login Name")
           $('#login').css({
               "border": "1px solid red",
               "background": "#FFCECE"
           });
         
           e.preventDefault();
            $('#LName').focus();
       }





if ( $('#officeName').val() == '' )
{
isValid = false;
            $('#officeName').css({
                 "border": "1px solid red",
                 "background": "#FFCECE"
             });
}
var officeName = $('#officeName').val()
if(validateLNameSize(officeName)){
//$('#fNameErr').hide();
}
else {

$("#lNameErr").text("Invalid office Name")
           $('#lNameErr').css({
               "border": "1px solid red",
               "background": "#FFCECE"
           });
         
           e.preventDefault();
            $('#LName').focus();
       }




if ( $('#password').val() == '' )
{
isValid = false;
            $('#password').css({
                 "border": "1px solid red",
                 "background": "#FFCECE"
             });
}
var passwordName = $('#password').val()
if(validatePassword(passwordName)){
//$('#fNameErr').hide();
}
else {

$("#pwdErr").text("Invalid Password")
           $('#pwdErr').css({
               "border": "1px solid red",
               "background": "#FFCECE"
           });
         
           e.preventDefault();
         
       }



var sEmail = $('#email').val();
 if ($.trim(sEmail).length == 0) {
          // alert('Please enter valid email address');
           e.preventDefault();
       }
       if (validateEmail(sEmail)) {
           //alert('Email is valid');
           $('#emailErr').hide();
       }
       else {
       
        $("#emailErr").text("Invalid Email Address")
           $('#emailErr').css({
               "border": "1px solid red",
               "background": "#FFCECE"
           });
           //alert('Invalid Email Address');
           e.preventDefault();
            $('#email').focus();
       }
     
if (isValid == false)
            e.preventDefault();

     
         $('#createUserForm input').blur(function() {
       
        alert('Thanks');
            if ($.trim($(this).val()) == '') {
                isValid = false;
                $(this).css({
                    "border": "1px solid red",
                    "background": "#FFCECE"
                });
            }
            else {
                $(this).css({
                    "border": "",
                    "background": ""
                });
            }
        });
        if (isValid == false)
            e.preventDefault();
        else
            alert('Thank you for submitting');
    });

});

function validateEmail(sEmail) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (filter.test(sEmail)) {
        return true;
    }
    else {
        return false;
    }
}
function validateFNameSize(fName) {
     if (fName.length <= 6) {    
         $("#fNameErr").text("First Name must be at least 5 characters long")
         $('#fNameErr').css({
             "border": "1px solid red",
             "background": "#FFCECE"
         });
         return true;
       
     }  
    else {
        return false;
    }
}
function validateLNameSize(lName) {
    if (lName.length <= 6) {    
        $("#lNameErr").text("Last Name must be at least 5 characters long")
        $('#lNameErr').css({
            "border": "1px solid red",
            "background": "#FFCECE"
        });
        return true;
     
    }  
   else {
       return false;
   }
}

function validatePassword(passwordName) {
    if (passwordName.length <= 3) {    
        $("#pwdErr").text("Password must be at least 3 characters long")
        $('#pwdErr').css({
            "border": "1px solid red",
            "background": "#FFCECE"
        });
        return true;
     
    }  
   else {
       return false;
   }
}

function validatelogin(login) {
    if (login.length <= 6) {    
        $("#loginErr").text("login must be at least 6 characters long")
        $('#loginErr').css({
            "border": "1px solid red",
            "background": "#FFCECE"
        });
        return true;
     
    }  
   else {
       return false;
   }
}



</script>

</head>
<body>
<form:form  id="createUserForm" method="POST" commandName="user" action="${pageContext.request.contextPath}/docmanager/admin/save">
<div class="mainDiv">
<div class="inner1Div">USER DETAILS</div>

<table border="1" class="tableNav">
<tr>
<td>FirstName * : <form:input id="fName" path="firstName" /><!-- <div class="ui-widget">
  <div class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
    <p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
      <strong>Alert:</strong> Sample ui-state-error style.</p>
  </div>
</div> -->

<div id="fNameErr"></div></td>
<td>LastName *: <form:input id="lName" path="lastName" /><div id="lNameErr"></div></td>
<td>Email *: <form:input id="email" path="email" /><div id="emailErr"></div></td>

</tr>
<tr>
<td>Login *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : <form:input id="login" path="login" /><div id="loginErr"></div></td>
<td>Password * : <form:password id="password"path="password" /><div id="pwdErr"></div></td>
</tr>
</table>

</div>

<div class="_blankDiv"></div>

<div class="mainDiv">
<div class="inner1Div">USER ACCESS</div>
<table border="1" class="tableNav">
<tr>
<td><form:label path="companyName"></form:label></td>
<td>CompanyId* <form:select path="companyId"
id="companySelect" cssClass="select">
<form:option value="-" label="--Please Select" />
<form:options path="companyId" items="${compList}"
itemValue="companyId" itemLabel="companyName" />
</form:select></td>

<td><form:label path="officeId"></form:label></td>
<td>OfficeId*<form:select id="officeName" path="officeId"
cssClass="select"></form:select></td>
</tr>


</table>

</div>

<div class="_blankDiv"></div>

<div class="mainDiv">
<div class="inner1Div">USER ROLE</div>
<table class="tableNav">
<tr>
<td><form:radiobutton path="role" value="3"/>USER_ROLE</td>
<td><form:radiobutton path="role" value="2"/>ADMIN_ROLE</td>
<td><form:radiobutton path="role" value="1" disabled="true"/>SUPER_USER</td>
</tr>
</table>
</div>
<div class="_blankDiv"></div>
<div>
<table>
<tr>
<td width="30%">
<button type="submit" value="Submit" class="button" id="btnSubmit">Submit</button>
</td>
<td width="30">
<button type="reset" value="Reset" class="button">Reset</button>
</td>
</tr>
</table>
</div>
</form:form>
</body>
</html>

Tuesday, 21 April 2015

Loop Optimization in java

Loop Optimization I found it very interesting thing that will increase the java looping performance
===============================================================
public loopA()
 {
     String str = “abcdefghijklmnopqurstuvwxyz”; 
    
       for (int j = 0; j < str.length(); j++) {
       }
  }
====================================================
public loopB()
 {
  String str = “abcdefghijklmnopqurstuvwxyz”;
  int len = str.length();
  for (int j = 0; j < len; j++)
   {
//This is because the length of the string is not calculated for each iteration
//through the loop. 
  }
}
====================================================
LooB is 200% faster than loopA.


This is because the length of the string is not calculated for each iteration
through the loop. The method call to str.length() is avoided by setting the results to an integer prior to entering the loop.

Thursday, 26 March 2015

How hash map works if it has same key of strings

it was great discussion with my friend over working of hash-map with the same key.

The question was.
Does hash map store the same key? if yes then

What happens when a duplicate key is put into a HashMap?

Here is example of store ing duplicate key guess the output?

import java.util.*;
public class MyHashMap {
 public static void main(String args[]){
 
  HashMap<String,String> hm=new HashMap<String,String>();

  hm.put("Vipul","1000");
  hm.put("Vipul","2000");
  hm.put("Vipul","3000");

 
  System.out.println(hm.get("Vipul"));
  for(Map.Entry m:hm.entrySet()){
   System.out.println(m.getKey()+" "+m.getValue());
  }
 }
}

ANS Is

Vipul 3000

--------------------------------------------------------------------------------------------
now it is getting more complex....?

What will be size of hash-map in this case?
Ans: ONE
--------------------------------------------------------------------------------------------
import java.util.*;
public class MyTestHashMap {
 public static void main(String args[]){
 
  HashMap<String,String> hm=new HashMap<String,String>();

  hm.put("Vipul","1000");
  hm.put("Vipul","2000");
  hm.put("Vipul","3000");

 
  System.out.println(hm.get("Vipul"));
  for(Map.Entry m:hm.entrySet()){
   System.out.println(hm.size+" "+m.getKey()+" "+m.getValue());
  }
 }
}

There are some more code as well I will add soon
In case your finding is different please comment.


Friday, 30 January 2015

Onclick get image tag value in html

<html>
<head>
<title>img</title>
 <script>
 function myFunction() {
     var catImage = document.getElementById("catImage"),
    catImageValue = document.getElementById("catImageValue");
//alert("I am an catImageValue box!"+ catImageValue);

catImageValue.innerHTML = "Value = " + catImage.getAttribute("value");
   
}

 </script>
 </head>
  Click on this
 <img id="catImage" src="http://i.imgur.com/Mmfl8.png" width="100px" value="1" />
<div id="catImageValue"></div>
<button onclick="myFunction()">Try it</button>
 </body>
</html>

VIEW DEMO HERE MY Fiddle

http://jsfiddle.net/vipulg/povnd0t2/
DEMO