Monday, 30 November 2015

java junit4

@Ignore("ignore this test")
@AfterClass
@BeforeClass
@After
@Before
@Test (expected =ArithmeticException.class)
@Test

Sunday, 29 November 2015

How get BigdecimalEnum value in java

package com.org.vipul;

import java.math.BigDecimal;

public class BigdecimalEnum {

public static void main(String[] args) {
System.out.println(Vat.FIVE.getValue());

}

public enum Vat {
ONE(new BigDecimal("1")), TWO(new BigDecimal("2")), THREE(
new BigDecimal("3")), FIVE(new BigDecimal("5"));

private final BigDecimal value;

Vat(BigDecimal val) {
value = val;
}

public BigDecimal getValue() {
return value;
}
}
}

Sunday, 16 August 2015

java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

To fix this use this jar

http://commons.apache.org/logging/download_logging.cgi

Add to class path

Wednesday, 8 July 2015

Spring REST xml responce


Spring rest json responce

1) Create bean of JSON view resolver

<bean name="jsonTemplate" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>

2) Return this Json view from modelAndView controller

@RequestMapping(value = "/clients")
public String getAllClientsJSON(Model model) {

model.addAttribute("clients", getClientsCollection());
 return "jsonTemplate";

 }

//getClientsCollection() this meothod will have list of clients

Tuesday, 30 June 2015

how to call a constructor from another constructor in java

how to call a constructor from another constructor in java
Use this keyword to achieve this

public class FooConstructor
{
    private int x;

    public FooConstructor ()
    {
        this(1);
    }

    public FooConstructor (int x)
    {
        this.x = x;
    }
}

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

sybase add column

Begin

ALTER TABLE Order_def ADD shared char(3) DEFAULT 'N' NOT NULL CONSTRAINT CHK_shared CHECK (shared IN ("Yes","No","-") )
End
GO


Wednesday, 28 January 2015

How do I remove objects from an array in Java

How do I remove objects from an array in Java


I have array of object type how to remove the object from it

i have class StockExchange 
     and i have array of the same class

  StockExchange[] t= new StockExchange[]{TSE,HKSE,NYSE};

now i want to remove the element from this array 

Here is full example how i removed.
-----------------------------------------------------------------------------
class StockExchange{
    public boolean isClosed() {
return false;
}
--------------------------------------------------------------------------------
public class ObjectRemovalTest {
  
    public static void main(String args[])
    {
    StockExchange TSE = new StockExchange(){
            
            @Override
            public boolean isClosed() {
                return true;
            }         
       };
     
       StockExchange HKSE = new StockExchange(){

            @Override
            public boolean isClosed() {
                return true;
            }         
       };
      
       StockExchange NYSE = new StockExchange(){

            @Override
            public boolean isClosed() {
                return false;
            }         
       };
      

       
    StockExchange[] t= new StockExchange[]{TSE,HKSE,NYSE};
        System.out.println("T"+Arrays.toString(t));
        Set<StockExchange> asSet = new HashSet<StockExchange>(Arrays.asList(t));                   asSet.remove(TSE);
        t = asSet.toArray(new StockExchange[] {});
        System.out.println(Arrays.toString(t));
   
    }

Wednesday, 21 January 2015

convert int to string in java

convert int to string in java

Use String.valueOf(id);

int id =2;

String name = String.valueOf(id);

Monday, 19 January 2015

field xxxxx doesn have a default value

field xxxxxx doesn have a default value

drop the table schema or update the schema using hibernate of jpa option

<property name="hibernate.hbm2ddl.auto" value="update" />



spring jpa auto create- update table mysql

spring jpa auto create- update table mysql

add this in persistence.xml

<property name="hibernate.hbm2ddl.auto">create</property>
OR
<property name="hibernate.hbm2ddl.auto">Update</property>