Wednesday, 27 March 2013

Check Valid extension of file at client side while uploding file

This following example allow to user upload only pdf file.for this example we need the jquery.js file.
<html>
<head>
<script src="jquery.js"></script>
<style>
body {
    margin:1em;
    font-size:.9em;
}
h1 {
    margin:1em 0;
    font-weight:bold;
}
h1:not(:first-of-type) {
    border-top:1px solid #ccc;
    padding:1em 0 0;
}
p {
    margin:1em 0;
}
p label {
    color:#333;
    font-family:sans-serif;
    display:inline-block;
    padding:.1em .1em .1em .3em;
    background:#f7f7f7;
    border:1px solid #ccc;
}
aside {
    margin-top:-.5em;
}
aside p {
    color:#333;
    font-size:.8em;
    font-family:sans-serif;
}

</style>
<script>
function getExtension(filename)
{

    var parts = filename.split('.');
    return parts[parts.length - 1];
}

function isPDF(filename)
{
    var ext = getExtension(filename);
    switch (ext.toLowerCase())
    {
    case 'pdf':
   
        /*
        etc
        like
        'xsl'
        */
        return true;
    }
    return false;
}

function failValidation(msg)
{
            alert(msg);
            return false;
}
function validate()
{      
        var file = $('#file');    
       
        if (!isPDF(file.val()))
        {
            return failValidation('Please select a valid file');
        }
               
        // indicate success with alert for now
        alert('Valid file');
        return true;
 }

</script>
</head>
<body>

<form name="frmpdf" action="connect.jsp" onsubmit="return validate()">
<h1>Match all pdf  files (application/pdf)</h1>
<p><label>Pdf File <input type="file" id="file" accept="application/pdf"></label></p>
<input type="submit" value="submit">
</form>
</body>
</html>

for checking image you can write following function.
function isImage(filename) 
 {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) 
   {
    case 'jpg':
    case 'gif':
    case 'bmp':
        //etc
        return true;
    }
    return false;
}

Tuesday, 26 March 2013

How to read and write value in List,Map,Set using getter and setter method in java

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.*;


public class CollectionEG
{

private Set setv;
private List listv;
private Map<String,String> mapv;


public Set getSetv() {
    return setv;
}
public void setSetv(Set setv) {
    this.setv = setv;
}
public List getListv() {
    return listv;
}
public void setListv(List listv) {
    this.listv = listv;
}
public Map<String, String> getMapv() {
    return mapv;
}
public void setMapv(Map<String, String> mapv) {
    this.mapv = mapv;
}

public static void main(String args[])
{
    CollectionEG cd=new CollectionEG();


    //This example for Map
    Map<String,String> map=new HashMap<String,String>();

        map.put("one","1");
        map.put("two","2");
        map.put("three","3");

        cd.setMapv(map);
        map=null;
        map=cd.getMapv();


        Set s=map.entrySet();
        Iterator mapIterator = s.iterator();
        System.out.println("Map Demo");
        while(mapIterator.hasNext())
        {
            Map.Entry mapEntry = (Map.Entry) mapIterator.next();
            // getKey Method of HashMap access a key of map
            String keyValue = (String) mapEntry.getKey();
            //getValue method returns corresponding key's value
            String value = (String) mapEntry.getValue();
            System.out.println("Key : " + keyValue + "= Value : " + value);

        }



    //This example for List
    System.out.println("List Demo");
    List list=new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    cd.setListv(list);

    list=null;
    list=cd.getListv();
    for(int i=0;i<list.size();i++)
    {
        System.out.println(list.get(i));
    }


    //This example for Set
    System.out.println("Set Demo");
      Set<Integer> set = new TreeSet<Integer>();

    set.add(1);
    set.add(2);
    set.add(3);

    cd.setSetv(set);

    set=null;
    set=cd.getSetv();

    Iterator<Integer> iterator = set.iterator();
    while(iterator.hasNext())
    {
        Integer setElement = iterator.next();
        System.out.println(setElement);
    }

  }
}

Friday, 22 March 2013

