Wednesday, November 30, 2011

Remove table using index number in jquery

Suppose you are sure that u need to remove 2nd table of the page,you can do this by using index
index starts with 0

$('table:eq(1)').remove();

The same concept can be applied for any elements

Saturday, November 26, 2011

FileUpload Application in Servlet

This is not the only way,But its one of the way to create an application using which you can upload your file into Server.
The idea is very simple,we will create 2 folders in the server "temp1","temp2".
"temp1" will act as a buffer where the files will be stored temporarily,Once its uploaded successfully,The file will then be store on "temp2" permanently.

Steps
*****
1.create following 2 folder in ur c:
     c:\temp1
     c:\temp2
2.Prepare the directory structure
welcome.html
***********
<center><h1><br><p>Upload Your File</P></h1><hr>

<form action="mypattern" enctype="multipart/form-data" method="post">
<input type="file"name="file1"><br>
<input type="submit" value="upload file"><br>
</form>

web.xml
*******
<web-app>
    <servlet>
        <servlet-name>abc</servlet-name>
        <servlet-class>FileUploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>abc</servlet-name>
        <url-pattern>/mypattern</url-pattern>
    </servlet-mapping>
</web-app>


FileUploadServlet.java
********************************************************************************
import java.io.*;//File,PrintWriter,IOEXception
import java.util.*;  //Iterator,List
import javax.servlet.*;//ServletConfig,ServletException
import javax.servlet.http.*;//HttpServlet.HttpServletRequest,HttpServletResponse

import org.apache.commons.fileupload.*; //FileItem,FileUploadException
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class FileUploadServlet extends HttpServlet
{
    private static final String TMP_DIR_PATH="c:\\temp1";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH="c:\\temp2";
    private File destinationDir;

    public void init(ServletConfig config)throws ServletException
    {

        super.init(config);
        tmpDir=new File(TMP_DIR_PATH);
        if(!tmpDir.isDirectory())
        {
            System.out.println("A");
            throw new ServletException(TMP_DIR_PATH+"is not a directory");

        }
        System.out.println("Source Directory..."+TMP_DIR_PATH);


        destinationDir=new File(DESTINATION_DIR_PATH);

        if(!destinationDir.isDirectory())
        {

            throw new ServletException(DESTINATION_DIR_PATH+"is not a directory");
        }
        System.out.println("Destination directory..."+DESTINATION_DIR_PATH);

    }//INIT()

protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{

    PrintWriter out=response.getWriter();
    response.setContentType("text/plain");
    out.println("****File UPload status**");
    out.println();
    DiskFileItemFactory fileItemFactory=new DiskFileItemFactory();

    //set the size theshold ,aboutwhich content will be stored on disk

    fileItemFactory.setSizeThreshold(1*1024*1024);

    //set the temporary directory to store the uplaoded files of sze abouve threshold
    fileItemFactory.setRepository(tmpDir);
    File file=null;
    ServletFileUpload uploadHandler=new ServletFileUpload(fileItemFactory);

    try
    {
        System.out.println("A");
        //parse the request
        List items=uploadHandler.parseRequest(request); //throws some exception
        System.out.println("B");
        System.out.println("request items");
        System.out.println(items);

        Iterator itr=items.iterator();
        while(itr.hasNext())
        {
            FileItem item=(FileItem)itr.next();
            if(item.isFormField())
            {
                out.println("FileName=" +item.getFieldName()+ ",value="+item.getString());
            }
            else
            {
                /*    String fileName=null;
                String s1=item.getName();
                int index=s1.lastIndexOf("\\") +1;
                String s2=s1.substring(index);
                if(s1!=null)fileName=s2;
                else fileName="";"*/
                System.out.println("0");
                String fileName= (item.getName()!=null)? item.getName().substring(item.getName().lastIndexOf("\\")+1):"";
                out.println("FileName="+fileName+"\n Content type="+item.getContentType()+"\n FileSeze="+item.getSize());
                System.out.println("1");
                //write file into ultimate location

                if(fileName!=null && fileName.length()>0)
                {
                    file=new File(destinationDir,fileName);
                    item.write(file);
                    out.println("Loaded successfully");
                }
            }
            out.close();
        }
    }//try

    catch(FileUploadException ex)
    {
        ex.printStackTrace();
        out.println("Error encountered while parsing the request");
        log("Error encountered while parsing the request",ex);
    }
    catch(Exception ex)
    {
        System.out.println("3");
        out.println("Error encountered while parsing the request");
        log("Error encountered while uploading file",ex);
    }
}
}
***************************************************************************
Note:Collect those jars from struts software
    


