Wednesday 24 September 2014

In crystal report How to avoid or disable login prompt popup in java

Avoid or disable  CrystalReport login prompt popup in java

use belew code in viewer file:-


CrystalReportViewer crystalReportPageViewer = new CrystalReportViewer();
    
ConnectionInfos connInfos = new ConnectionInfos();
IConnectionInfo connInfo1 = new ConnectionInfo();
    
 connInfo1.setUserName("YourUserName");
        connInfo1.setPassword("Yourpassword");
        connInfos.add(connInfo1);

    crystalReportPageViewer.setEnableParameterPrompt(false);
    crystalReportPageViewer.setDatabaseLogonInfos(connInfos);








Cystal Report new line with java .

By using Can Grow option in conditional formulas, we can achieve the new line in crystal 
report 

if it returns true, can Grow option will enabled for the required field.

Sunday 17 August 2014

Spring Exception

org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:491) 


The above exception relates the command object
It will occur following scenario.
 1.when  command  object to view page not properly set into the page.
2.command object name misspelled 
 
 

Saturday 16 August 2014

Spring Login Example.

Spring Login with username and password.

Following example demonstrate the simple login in web page.

I have used annotation for the controller

user name:  bala
password : bala123
spring Login Example war

Page 1  Login page:











Page 2 : Success Page:



Page 3 Failure Page
When user enter Incorrect  Username or password.


Following link contains the war file to execute the login spring application

spring Login Example war

Wednesday 11 June 2014

Create Jar File in windows

Create Jar File in windows:

set class path for java
set path = C:\Program Files\Java\jdk1.6.0\bin

jar file creation command for all class files in current and sub directory

commad  :- jar cvf jarFileName directory

examnple: jar cvf "myjar1.jar" .\in

jar file creation command for particular files

commad  :- jar cvf jarFileName  "fileName 1,fileName 2,fileName 3"

examnple: jar cvf "myjar1.jar" "sample.class,example.class"

To cheack jar file:

E:\NewFolder\jboss-4.0.3\server\default\deploy\timesheet.war\WEB-INF\classes>jar  tvf myjar1.jar

Tuesday 15 April 2014

My Exceptions

org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:435).
java.lang.IllegalStateException

At point of nothing to response to client (browser)

Following is sample example
if(a.equals("7")){
  RequestDispatcher dispatcher= getServletContext().getRequestDispatcher("/login.jsp");
   dispatcher.forward(request,response);

}

if(b.equals("6")){
  RequestDispatcher dispatcher= getServletContext().getRequestDispatcher("/login.jsp");
    dispatcher.forward(request,response);

}

In first  block itself it respond to browser . In step 2 nothing to response
so this exception will occur

To Avoid Exception java.lang.IllegalStateException.
Add return statement .
if(a.equals("7")){
      RequestDispatcher dispatcher= getServletContext().getRequestDispatcher("/login.jsp");
    dispatcher.forward(request,response);
      return;
}

Javascript Useful Code

 Dynamic Regex :-