How to set session and destroy session and setInactive time of session in jsp

1)Set the session
<%
String uname="ishwar";
session.setAttribute("name",uname);
%>

2)read the value of session and if user is not login then redirect to login.jsp page
<%
if(session.getAttribute("name")==null)
{
    out.println("<script>alert('please login first')</script>");
    out.println("<script>location.href='login.jsp'</script>");
   
}
else
{
    String uname=(String)session.getAttribute("name");
    out.println("uname is"+uname);
}
%>

3)Destroy or Delete the session
<%
    session.invalidate();
%>

4)set inactive time for session

for programmatically set session
This for 10 seconds
<% session.setMaxInactiveInterval(10); %>

This will set your session to keep everything till the browser is closed
<% session.setMaxInactiveInterval(-1); %>

This should set it for 1 day
<% session.setMaxInactiveInterval(60*60*24); %>

Other way you can set inactive time for session in web-inf file
<web-app>
<session-config>
<session-timeout>10</session-timeout>
</session-config>
</web-app>

Thursday, 21 March 2013

How to disable Browser back button using java script

<html>
<body>
<head>
<SCRIPT type="text/javascript">
    window.history.forward();
    function noBack() { window.history.forward(); }
</SCRIPT>
</head>
<body onload="noBack();"  onpageshow="if (event.persisted) noBack();" onunload="">
<h1>Disable Back Button Demo</h1>
</body>
</html>

Tuesday, 19 March 2013

how to find current location using javascript & jquery

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js">
    </script>
    <script src="http://j.maxmind.com/app/geoip.js"></script>
   <script src="http://maps.google.com/maps/api/js?sensor=false"></script>

<script>

    // wire up button click
    function fun1()
    {
        
        // test for presence of geolocation
        if (navigator && navigator.geolocation)
         {
            // make the request for the user's position
            navigator.geolocation.getCurrentPosition(geo_success, geo_error);
        }
         else
         {
            // use MaxMind IP to location API fallback
            printAddress(geoip_latitude(), geoip_longitude(), true);
        }
    }

function geo_success(position)
 {
    printAddress(position.coords.latitude, position.coords.longitude);
}

function geo_error(err)
{
    // instead of displaying an error, fall back to MaxMind IP to location library
    printAddress(geoip_latitude(), geoip_longitude(), true);
}

// use Google Maps API to reverse geocode our location
function printAddress(latitude, longitude, isMaxMind)
{
        // set up the Geocoder object
    var geocoder = new google.maps.Geocoder();

    // turn coordinates into an object
    var yourLocation = new google.maps.LatLng(latitude, longitude);

     // find out info about our location
    geocoder.geocode({ 'latLng': yourLocation }, function (results, status)
    {
        if (status == google.maps.GeocoderStatus.OK)
        {
            if (results[0])
            {
                $('body').append('<p>Your Address:<br />' +
                    results[0].formatted_address + '</p>');
            } else
            {
                error('Google did not return any results.');
            }
        }
        else
        {
            error("Reverse Geocoding failed due to: " + status);
        }
    });

  
}

function error(msg) {
    alert(msg);
}
</script>

</head>
<body>
<b id="my"></b>
<input type="button" id="go" value="Click Me To Find Your Address" onclick="fun1()">
</body>
<script>
</script>
</html>

How to upload image and read other form data too in jsp

Here we are using the two packages for upload the picture which provides by apache.org.
1)commons-fileupload-1.2.2
2)commons-io-2.4
This two files you can download from google or you can download full example of this program.
after download this two files you have to paste .jar file from this two folder into apche tomate lib files
.these are files
1)commons-fileupload-1.2.2.jar,commons-io-2.4.jar
The first jar files is used for upload your image and second jar file provides functionality for reading the stream data and save data to a file beyond that point.
eg.DeferredFileOutputStream-This class provides utility for store file into disk and this class
available in commons-io-2.4.jar

first your index.html file