Suns secret WebServer from java6 onwards

Sun Ms has given its own HttpWebServer,using which you can even create a simple webServer like Tomcat.
com.sun.net.httpserver.HttpServer is a class representing WebServer.
You can find this class inside java\jre 1.6.0\lib\rt.jar

Friday, November 25, 2011

Adding Customized Dynamic FormValidation using jquery

DynamicCustomFormValidation.html
******************************

<script type="text/javascript" src="../jquery-1.6.2.js"></script>
<script type="text/javascript" src="../jquery.validate.js"></script>

<script>
$(document).ready(function() {
 $("#form2").submit(function()
  {
      var selError="";
      $("[id^=sport]").each(function()
        {
          //resetting the Color of Both checkbox,when clicked 2nd times onwards
          $(this).css({'background-color':'white'});
                 
             if($(this).val()=="none")
              {   
                 selError+=$(this).attr("id");
                 $(this).css({'background-color':'wheat'});
              }//if
        });//for each
       
      if(selError.length!=0)
      {
        $("#showmsg").html(selError);
        $("#showmsg").css({'background-color':'wheat'});
             
         return false;//stop page from being submitted
      }
         else return true;//submit the page
           
  });//submit()
}); //onready()
   
</script>
<body>
        <form id="form2">
                <select name="sport1" id="sport1">
                    <option value="none">Select a sport</option>
                    <option value="baseball">Baseball</option>
                        <option value="basketball">Basketball</option>
                    <option value="soccer">Soccer</option>
                    <option value="football">Football</option>
                </select> <br>
               
                <select name="sport2" id="sport2">
                    <option value="none">Select a sport</option>
                    <option value="cricket">cricket</option>
                        <option value="badminton">badminton</option>
                    <option value="swimming">swimming</option>
                    <option value="volleyball">VolleyBall</option>
                </select>
                <br>
            <input  type="submit" value="Submit" id="submitBtn">
        </form>
       
        <div id="showmsg" width=200></div>
</body>
*********************************Ends********************************************
















Thursday, November 24, 2011

Add custom validation in JQuery

When the user click on submit button,It has to be validated
****************************** CustomValidation.html*****************


<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript" src="jquery.validate.js"></script>

<script>
  jQuery.validator.addMethod("selectNone",
      function(value, element)
       {
         if (element.value == "none")return false;
         else return true;
       },
             "Please select an option."
      ); //addmethod
     
     
      $(document).ready(function() {
                              $("#form2").validate(
                              {
                                rules:
                                {
                                  sport: {"selectNone": true}
                                }
                              }); //validate
                            }); //function
</script>
<body>
        <form id="form2">
                <select name="sport" id="sport">
                    <option value="none">Select a sport</option>
                    <option value="baseball">Baseball</option>
                        <option value="basketball">Basketball</option>
                    <option value="soccer">Soccer</option>
                    <option value="football">Football</option>
                </select> <br>
            <input class="submit" type="submit" value="Submit"></div>
        </form>
</body>
***********************ProgramEnds********************************************
Collect JavaScript files Separately

Wednesday, November 23, 2011

Converting String into util.Date,and sql.Date

 ********************DateConvert.java******************************