Try the following code when systen test is not function in  javascript. while regex  validation.
or
Dynamic create the Regex that is stored in another variable and compare
check In if condition you have place the regex pattern and email  in correct location as follow
if(pattern.test(emailid)
 
var emailid='balamurugan2b@gmail.com';
var regexpattern='^([\w-]+(?:\.[\w-]+)*)@(gmail.com)$';
var pattern = new RegExp(regexpattern);

if(pattern.test(emailid)){
true;
}else{
false;
}


add more rows and delete row

Click Here


jquery drag and drop file upload

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<style>
#dragandrophandler
{
border:2px dotted #0B85A1;
width:400px;
color:#92AAB0;
text-align:left;vertical-align:middle;
padding:10px 10px 10 10px;
margin-bottom:10px;
font-size:200%;
}
.progressBar {
    width: 200px;
    height: 22px;
    border: 1px solid #ddd;
    border-radius: 5px; 
    overflow: hidden;
    display:inline-block;
    margin:0px 10px 5px 5px;
    vertical-align:top;
}
 
.progressBar div {
    height: 100%;
    color: #fff;
    text-align: right;
    line-height: 22px; /* same as #progressBar height if we want text middle aligned */
    width: 0;
    background-color: #0ba1b5; border-radius: 3px; 
}
.statusbar
{
    border-top:1px solid #A9CCD1;
    min-height:25px;
    width:700px;
    padding:10px 10px 0px 10px;
    vertical-align:top;
}
.statusbar:nth-child(odd){
    background:#EBEFF0;
}
.filename
{
display:inline-block;
vertical-align:top;
width:250px;
}
.filesize
{
display:inline-block;
vertical-align:top;
color:#30693D;
width:100px;
margin-left:10px;
margin-right:5px;
}
.abort{
    background-color:#A8352F;
    -moz-border-radius:4px;
    -webkit-border-radius:4px;
    border-radius:4px;display:inline-block;
    color:#fff;
    font-family:arial;font-size:13px;font-weight:normal;
    padding:4px 15px;
    cursor:pointer;
    vertical-align:top
    }
</style>
</head>
 
<body>
<div id="dragandrophandler">Drag & Drop Files Here</div>
<br><br>
<div id="status1"></div>
<script>
function sendFileToServer(formData,status)
{
    var uploadURL ="fileUpload.jsp"; //Upload URL
    var extraData ={}; //Extra Data.
    var jqXHR=$.ajax({
            xhr: function() {
            var xhrobj = $.ajaxSettings.xhr();
            if (xhrobj.upload) {
                    xhrobj.upload.addEventListener('progress', function(event) {
                        var percent = 0;
                        var position = event.loaded || event.position;
                        var total = event.total;
                        if (event.lengthComputable) {
                            percent = Math.ceil(position / total * 100);
                        }
                        //Set progress
                        status.setProgress(percent);
                    }, false);
                }
            return xhrobj;
        },
    url: uploadURL,
    type: "POST",
    contentType:false,
    processData: false,
        cache: false,
        data: formData,
        success: function(data){
            status.setProgress(100);
 
            $("#status1").append("File upload Done<br>");         
        }
    }); 
 
    status.setAbort(jqXHR);
}
 
var rowCount=0;
function createStatusbar(obj)
{
     rowCount++;
     var row="odd";
     if(rowCount %2 ==0) row ="even";
     this.statusbar = $("<div class='statusbar "+row+"'></div>");
     this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
     this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
     this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
     this.abort = $("<div class='abort'>Abort</div>").appendTo(this.statusbar);
     obj.after(this.statusbar);
 
    this.setFileNameSize = function(name,size)
    {
        var sizeStr="";
        var sizeKB = size/1024;
        if(parseInt(sizeKB) > 1024)
        {
            var sizeMB = sizeKB/1024;
            sizeStr = sizeMB.toFixed(2)+" MB";
        }
        else
        {
            sizeStr = sizeKB.toFixed(2)+" KB";
        }
 
        this.filename.html(name);
        this.size.html(sizeStr);
    }
    this.setProgress = function(progress)
    {       
        var progressBarWidth =progress*this.progressBar.width()/ 100;  
        this.progressBar.find('div').animate({ width: progressBarWidth }, 10).html(progress + "% ");
        if(parseInt(progress) >= 100)
        {
            this.abort.hide();
        }
    }
    this.setAbort = function(jqxhr)
    {
        var sb = this.statusbar;
        this.abort.click(function()
        {
            jqxhr.abort();
            sb.hide();
        });
    }
}
function handleFileUpload(files,obj)
{
   for (var i = 0; i < files.length; i++) 
   {
        var fd = new FormData();
        fd.append('file', files[i]);
 
        var status = new createStatusbar(obj); //Using this we can set progress.
        status.setFileNameSize(files[i].name,files[i].size);
        sendFileToServer(fd,status);
 
   }
}
$(document).ready(function()
{
var obj = $("#dragandrophandler");
obj.on('dragenter', function (e) 
{
    e.stopPropagation();
    e.preventDefault();
    $(this).css('border', '2px solid #0B85A1');
});
obj.on('dragover', function (e) 
{ 
     
     e.stopPropagation();
     e.preventDefault();
});
obj.on('drop', function (e) 
{
 
     $(this).css('border', '2px dotted #0B85A1');
     e.preventDefault();
     var files = e.originalEvent.dataTransfer.files;
 
     //We need to send dropped files to Server
     handleFileUpload(files,obj);
});
$(document).on('dragenter', function (e) 
{
  
    e.stopPropagation();
    e.preventDefault();
});
$(document).on('dragover', function (e) 
{

  e.stopPropagation();
  e.preventDefault();
  obj.css('border', '2px dotted #0B85A1');
});
$(document).on('drop', function (e) 
{
    e.stopPropagation();
    e.preventDefault();
});
 
});
</script>
</body>
</html>


fileUpload.jsp

<!--
File Name :-fileUpload.jsp
Created By:-B.Balamurugab
Created on:-May 14,2014.
Description:- This file is used for upload
    droped file 
Edited By 
-->


<%@ page language="java" import="java.io.*,java.util.*" %>
<%@ page import="java.sql.*,in.textech.library.DatabaseLibrary,in.textech.common.ConstantValues" %>
<%@page import="in.textech.library.DatabaseLibrary"%>
<%@ page import="in.textech.library.LocaleDateTime" %>
<%@page import="in.textech.common.ConstantValues"%>

<%@page import="java.sql.Connection"%>
<%@page import="com.mysql.jdbc.Driver"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.io.File"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.PrintWriter"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>

<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%

response.setContentType("text/html");
response.setHeader("Cache-control","no-cache");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
try{
if(!ServletFileUpload.isMultipartContent(request)) {
  out.println("Request does not contain upload data");
  return;
 }

 // configures upload settings
 DiskFileItemFactory factory = new DiskFileItemFactory();

 factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    String UPLOAD_DIRECTORY = "PO";

 // constructs the directory path to store upload file
 String uploadPath = System.getProperty("java.io.tmpdir")+ UPLOAD_DIRECTORY;
 // creates the directory if it does not exist
 File uploadDir = new File(uploadPath);
 if (!uploadDir.exists()) {
  uploadDir.mkdir();
 }
 String filePath = "";

 // parses the request's content to extract file data
 List formItems = upload.parseRequest(request);
 Iterator iter = formItems.iterator();

 // iterates over form's fields
 while (iter.hasNext()) {
  FileItem item = (FileItem) iter.next();
  // processes only fields that are not form fields
  if (!item.isFormField()) {
   String fileName = new File(item.getName()).getName();
   if(fileName!=null && !"".equals(fileName)){
    filePath = uploadPath + File.separator + fileName;
    File storeFile = new File(filePath);
    // saves the file on disk
    item.write(storeFile);
    
    
         }
  }
 }
}catch(Exception e){
 e.printStackTrace();
 
}

response.getWriter().write("y");

%>
drag and drop file upload pure java script .


                window.onload = function() {
                var dropbox = document.getElementById("dropbox");
                dropbox.addEventListener("dragenter", noop, false);
                dropbox.addEventListener("dragexit", noop, false);
                dropbox.addEventListener("dragover", noop, false);
                dropbox.addEventListener("drop", dropUpload, false);
            }

            function noop(event) {
                event.stopPropagation();
                event.preventDefault();
            }

            function dropUpload(event) {
                noop(event);
                var files = event.dataTransfer.files;
               for (var i = 0; i < files.length; i++) {
    var xhr = new XMLHttpRequest();
                               xhr.open("POST", fileUpload.jsp, false); 
                                    xhr.send(formData)
} } function upload(file,poID) { } function uploadProgress(event) { // Note: doesn't work with async=false. var progress = Math.round(event.loaded / event.total * 100); document.getElementById("status").innerHTML = "Progress " + progress + "%"; } function uploadComplete(event) { alert("Complete Request"); }

Show only month and year 

Call  setYearToDropDown() in onload of page

Html Code

<html>
<body onload="setYearToDropDown()">

<table>
<tr><td><td>Month</td><td>
<select name="year" id="year" style="width:155px" size="1" onchange="display_month()" >
</td>
</tr>
<tr><td><td>Year</td><td>

<select name="month" id="month"  style="width:155px"   size="1"  >
</td>
</tr>
</body>

<script>

function setYearToDropDown(){
   var currentDate = new Date();
         var currentYear = currentDate.getFullYear(); 
   var nextYear = currentYear +1; 
   var nextNextYear = nextYear+1;
   
     document.getElementById("year").options.length = 0;
  document.getElementById("year").options[0] = new Option('Select','');
  document.getElementById("year").options[1] = new Option(currentYear,currentYear);
  document.getElementById("year").options[2] = new Option(nextYear,nextYear);
  document.getElementById("year").options[3] = new Option(nextNextYear,nextNextYear);

   
 }

 function display_month() {

 var year = document.getElementById("year").value;
 var k=1;
 var d = new Date();
 var n = d.getMonth(); 
 var Currentyear = d.getFullYear()
 var month=new Array();
  month[0]="January";
  month[1]="February";
  month[2]="March";
  month[3]="April";
  month[4]="May";
  month[5]="June";
  month[6]="July";
  month[7]="August";
  month[8]="September";
  month[9]="October";
  month[10]="November";
  month[11]="December";
  
 if(document.getElementById("year").value !="") {      
  document.getElementById("month").options.length = 0;
  document.getElementById("month").options[0] = new Option('Select','');
  
  if(Currentyear==year) {
  
   for(var i=n;i<month.length;i++) {
    document.getElementById("month").options[k] = new Option(month[i],i+1);
   k++;
   }
  }
  else {
   
   for(var i=1;i<=month.length;i++) {
    document.getElementById("month").options[i] = new Option(month[i-1],i);
   }
  }
 }
 else {
  document.getElementById("month").options.length = 0;
  document.getElementById("month").options[0] = new Option('Select','');
 
 }
 
}
</script>
</html>

jQuery get radio buttom value

<td> <input type="radio" name="sendMail"  id="sendMailYes" value="yes" >Yes<br>
       <input type="radio" name="sendMail" id="sendMailNo" value="no" >No</td>

var issendMail =  $('input[name=sendMail]:checked').val(); 



To Select Multi select dropdwon

function selectTeamSubgroup(){
  $("#selectedVendor").each(function(){
            $("#selectedVendor option").attr("selected","selected"); });
  
 }
 

File Upload to Server  on change of input Box
window.addEventListener('load',function(){ var emailAttachment = document.getElementById("files"); emailAttachment.addEventListener("change", handleFileSelect, false); }); function handleFileSelect(e) { var storedFiles = []; var valuesCount; var requestAttachment; var files = e.target.files; var filesArr = Array.prototype.slice.call(files); filesArr.forEach(function(f) { storedFiles.push(f); var reader = new FileReader(); reader.onload = function (e) { } reader.readAsDataURL(f); }); var data = new FormData(); valuesCount =storedFiles.length; for(var i=0, len=storedFiles.length; i<len; i++) { data.append('files', storedFiles[i]); } if (window.XMLHttpRequest) { requestAttachment = new XMLHttpRequest(); } else if (window.ActiveXObject) { requestAttachment = new ActiveXObject("Microsoft.XMLHTTP"); } var url = "conversionEmailAttachment.jsp"; requestAttachment.open("POST", url, true); requestAttachment.onreadystatechange =callbackUpload(requestAttachment,mainUpload); requestAttachment.send(data); } function callbackUpload(requestAttachment,responseXmlHandler){ return function(){ if(requestAttachment.readyState == 4) { if(requestAttachment.status == 200){ var height = 600; document.getElementById("selDiv").innerHTML=""; var jsonObj = JSON.parse(requestAttachment.responseText); for (var key in jsonObj) { if (jsonObj.hasOwnProperty(key)) { var fileName1 = jsonObj[key]; var html = "<div>" + fileName1.split("\\").pop() + " <img src=\"images/icon/attachmentDel.png\" onClick='deleteMe("+JSON.stringify(key)+");'/></div>"; document.getElementById("selDiv").innerHTML+= html; height +=30; } } document.getElementById("email_send").style.height = height+"px"; } else{ alert("Http error :"+requestAttachment.status); } } } } function mainUpload(main) { } function deleteMe(fileID){ var url = "deleteEmailAttachment.jsp?fileID="+fileID; var request; try{ if (window.XMLHttpRequest){ request = new XMLHttpRequest(); } else if (window.ActiveXObject) { request = new ActiveXObject("Microsoft.XMLHTTP"); } request.open("GET", url, true); request.onreadystatechange = callbackDelete(request,mainDelete); request.send(null); } catch(e){ alert(e); } } function callbackDelete(request,responseXmlHandler1){ return function(){ if(request.readyState == 4) { if(request.status == 200){ var jsonObj = JSON.parse(request.responseText); document.getElementById("selDiv").innerHTML=""; for (var key in jsonObj) { if (jsonObj.hasOwnProperty(key)) { var fileName1 = jsonObj[key]; var html = "<div>" + fileName1.split("\\").pop() + " <img src=\"images/icon/attachmentDel.png\" onClick='deleteMe("+JSON.stringify(key)+");'/></div>"; document.getElementById("selDiv").innerHTML+= html; } } } else{ alert("Http error :"+requestAttachment.status); } } } } function mainDelete(main) { }

------------------------------------------------------------------------------

Disable dates in jquery Calender 


var x="Threshold Reached";

    <% 

    CustomThreshold threshold = new CustomThreshold();
    String[] disabledDays= threshold.dateFoundCheck(employee_id);
    //String[] params = request.getParameterValues("someField");  
 
 int disableDaysLength=disabledDays.length;
    
    
    for (int i=0;i<disabledDays.length;i++) {
out.println("unavailableDates["+i+"]='"+disabledDays[i]+"';");
}
%> function unavailable(date) {
        ymd = date.getFullYear() + "-" + ("0"+(date.getMonth()+1)).slice(-2) + "-" + ("0"+date.getDate()).slice(-2);
        day = new Date(ymd).getDay();
        if ($.inArray(ymd, unavailableDates) < 0 ) {
            return [true, "enabled", ""];
        } else {
            return [false,"disabled",x];
        }
    }

/* create datepicker */
jQuery(document).ready(function() {
  jQuery('#startdate').datepicker({
 
    minDate: new Date(2010, 0, 1),
    maxDate: '+1Y',
 //minDate: 0,
    dateFormat: 'dd-mm-yy',
    constrainInput: true,
    showOn: "button",
    buttonImage: "../images/cal1.gif",
    buttonImageOnly: true,
   beforeShowDay:unavailable
  });
});
jQuery(document).ready(function() {
  jQuery('#enddate').datepicker({
 
    minDate: new Date(2012, 0, 1),
    maxDate: '+1Y',
 
    dateFormat: 'dd-mm-yy',
    constrainInput: true,
    showOn: "button",
    buttonImage: "../images/cal1.gif",
    buttonImageOnly: true,
   beforeShowDay:unavailable
  });
});
 




Monday 17 March 2014

bulid xml like as normal folder . war

Following build.xml is used to create the war file like normal folder


<!-- Build file for epubtoword -->

<project name="epubtoword" default="build" basedir=".">

  <!-- ============= -->
  <!-- === CLEAN === -->
  <!-- ============= -->
  <target name="clean"  description="removes all generated files">
    <delete dir="build" />
  </target>
  
  <!-- =============== -->
  <!-- === INIT === -->
  <!-- =============== -->
  <target name="init">
 <property name="dirs.base" value="${basedir}"/>
 <property name="src" value="${dirs.base}/src"/>
 <property environment="env"/> 
 <property name="jboss.home" value="${env.JBOSS_HOME}"/>
 <property name="warDir" value="${jboss.home}/server/default/deploy/epubtoword.war"/>
 
 <!-- Create Web-inf and classes directories -->
 <mkdir dir="${warDir}/WEB-INF"/>
 <mkdir dir="${warDir}/WEB-INF/classes"/>
 <mkdir dir="${warDir}/WEB-INF/lib"/>
 <mkdir dir="${warDir}/src"/>
 <mkdir dir="${warDir}/css" />
 <mkdir dir="${warDir}/images"/>
 <mkdir dir="${warDir}/js"/>
 <mkdir dir="${warDir}/fonts"/>
</target>

  <!-- ================= -->
  <!-- === CLASSPATH === -->
  <!-- ================= -->
  <path id="classpath">
    <fileset dir="WebContent/WEB-INF/lib" includes="**/*.jar" />
  </path>
  
  <!-- =============== -->
  <!-- === COMPILE === -->
  <!-- =============== -->
  <target name="compile" depends="init">
   <echo message="start compiling" />
 <javac srcdir="${src}" destdir="${warDir}/WEB-INF/classes" debug="true" includes="**/*.java">
 <classpath refid="classpath" />
 </javac>
  </target>
  <!-- =============== -->
  <!-- === BUILD ===== -->
  <!-- =============== -->
  <target name="build" depends="init,compile">
    <echo message="start building:" />
    <copy todir="${warDir}/src">
     <fileset dir="src/" includes="**/*.java"/>
    </copy>
    <copy todir="${warDir}/">
     <fileset dir="${dirs.base}/" includes="*.jsp"/>
    </copy>
    <copy todir="${warDir}/">
     <fileset dir="${dirs.base}/" includes="*.html"/>
    </copy>
    <copy todir="${warDir}/">
     <fileset dir="${dirs.base}/" includes="*.htm"/>
    </copy>    
    <copy todir="${warDir}/">
     <fileset dir="${dirs.base}/" includes="**/*.properties"/>
    </copy>
    <copy todir="${warDir}/WEB-INF">
     <fileset dir="${dirs.base}/" includes="web.xml"/>
    </copy>
    
    <copy todir="${warDir}/WEB-INF/lib">
     <fileset dir="${dirs.base}/WEB-INF/lib" includes="*.jar" />
    </copy>
    <copy todir="${warDir}/images">
     <fileset dir="${dirs.base}/images" includes="*.*"/>
    </copy>
    
    <copy todir="${warDir}/js">
     <fileset dir="${dirs.base}/js" includes="*.js"/>
    </copy>
  <copy todir="${warDir}/css">
     <fileset dir="${dirs.base}/css" includes="*.css"/>
    </copy>
 
 <copy todir="${warDir}/fonts">
     <fileset dir="${dirs.base}/fonts" includes="*.*"/>
    </copy>
 
  </target>
  </project>

bulid.xml Creation

build xml creation  from eclipse  project  as war file


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="deploy" name="epubtoword">
 <property name="warfile" value="epubtowordx" />
 <target name="unpack">
  <unwar src="${warfile}.war" dest="${warfile}" />
 </target>
 <property name="debuglevel" value="source,lines,vars" />
 <property name="target" value="1.5" />
 <property name="source" value="1.5" />
 <path id="Web App Libraries.libraryclasspath">
  <pathelement location="WebContent/WEB-INF/lib/commons-fileupload-1.2.1.jar" />
  <pathelement location="WebContent/WEB-INF/lib/commons-fileupload-1.2.2.jar" />
  <pathelement location="WebContent/WEB-INF/lib/commons-io-2.3.jar" />
  <pathelement location="WebContent/WEB-INF/lib/commons-logging-1.1.1.jar" />
  <pathelement location="WebContent/WEB-INF/lib/javax.servlet-3.0.jar" />
  <pathelement location="WebContent/WEB-INF/lib/javax.servlet.jar" />
  <pathelement location="WebContent/WEB-INF/lib/mail.jar" />
  <pathelement location="WebContent/WEB-INF/lib/mysql-connector-java-3.1.10-bin.jar" />
  <pathelement location="WebContent/WEB-INF/lib/org.apache.commons.io.jar" />
  <pathelement location="WebContent/WEB-INF/lib/quartz-1.5.2.jar" />
  <pathelement location="WebContent/WEB-INF/lib/urlrewritefilter-4.0.3.jar" />
  <pathelement location="WebContent/WEB-INF/lib/xercesImpl-2.6.2-jaxb-1.0.6.jar" />
 </path>
 <path id="EAR Libraries.libraryclasspath" />
 <path id="epubtoword.classpath">
  <pathelement location="build/classes" />
  <path refid="Web App Libraries.libraryclasspath" />
  <path refid="EAR Libraries.libraryclasspath" />
 </path>
 <target name="init">
  <mkdir dir="build/classes" />
  <copy includeemptydirs="false" todir="build/classes">
   <fileset dir="src">
    <exclude name="**/*.launch" />
    <exclude name="**/*.java" />
   </fileset>
  </copy>
 </target>
 <target name="clean">
  <delete dir="build/classes" />
 </target>
 <target name="build">
  <javac debug="true" debuglevel="${debuglevel}" destdir="build/classes" source="${source}" target="${target}">
   <src path="src" />
   <classpath refid="epubtoword.classpath" />
  </javac>
 </target>

 <target name="create">
  <war destfile="/usr/jboss-4.2.3.GA/server/default/deploy/${warfile}.war" webxml="WebContent/WEB-INF/web.xml" update="true">
   <classes dir="build/classes" />
   <fileset dir="WebContent">
    <exclude name="WEB-INF/web.xml" />
   </fileset>
  </war>
 </target>
 

 <target name="deploy">
  <antcall target="clean" />
  <antcall target="init" />
  <antcall target="build" />
  <antcall target="create" />

 </target>
</project>






Monday 24 February 2014

Java String Objects and object creation JVM

Java Object toString()  method:

This method is used to view the text format of object created in heap;

class ToStringTest{
  public static void main(String[] ags){   
    ToStringTest tst = new ToStringTest();
     System.out.println("Object value"+tst);
     System.out.println("Hash Code"+tst.hashCode());

  
  }
}
 
When JVM executing  this line (ToStringTest tst = new ToStringTest())
1)The tst reference variable created in the stack ,
 
2)By new operator object creation in heap.(memory space allocating for the object)
 