<html>
    <head>
        <title>Upload photos</title>
    </head>
    <body>
    <form name="fupload" action="upload.jsp" method="post" enctype="multipart/form-data">
    <table>
    <tr>
    <td>Name:</td>
    <td><input type="text" name="uname" id="uname"></td>
    <tr>
    <tr>
    <td>Address:</td>
    <td><textarea  name="address" id="address"></textarea></td>
    <tr>
    <td>Profile Picture:</td><td><input type="file" name="photo" id="photo"/></td>

    <tr><td><input type="submit" value="upload"/></td>
    </tr>
    </form>
    </body>
</html>

This is above html file which used select the pdf file.and when you uploding any file you have to specify the form attribute  enctype="multipart/form-data" and method="post". after upload your file when you click on submit button its will call the upload.jsp file.

second is upload.jsp fle

<%@ page import="java.util.List" %>
   <%@ page import="java.util.Iterator" %>
   <%@ page import="java.io.File" %>
   <%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
   <%@ page import="org.apache.commons.fileupload.disk.*"%>
   <%@ page import="org.apache.commons.fileupload.*"%>
  
   <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  
<%

     boolean isMultipart = ServletFileUpload.isMultipartContent(request);
     if (!isMultipart)
     {
     }
     else
     {
       FileItemFactory factory = new DiskFileItemFactory();
       ServletFileUpload upload = new ServletFileUpload(factory);
       List items = null;
       try
       {
               items = upload.parseRequest(request);
       }
       catch (FileUploadException e)
       {
               e.printStackTrace();
       }
       Iterator itr = items.iterator();     //this will create iterator object from list..used for traversing the data.
       String uname="",uadd="";
       while (itr.hasNext())
       {
           FileItem item = (FileItem) itr.next();
         
           if (item.isFormField())   //checking if its normal field then we read as normal. no need to store in disc
            {
                        String name = item.getFieldName();
                       String value = item.getString();
                                           
                       if(name.equals("uname"))
                       {
                               uname=value;
                              
                        }
                       else if(name.equals("address"))
                        { 
                                   uadd=value;                       
                           
                        }                                                       
                                
            }
            else                                      //this else part for process about PDF file
             {
                try
                {
       
                   String itemName = item.getName();    //this will return the pdf file name
                   String filename=request.getRealPath("") + "/uploads/";
                   filename=filename+itemName;       //now concatenation the file name with upload  path.
                   File savedFile=new File(filename);
                      
                       item.write(savedFile);    //saving file into disc,item contain which you select the file.
                                                                //here item will copy into the savedFile and store into disk

                       out.println("successfull");
                       response.sendRedirect("index.html");
                }
                catch(Exception ste)
                {
                    out.println(ste);
                }
              }
          }
          out.println("the user name is"+uname);
          out.println("the address is"+uadd);
       }
%>
The above file which is used the
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
This will used for checking the whether your request is contain file data and other data or not.

for save pdf file into disc we need to creare FileItemFactory object and ServletFileUpload object

 FileItemFactory factory = new DiskFileItemFactory();
  ServletFileUpload upload = new ServletFileUpload(factory);

for reading the request we need to parse and it will return the List types.
items = upload.parseRequest(request);
Now items will contain the all data.

The request.getRealPath() will return the where deploy the your application and in my application i create uploads folder and i want to save pdf file in the uploads folder.


     



You can download full example from here

Friday, 15 March 2013

How Create From and To calander using Jquery