import java.text.ParseException;
import java.text.SimpleDateFormat;
public class DateConvert
{
  public DateConvert() throws ParseException
  {
    String dateString = "2011/10/23";
    //set the format,in which you are going to represent date
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
   
    //parse it and get it in util date format
    java.util.Date utilDate = dateFormat.parse(dateString);

    //converting Util Date into sql Date
    java.sql.Date sqlDate= new java.sql.Date(utilDate.getTime());
   
    System.out.println("Util Date Format: " + utilDate);
    System.out.println("Sql Date Format: " + sqlDate);
   
  }

  public static void main(String[] argv)throws Exception
  {
    new DateConvert();
  }
}
*******************************Prog-Ends**********************************
Note:- make sure to keep MM in uppercase

Tuesday, November 22, 2011

Creating Dynamic Form Using JQuery

The Objective of the Application is to create a dynamic form
  • clicking + button gives u a new row beneath it,
  • each row has unique id for each element
  • New row is generated by cloning the selected component,so all the value present in the previous component
  • Also gets cloned,which we have to remove("ChangeId" button does the same thing).
  • Change ID button assigns unique value to all component as well as removes the cloned data from component
  • "CheckID" button is given to check the id of each row,so that you can know the id was really changed.(Useful if you are not using debugger like firebug)
  • Select All the checkbox which you want to delete,click on delete btn,it will delete the row for you
Steps
****
click on CheckID to know the id of each component
Enter values to any rows components,and click its + symbol
Click "ChangeId" Btn to  change id,and previous cloned value removed
Again click on "CheckMe" to check the new id created for the newly inserted row
Select some checkbox and click on "Delete" to delete the row
 Folder Structure
************





Note:You can take any .jpg file instead of png's,make sure the height and width is appropriate

DynamicForm.html
***************

<html>
<head>
    <title></title>
    <script src="script/jquery-1.4.2.min.js"></script>

    <script type="text/javascript">
    var index=1;
    var flag=5;//because i have only 5 rows initially,so the counter for 6th onwards
    $(document).ready(function()
     {
        index++;
       $("#btnDel").click(function(){
           $('input:checkbox:checked').each(function()
                   {
               var idno=$(this).attr("id").substring(3,4);//get access to current checkbox number
               alert(idno);
               $("#row"+idno).remove();
                   });
            // alert('deleteBtn():called');          
        });
    $("[id^=ref]").click(function()
            {
        //alert("clicked");
        flag++;
            //get the position where you want to insert table
            var pos=$(this).attr('id').substring(3,4);
            $("#row"+pos).clone(false).insertAfter("#row"+pos).attr({id:"row"+flag});
            $("#cbx1 last").attr({id:"cbx7"});
            });
$("#btnChk").click(function(){
     $("input").each(function(){
              alert($(this).attr("id"));
              });
            });
   
    $("#btnChangeId").click(function()
        {
       
        $("#row"+flag+" input:checkbox").attr({id:"cbx"+flag});
        $("#row"+flag+" input:text[id^=text]").attr({id:"text"+flag});
        $("#row"+flag+" input:text[id^=age]").attr({id:"age"+flag});

        //nullify the value
        /**
        $("#row"+flag+" input:checkbox").attr('selected', false);
        $("#row"+flag+" input:text[id^=text]").val("");
        $("#row"+flag+" input:text[id^=age]").val("");
        **/
        //another quickest Approach to nullify
        $("#text"+flag).val("");
        $("#age"+flag).val("");
        $("#cbx"+flag).attr({checked:false});
    });
  });
  
</script>
</head>

<body>

<form id="myForm">
<table id="dataTable">
<tr><td></td><td>Name</td><td>Age</td></tr>

<tr id="row1"><td><input type=checkbox name="cbx1" id="cbx1"></td><td><input type=text value="" id="text1"></td><td><input type=text value="" id="age1"></td><td><div id="ref1"><img src="image/plus1.png" height="10" width="10"></div></td></tr>

<tr id="row2"><td><input type=checkbox name="cbx2" id="cbx2"></td><td><input type=text value="" id="text2"></td><td><input type=text value="" id="age2"></td><td><div  id="ref2"><img src="image/plus1.png" height="10" width="10"></div></td></tr>