3)Assignment operator =  is used for the assign the created object to reference variable 
 
 
 
output is Object value  ToStringTest@35c41b
                                     Hash Code   32429958
32429958 is interger value for object creatd location heap


after the @ symbol. hex decimal value of object .that created in heap


Tuesday 18 February 2014

Java Loosely and tightly coupled code or Spring Dependency Injection

Following post will explain the java tightly and loosely coupled code.And  How to avoid the tightly coupled code By using Spring Dependency Injection 

Following link have war file example. play it

Download Dependence Injection Example (War)

This is a web project war import this war to your eclipse and  right click on Employee class run the java
To view change the id ref to oracle to view change

Tightly Coupled Code:

If the one java class  completely  using the other java class's logic   means collaboration.

Example:

class SunMicrosystems {
 public void showCompanyName() {
  System.out.println("SunMicrosystems");

 }
}


/**
Employee  calls the  SunMicrosystems's   logic . If we  change the logic.we must change the java file also.
Employee class always depends the SunMicrosystems is called tightly coupled
*/


class Employee {
 SunMicrosystems sun = new SunMicrosystems();

 public void workCompany() {
  sun.showCompanyName();
 }

 public static void main(String[] arg) {
  Employee emp = new Employee();
  emp.workCompany();

 }

}

Let We See How to avoid tightly coupled code by Spring Dependency Injection.

By Introduce the Interface  we can avoid the tightly coupled code

Loosely Coupled Code: 

package com;

interface Company {
 public void showCompanyName();

}



package com;

class Oracle implements Company {
 public void showCompanyName() {
  System.out.println("Oracle");

 }
}


package com;

class SunMicrosystems implements Company {
 public void showCompanyName() {
  System.out.println("SunMicrosystems");

 }
}


package com;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

class Employee {

 private Company c;

 public void setC(Company c) {
  this.c = c;
 }

 public void showCompany() {
  c.showCompanyName();
 }

 public static void main(String[] arg) {
  Resource r = new ClassPathResource("applicationContext.xml");
  BeanFactory factory = new XmlBeanFactory(r);

  Employee emp = (Employee) factory.getBean("emp");
  emp.showCompany();
 }

}

/**
In the employee class class the method showCompany(), It in company  Interface , Following xml file we can change the ref attribute itself can desired ,the method call from which  class
*/


<?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="sun" class="com.SunMicrosystems" />
<bean id="oracle" class="com.Oracle" />
  <bean id="emp" class="com.Employee">
    <property name="c" ref="sun" />
  </bean>

</beans>