Saturday, April 20, 2013

set classpath in windows

| 0 comments

Set classpath in windows


  •  Right click on MyComputer and click Properties
  •  Click on Advance system settings-->Environment Variable
  •  Select classpath and click on Edit
  •  Give Path to your jar file and end it up with semicolon

Friday, April 19, 2013

How to debug a client side script

| 0 comments
All we know that javascript/jquery are client side Script and only run on web browser like Mozilla Firefox.Google chrome.Safari etc.but there is no way to find bug on clientside script,we have to alert at many places to find bug.Now like sever side script we can also debug client side script ,for this web developer tool required of that browser.For exmaple Firebug in Mozilla Firefox.
Steps to add Firebug on your mozilla firefox
  • Press Ctrl+Shift+A
                          
  • In Search box type Firebug and click on install.if you don't find it here then you can download it from Download Firebug and when it install ,it require restart browser
  • After restart  you can see inspect element with firebug in Mozilla firefox by Right click
                           
    Firebug Interface
     check all the field and view all panel if it is disable then manually enable it.By default it some panel are disable
    Create a html page of below coding and run it on Mozilla Firefox.. 
    For Example
    <html>
    <head>
    <title>index</title>
    </head>
    <script src="YourJavaScript.js" type="text/javascript"></script>
    <script>
    display function()
         {
            var name = document.getElementById("name").value;
            alert(name);
         }
    </script>
    <body>
        <form action="#">
            <label>Enter Name</label> <input type="text" id="name"> <input
                id="btn" onclick="display();" type="submit">
        </form>
    </body>
    </html>
    Now It will not run .
    Open console panel that show error in the script

    Error Say Missing ; before statement because it assume display as token of previous block ,which is not yet close by semicolon.Now we got the idea how to fix it ,it's Syntax error function is a type and  display is name of this type ,so it must be place after the type like this
    Place this in coding function display()
    Now correct the syntax and run it.It work fine,if we want to see what happen after that onsubmit of button where control goes,then we can debug it
    Open Script panel and choose your particular script because it show html file containing script ,Jscript api and script of event .Chosse html file containing script
             
    Now place a breakpoint by simple click on leftpane corresponding to particular line.As shown below
            
    It time run a page, fill name in the text field and click on SubmitQuery.Page load will pause on this breakpoint
    ,move the control one step to next line by pressing F11.
            
    Now on place your mouse cursor on "name" and it show it's value
            
    Click F8 to continue.It's a small example but in large program it is very helpful.If you have any doubt place a comment below



    Tuesday, April 16, 2013

    How to upload file using jsp using FileRenamePolicy

    | 13 comments
    How to upload file from jsp?Java servlet  API doesn't provide any class to handle file upload.So we have to download external library to upload file Download Jar.File uploading can be done only with doPost and by using enctype "multipart/form-data" .By default it's enctype is"application/x-www-form-urlencoded" Feature of various enctype given below

    valueDescription
    application/x www form urlencodedSpace of url converted to "+" symbols and special characters are converted into ASCII HEX values.All characters are encoded before sent
    mulipart/form-dataValue is required when you are using rms that have a file upload file contol(no characters are encoded)
    text/plainSpaces are converted into "+" symbols.No specical character are encoded.
    The Structure of form is like
    <form name="form" method="post" enctype="multipart/form-data"action="YourController">
            <input  type="file"  name="file" size="50" />              
            <input  type="submit" name="Insert" value="Insert">
    </form>
    Coding at Controller
    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    if (ContextType.indexOf("multipart/form-data") >= 0) {
        MultipartRequest m = new MultipartRequest(request, "yourpath");
        m.getOriginalFileName("file") ;//return the name of uploaded file  
       } 
    }
    MultipartRequest Constructor have 
    MultipartRequest(HttpServletRequest request, String saveDirectory,int maxPostSize,String encoding,FileRenamePolicy policySource Code
    • request the servlet request.
    • saveDirectory the directory in which to save any uploaded files.
    • maxPostSize the maximum size of the POST content.
    • encoding the encoding of the response, such as ISO-8859-1
    • policy a pluggable file rename policy
    File rename policy is used to rename a file,Suppose you upload a file but in upload folder, file existed with same name,then it cause overwrite the old file with new one.So solution is to use File rename policy
    • It automatically add number to file name
    • Example sample.txt ,sample1.txt,sample2.txt and so on
    import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
    MultipartRequest m = new MultipartRequest(request, Path, 5024 * 1024, new DefaultFileRenamePolicy());
    It automatically add number to filename.
    But if you want to give name according to your standard then
    MultipartRequest m = new MultipartRequest(request, Path,
                        5024 * 1024, new FileRenamePolicy() {
                            @Override
                            public File rename(File arg0) {
                                boolean result = arg0.renameTo(new File(arg0
                                        .getParentFile().getAbsolutePath()
                                        + File.separator + "Standard"));
                                if (result) {
                                    System.out.println("Renamed");
                                }
                                return arg0;
                            }
                        });

    But file.renameTo() have unpredictable behaviour on Windows, it seems. As the API documentation says,

    Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

    You can use apache.commons.io library, which includes FileUtils.moveFile() or also the Files.move() method in JDK 7.

    At bottom line we can successfully use DefaultFileRenamePolicy on windows.If you have any Confusion or any doubt then leave a message below or email me 
     

    Saturday, April 13, 2013

    How to create gridview dynamically in jsp

    | 0 comments
    How to generate gridview dynamically on runtime.We all waste lot of time ,to manage data in Grid view (Table Form ) Each Time when there is another Database table,we have to create a new Grid view for that.We can utilize this time while creating a single Grid view control that automatically generate Grid view.That Control accept Collection and bean object from us and generate the corresponding Grid View.This can be done by using reflection,Now there is no need to typecast the collection(ArrayList) and iterate it.While using reflection we can retrive the fields of any object. there is example
           for (Field field : bean.getClass().getDeclaredFields())
               {
                 field.setAccessible(true); //set it to make Accessiable
                 System.out.println( field.getName());
               }
    Here bean is object and field object save the Fields retrive form bean object This code print the field name of your bean object(In Control this fieldname became the heading of grid view).Now how to retrive the value from the collection Object
           for (Field field : collection.getClass().getDeclaredFields())
                {
                    field.setAccessible(true);
                    Object value;
                    value = field.get(collection);// Retrive the vale from the Collection object
                    System.out.println(value);
                }
    field.get(Object) return the value in field From this code we retrive the value's of collection.Now you got the basic idea how control works.I already created Grid view Control,You just have only to use it Download Code  .Here is Smaple view for the output of control
    Pass the Collection and bean object,name of servlet .when you click on Select or Delete the form is submitted and control goes to servlet (which you specify).And you have to chosse one unique field accordingly which perform Select or Delete operation .Suppose I want to select or delete field  according to Id (As specified in Image),then I set index in my code to 0 and if I want to do operation according to Name then I set index to 1 and so on ,Start it from 0.Here is Code for Passing bean object,Collection Object ,Servlet Name and Index.
    <%
           SignupDA sa = new SignupDA();
           Signups da = sa.Getall();//collection object
           Signup be = new Signup();//bean object
           int ind = 0; // It is index
           application.setAttribute("bean", be);
           application.setAttribute("coll", da);
           application.setAttribute("action", "ManageCategory"); servlet name 
           application.setAttribute("index", ind);
        %>
        <%@ include file="/Control/Gridview.jsp"%>
    Collection is nothing new ,it is same as Arraylist<bean> you can use ArrayList<yourbean> instead of Singups,sa is object of DBoperation,be is object of bean class,ind is index,ManageCategory is Servlet.Now how to use the Control on your jsp page.Grid view control is also a jsp page.For this we have to include the Gridview.jsp file on current Jsp which is specifed in previous Code.This way you can use Gridview Control in your project 
    If you click on Link select or delete it will go to the servlet, you can recieve the value in doPost section as shown below 
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException
            {
              String Id = request.getParameter("index");
              String Operation = request.getParameter("operation");
              System.out.println(Id + " " + Operation);
            }
    Here you recieve the index and operation.if you want to delete then you can use"if(Operation.equals("Delete")) {your code}" by using Id (Index value)For Select "if (Operation.equals("Select")) {your code}"

    Here is code for Gridview Control  Download Code 
    If you have any confusion .Please Drop your Comment Below

    Thursday, April 4, 2013

    Where does Eclipse store generated servlet files after jsp run on server?

    | 5 comments
    I wonder many time that where the compiled jsp goes.I can't find it in the Eclipse workspace not in tomcat server directory.I read it in the book ,it say that  the compiled servlet save in the work directory,but I still can't find it.After some effort's fortunately, I find the storage location in the environment variables of Project. but it is tricky way.
     Now in good manner how to find the storage location of your tomcat server
    •  Double Click on the server

    • Now as arrow point to the location ,Catch this location in your Eclipse Workspace  
    • This folder contain the Tomcat Server Container and other important stuff
    • Conf is same as Same as Servers folder in your eclipse workspace 
    • work folder contain the servlet file of jsp. "work\Catalina\localhost\YourProjectName\org\apache\jsp"
    • jsp folder contain the java file and class file .Open Java file in the eclipse,this is compiled form of your jsp file

    Tuesday, April 2, 2013

    Send Email through Java via Gmail,Yahoo,Hotmail or your hosting Email server

    | 15 comments
    How to send email from java? .For this we need an JavaMail API .Include this jar file in your class path by placing it into YourProject\WebContent\WEB-INF\lib or if you are not using EE version then add it into environment variable.
            
         First we need to login to mail account.
    • Email server consist two types of port, one is for incoming mail(POP, IMAP) and another is for outgoing mail(SMTP).For sending purpose we only need SMTP port of that particular Email server.
    • Second thing is how to send authentication data to server using insecure network.To maintain security there is two protocol SSL and TLS which send authentication data(Email,Password) to server in encrypted form,If we use TLS ,it allow both secure and unsecure connection,and if SSL it only allow secure Connection.That is up to user to choose the protocol
    • In java to carry Email account setting,we use Properties,These Email settings are 
                1. smtp host
                2. smtp port (either for protocol SSL or for protocol TLS)
                3  valid EmailId and password of active account
         Now Code for Login in Gmail using SSL protocol
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com"); / /      Host Name
            props.put("mail.smtp.socketFactory.port", "465");/ /       SSL Port     
            props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");
            Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator()
                { protected PasswordAuthentication getPasswordAuthentication()
                    {  return new PasswordAuthentication("YOUREMAIL@GMAIL.COM", "PASSWORD");
                     }
                 });
         
     Now Code for Login in Gmail using TLS protocol
           Actually Gmail use STARTTLS

            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");/ /       Host Name
            props.put("mail.smtp.port", "587"); / /    TLS Port
            Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator()
                { protected PasswordAuthentication getPasswordAuthentication()
                    {  return new PasswordAuthentication("YOUREMAIL@GMAIL.COM", "PASSWORD");
                     }
                 });
    • Now after login we have to compose email,First understand our email message cannot simply transfer through http,for this a particular standard are set and those are mime standard,our email server use mime to transfer email ,first it convert the email message into mime format and transfer it on network Know more about Mime
    • Email Header contain all the information about the message and Routing information.
    • Use MimeMessage to create mail format. It provide option to set From ,where and To whom ,email is going to be sent and it also provide setSubject to set the Subject of Email.
    •  After that,it give freedom to setContext of email.Use text/html if you want to send html in message else there is no need to setContext to text/html
    • At Last Transport.send(message),same as we click on send button in email client application
          Message message = new MimeMessage(session);
          message.setFrom(new InternetAddress("YOUREMAIL@GMAIL.COM"));
          message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(TO@XYZ.COM));
          message.setSubject("My First Email using Behind Java Scene");
          String msg="Thank's to Behind Java Scene to teach the core aspect of Email sending "
          message.setContent(msg, "text/html; charset=utf-8");
          Transport.send(message);
      
       Email Server Settings for Yahoo
         Only change the host Name and SMTP port from Login code 
         Host Name :smtp.mail.yahoo.com
         SMTP port: 465 
            Properties props = new Properties();
            props.put("mail.smtp.socketFactory.port", "465");  
            props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.host", "smtp.mail.yahoo.com");
            props.put("mail.smtp.auth", true);  
       Email Server Settings for Hotmail 
         Only change the host Name and SMTP port from Login code in SSL section 
         Host Name: smtp.live.com 
         SMTP port: 25  
     Same for Hosting Server only change your particular Host Name and change your specific SMTP port

    Sunday, March 31, 2013

    How to import web application from one system to another system

    | 0 comments
    How to import  web application from one system to another without any error.One method is to just copy the project from one Workspace to another ,but some time it's not successfully deploy and Tomcat(Catalina Container) will not synch with that project.Best way to deploy the web application from one system to another is, creating a WAR file(Web application ARchive) from web application ,Same as jar file in java Project.
    Steps to Create War File
    • Open Web Application Right click on Deployment Descriptor-->Export->War file


    •  Set the path where to save and name given to war file,here,I change the war filename because if i give same name then it conflict with existing Project,But you can put the same name if you are deploying it on another system.
    •  Click on Finish 
    • Now how to deploy War file on another system.Click on File-->Import 
                                

    • Select Web-->War Next.                                                                                                           
                  
    •  Browse the War file where it is saved and click on Finsh
              
    • Now it successfully import the Web Application without any Error

    Friday, March 29, 2013

    Several Port(8080, 8009) Error how to remove without restarting eclipse

    | 0 comments
    We all got this error many time but we just simply restart the eclipse to avoid.Now why this error occur



    1. Because there is already one tomcat server is running and we try to run another tomcat server.It seem Previous tomcat is out of synch or not stopped.
    2. What happen when we restart the eclipse ,it destroy the running tomcat from memory 

     Is it possible to handle this error without restarting eclipse ???
    1. Yes
    2. How?
    3. delete the running tomcat from memory.
    4. what i have to do for this?
    5. open  task manager in Process bar find the process called javaw.exe and just end this process,this delete the running tomcat from memory
    6. Now go back run your application ,It's working fine now.

    Friday, March 15, 2013

    Behind the scene of First Program

    | 4 comments
    Running a java program give the output on console.but to analysis the detail of java program ,need to debug using Breakpoint,on which line we  have to pause the execution of running java program,just simply Toggle Breakpoint on that line .Right Click on corresponding line as show below

       Here Toggle Breakpoint on Main function and then click on debug  button as shown below
      
       Chosse yes for Debug perspective
                   
    Overview of Debug perspective .It Contain the debug Section where current thread on execution is shown
    and variable section show the stack of current java program (local variable).Debug current Instruction pointer indicate that upto which line processing has been done and on which line it point has to be done

    press f6 button to go on next line and it will show the output on console section .f6 is used to step over.

    abstraction is naked in next post ,this post just give idea that how to run the debug perspective.

    Tuesday, March 12, 2013

    Setup System to run java programs

    | 0 comments
    To run a java program we first need a jdk install on our machine,So download Jdk and Eclipse Juno from  http://www.eclipse.org/downloads/packages/release/indigo/sr2



    Chosse your downloading option according to operating system.If your operating system is 32-bit the choose operating system 32 Bit else choose operating system 64 Bit.After Download just Extract the eclipse-jee-indigo-SR2-winXX-XX_.XX.zip.No need of installation




    Click on the eclipse.exe 
    After that it required the workspace where all the project will be save .Give path to the WorkSpace

     Click on Java Project


    Next->Give Project name

     Click Finish and make it default perspective

    Right Click on src >new>class


    Give Class Name ,Check the method Stub to public staic void main(String[] args) and Finish

    Create the first basic Program  and click on arrowed button to run the program

    Output display in Console.Now you successfully create your first program.In next post discussion on the what happen when we run the Program behind the scene.