<tr id="row3"><td><input type=checkbox name="cbx3" id="cbx3"></td><td><input type=text value="" id="text3"></td><td><input type=text value="" id="age3"></td><td><div id="ref3"><img src="image/plus1.png" height="10" width="10"></div></td></tr>

<tr id="row4"><td><input type=checkbox name="cbx4" id="cbx4"></td><td><input type=text value="" id="text4"></td><td><input type=text value="" id="age4"></td><td><div id="ref4"><img src="image/plus1.png" height="10" width="10"></div></td></tr>

<tr id="row5"><td><input type=checkbox name="cbx5" id="cbx5"></td><td><input type=text value="" id="text5"></td><td><input type=text value="" id="age5"></td><td><div id="ref5"><img src="image/plus1.png" height="10" width="10"></div></td></tr>

 </table>
 <input type="button" id="btnDel" value="Delete"/>
 <input type="button" id="btnChk" value="CheckID"/>
 <input type="button" id="btnChangeId" value="ChangeID"/>
  
</form>
</body>
</html>


Thursday, November 17, 2011

Starting TomcatServer,Through your Java Class

Starting tomcat server through Your java class
***********************************
We generally click TOMCAT_HOME\bin\tomcat7.exe to start the tomcat server
it internally executes org.apache.catalina.startup.  Bootstrap.java
BootStrap.java is a class which contains main()
When we launch tomcat,jvm internally create the object of BootStrap.java and calls main() on it

Write your own Javaclass.From the main() of ur class,call the main() of BootStrap.class,server will start successfully


create the directory structure
*******************************
TomcatProj
   |-->src
   |    |-->StartTomcat.java
   |
   |-->conf
   |    |-->Server.xml(copy & Paste it from TOMCAT_HOME\conf folder)
   |
   |----->lib
       |--->bootstrap.jar         --->main jar file, all others are dependent jar file  
       |--->tomcat-juli.jar  
       |--->catalina.jar      
       |--->servlet-api.jar
       |--->jasper.jar
       |--->jsp-api.jar
       |--->tomcat-coyote.jar
       |--->tomcat-util.jar

Collect first 2 jar from Tomcat_HOME\bin folder
and Remaining jars from TOMCAT_HOME\lib folder

jasper.jar,jsp-api.jar is needed to activate jsp support,other wise not needed



***************StartTomcat.java*****************

import org.apache.catalina.startup.Bootstrap;
public class StartTomcat
{
    public static void main(String[] args) throws Exception
    {
        Bootstrap bs=new Bootstrap();
        bs.main(args);
    }
}


***************Program Ends***********************

Wednesday, November 16, 2011

Accessing Private Methods and Variables in Java

 It is possible to accessing private data members of a java class,from any other classes.
You can achieve this by using reflection API

*****************************AccessingPrivateVariable.java*****************************

import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class BaseClass 
    private String msg= "HelloWorld";
    private String getMsg()
    {
      return msg;
    }
   }
public class AccessingPrivateVariable
{
  public static void main(String[] args)throws IllegalAccessException, InvocationTargetException
  {
     BaseClass bc = new BaseClass();
     Class cls = bc.getClass();
      System.out.println("********Accessing all the methods*************"); 
      Method methods[] = cls.getDeclaredMethods(); 
      for (int i = 0; i < methods.length; i++) 
      { 
           System.out.println(methods[i].getReturnType()+" " +methods[i].getName());
           methods[i].setAccessible(true);
           System.out.println(methods[i].invoke(bc) );
       }
    //  Print all the field names & values
    System.out.println("**************Accessing all the fields************");
    Field fields[] = cls.getDeclaredFields();
    for (int i = 0; i < fields.length; i++){ 
       System.out.println("Field Name: " + fields[i].getName()); 
       fields[i].setAccessible(true); 
       System.out.println(fields[i].get(bc)); 
   }
 }
}

*****************************************PROGRAM ENDS**************************