<html>
<head>
<link rel="stylesheet" href="css/jquery-ui.css" />
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
 $(function()
 {
$( "#from" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
</script>
</head>

<body>
<label for="from">From</label>
<input type="text" id="from" name="from" />
<label for="to">to</label>
<input type="text" id="to" name="to" />

</body>
</html>
The view of above file is.


You can download above example from here

Monday, 11 March 2013

how to fill select option tag value base on other select option tag without realoading page using jQuery in jsp page.

 Hi friends.before jQuery was not introduce that time we filling the other select tag option value base on reloading  the page but in this situation the entire page reload and if user is selected data that also lost so overcome this problem jQuery is come so i am writing following example which is filling select tag option value base on select option value of other select tag without reloading entire page.

In this example when user change value of one select tag the second select tag option value will  fill base on value user select in first select tag. i am filling the select tag value from database so i need to connect with database also.

->first you need to create jsp file for establish connection with database.
Connection.jsp
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*" %>
<%!
    Connection con;
    String sql="";
    ResultSet rs;
    Statement stmt;
%>
  
<%  
   try
    {      
         Class.forName("com.mysql.jdbc.Driver").newInstance();
          con = DriverManager.getConnection("jdbc:mysql://localhost/cricketdb", "root", "");   
          stmt=con.createStatement();
       

   }
  catch(SQLException sa)
  {
     out.println("Error loading driver:" + sa.getMessage());  
  }
%>
This above file only used for establishing connection between jsp program and the MySQL database. so after creating this file we need to just  include this file whenever we need to connect with database.

->second step create jsp file which contain select tag
Cricket.jsp
<html>
<head>
    <title>Cricket View Data</title>
<script  src="jquery.js"></script>
<script>

    function fillplayer()
    {
      
        var countryv=document.getElementById("country").value;
      
        var url="connectCricket.jsp?country="+countryv;
      
        $.ajax({
            url:url,
            type:"POST",
            success:function(results)
            {
               
                document.getElementById('player').innerHTML=results;

            },
            error:function(data)
            {
                alert('error'+data);
            }
            });

    }
    </script>
    </head>
    <body>
    <form name="nm">
     Country<select  name="country" id="country" onchange="fillplayer()">
            <option value="">Select</option>
            <option value="india">india</option>
            <option value="pakistan">Pakistan</option>
            </select>
            <br/>
      
       Player:  <select name="player" id="player">
                  <option value="">Select players</option>
                </select>
      
    </form>
    </body>
    </html>

This above file Contain the two select tag one Country and second is Player. when user change the Country name then fillplayer() function will invokes and the fillplayer() function will send request to connectCricket.jsp file and also i am passing the parameter which is value selected in Country select tag so base on Country select tag value the connectCricket.jsp will give back response and if its successful then 
success:function(results) will invoke. if in case connectCricket.jsp file return error then it will invoke the error:function(data) and display error.

if its success then i am writing in success funtion
document.getElementById('player').innerHTML=results;
here
'player'=this is an id of Player select tag
The innerHTML is an property of document which is replace the content of select tag so here 'results' which is response comes from the connectCricket.jsp file i am assigning to player.so it will replace the value of select tag option.



->Third step create connectCricket.jsp file which file called by the jQuery(internally by the AJAX) and send back response.
connectCricket.jsp
<%@ include file="connect.jsp"%>
<%
   String country=request.getParameter("country");
      
  
   sql="select *from players where country='"+country+"'";
   rs=stmt.executeQuery(sql);
 
   String buffer="";
   while(rs.next())
   {
     
       buffer=buffer+"<option value='"+rs.getString("pname")+"'>"+rs.getString("pname")+"</option>";
   }
   out.println(buffer);
 %>

This file which read the 'country' name which send by the Ajax and base on this country value i am fetching data from database and dynamically creating option tag and storing into the one String buffer variable.after assigning all option to buffer variable i am just printing it using  'out.println(buffer)' so here i am printing the buffer variable which is contain the list of option so this output send back as a response.

after finish the execution of the above file its go back and base of response its will invoke either error function or success funtion.

if above file return list of option value then following function will invoke in the Cricket.jsp file

success:function(results)
now 'results' will contain the list of option

if above file  return error message then the error function will invoke in the Cricket.jsp file
error:function(data)
now 'data' is contain the error details.

 for above example you need to create database name cricketdb and table names players  which have follwoing fields.
country varchar2(10)
pname varchar2(10))

How to disabled and change color of particular date and display tooltips in datepicker

<html>
<head>

<link rel="stylesheet" href="jquery-ui.css" />
<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>

<style>

.wrapper {
    padding: 10px;
}
td.red span.ui-state-default {
    color: #f00;
}
td.green span.ui-state-default {
    color: #0f0;
}
td.yellow span.ui-state-default {
    color: #700;
}


</style>

<script type="text/javascript">
$(function() {

$('input').datepicker({
dateFormat: "yy-mm-dd",
minDate: "-0d",
    maxDate: "+90d",
    firstDay: 0,
    beforeShowDay: noWeekendsOrHolidaysOrBlockedDates

});

});


function noWeekendsOrHolidaysOrBlockedDates(date)
 {
    //var noWeekend = jQuery.datepicker.noWeekends(date);
    return setHoliDays(date);
}

// set holidays function which is configured in beforeShowDay

function setHoliDays(date)
{
    var day = date.getDay();
    if(day == 5 || day == 6)
        return [false, ''];

    if(date.getDate() == 11 || date.getDate() == 23)
        return [ false, 'holiday red', 'Red!' ];
    if(date.getDate() == 12 || date.getDate() == 22)
        return [ false, 'holiday green', 'Green!' ];
    if(date.getDate() == 24)
        return [ false, 'holiday yellow', 'all ready booked!' ];
    return [true, ''];
}
</script>
</head>


<body>

<div class="wrapper">
    <input type="text" id="b">
</div>
</body>
</html>
If you want to add more date then you can add in  the setHoliDays function as showing in above example.
You can download from here

Friday, 8 March 2013

How to Convert Date fomate in java or jsp

<%@ page import="java.text.*;"%>
        <%!
            String billdate="";
            SimpleDateFormat sdfSource,sdfDestination;
                    //there is sql Date is also availbe so u have to write following way
            java.util.Date date;
                    //this method convert user date to database formate
            public String UITODB(String bdate)
            {
                try
                {
                     sdfSource = new SimpleDateFormat("dd/MM/yyyy");
                     date = sdfSource.parse(bdate);
                     sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
                     billdate=sdfDestination.format(date);
                    
                }
                catch(Exception e)
                {
                   
                }
                return billdate;
               
            }
           
            //this method convert databse mysql formate to user date
            public String DBTOUI(String bdate)
            {
                try
                {
                     sdfSource = new SimpleDateFormat("yyyy-MM-dd");
                     date = sdfSource.parse(bdate);
                     sdfDestination = new SimpleDateFormat("dd/MM/yyyy");
                     billdate=sdfDestination.format(date);
                    
                }
                catch(Exception e)
                {
                   
                }
                return billdate;
               
            }
                      
          
        %>
        //how to call above function
       
    <%=UITODB("04/02/1987")%> //this will print:1987-02-04
   
    <%=DBTOUI("1987-02-04")%>  //this will print:04/02/1987

How to get todays day name using java

<%@ page import="java.util.*" %>
<%
        Calendar c = Calendar.getInstance();
        int day = c.get(Calendar.DAY_OF_WEEK);
        String dname="";
       
         switch(day)
          {
          case 1: dname="Sunday";
          break;
          case 2: dname="Monday";
          break;
          case 3: dname="Tueseday";
          break;
          case 4: dname="Wednesday";
          break;
          case 5: dname="Thursday";
          break;
          case 6: dname="Friday";
          break;
          case 7: dname="Saturday";
          break;
          }
          System.out.print("Todays Days is"+dname);
   
%>

Thursday, 7 March 2013

How to Read your email of gmail account using java mail api

import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.*;
import javax.activation.*;

public class FetchMail
{

    public static void main(String[] args) {

        // SUBSTITUTE YOUR ISP's POP3 SERVER HERE!!!
        String host = "pop.gmail.com";
        // SUBSTITUTE YOUR USERNAME AND PASSWORD TO ACCESS E-MAIL HERE!!!
        String user = "your user name";   //eg.  "ishwar"
        String password = "your gmail password";   //e.g "ishwar123"
        // SUBSTITUTE YOUR SUBJECT SUBSTRING TO SEARCH HERE!!!
        String subjectSubstringToSearch = "Test E-Mail through Java";

       
        Properties props = new Properties();
        props.put("mail.pop3s.starttls.enable", "true");
         Session session = Session.getDefaultInstance(props,null);

        try
         {

            // Get a Store object
            Store store = session.getStore("pop3s");
            store.connect(host,995,user, password);

            // Get "INBOX"
            Folder fldr = store.getFolder("INBOX");
            fldr.open(Folder.READ_WRITE);
            int count = fldr.getMessageCount();
            System.out.println(count  + " total messages");

            // Message numebers start at 1
            for(int i = 1; i <= count; i++)
            {
                        // Get  a message by its sequence number
                Message m = fldr.getMessage(i);

                // Get some headers
                Date date = m.getSentDate();
                Address [] from = m.getFrom();
                String subj = m.getSubject();
                String mimeType = m.getContentType();
                System.out.println(date + "\t" + from[0] + "\t" + subj + "\t" + mimeType);
            }

            // Search for e-mails by some subject substring.
            String pattern = subjectSubstringToSearch;
            SubjectTerm st = new SubjectTerm(pattern);
            // Get some message references
            Message [] found = fldr.search(st);

            System.out.println(found.length +" messages matched Subject pattern \"" +pattern + "\"");

            for (int i = 0; i < found.length; i++)
            {
                Message m = found[i];
                // Get some headers of email
                Date date = m.getSentDate();
                Address [] from = m.getFrom();
                String subj = m.getSubject();
                String mimeType = m.getContentType();
                System.out.println(date + "\t" + from[0] + "\t" + subj + "\t" + mimeType);

                Object o = m.getContent();
               
                if (o instanceof Multipart)
                {
                    System.out.print("**This is a Multipart Message.  ");
                    Multipart mp = (Multipart)o;
                    int count3 = mp.getCount();
                    System.out.println("It has " + count3 +
                        " BodyParts in it**");
                    for (int j = 0; j < count3; j++)
                    {
                        // Part are numbered starting at 0
                        BodyPart b = mp.getBodyPart(j);
                        String mimeType2 = b.getContentType();
                        System.out.println( "BodyPart " + (j + 1) +
                                            " is of MimeType " + mimeType);

                        Object o2 = b.getContent();
                        if (o2 instanceof String)
                        {
                            System.out.println("**This is a String BodyPart**");
                            System.out.println((String)o2);
                        }
                        else if (o2 instanceof Multipart)
                        {
                            System.out.print(
                                "**This BodyPart is a nested Multipart.  ");
                            Multipart mp2 = (Multipart)o2;
                            int count2 = mp2.getCount();
                            System.out.println("It has " + count2 +
                                "further BodyParts in it**");
                        }
                        else if (o2 instanceof InputStream) {
                            System.out.println(
                                "**This is an InputStream BodyPart**");
                        }
                    } //End of for
                }
                else if (o instanceof String)
                {
                    System.out.println("**This is a String Message**");
                    System.out.println((String)o);
                }
                else if (o instanceof InputStream)
                {
                    System.out.println("**This is an InputStream message**");
                    InputStream is = (InputStream)o;
                    // Assumes character content (not binary images)
                    int c;
                    while ((c = is.read()) != -1)
                    {
                        System.out.write(c);
                    }
                }

             

            } //End of for

           
            fldr.close(true);
            store.close();

        }
        catch (MessagingException mex)
        {
           
            mex.printStackTrace();
        }
        catch (IOException ioex)
        {
            ioex.printStackTrace();
        }

    }


}
for above program you need to download two jar file
1)jaf-1.1.1
2)javamail-1.4.5
One more things you need to enable the POP protocol in your gmail account .

  1. You login in your gmail account.
  2. Click on the Gear icon in the top right-hand corner of your screen and select Mail settings.
  3. Click on Forwarding and POP/IMAP.
  4. Under POP Download/Status select the Enable option that you prefer.
  5. Under POP Download/When messages are accessed with POP select the option that you prefer. We recommend that you select one of the options that leaves a copy of your messages on the server. This allows you to view your e-mails from more than one location and also insures that you always have a backup on the Gmail servers.
  6. Click Save Changes.