Friday, 13 September 2013

how to Concate the JSON Arary in java

This example is use for the concate or merge the more than one json Aray into signle json Array and for this example we need to download the json-lib-2.4-jdk15 library.

 import net.sf.json.JSONArray;  
 import net.sf.json.JSONException;  
 public class JsonConcateDemo {  
       public static JSONArray concatArray(JSONArray... arrs)throws JSONException   
       {  
         JSONArray result = new JSONArray();  
         for (JSONArray arr : arrs) {  
           for (int i = 0; i < arr.size(); i++) {  
             result.add(arr.get(i));  
           }  
         }  
         return result;  
       }  
       public static void main(String args[])  
       {  
            JSONArray jsonArray1=new JSONArray();  
            jsonArray1.add(0,"one");  
            jsonArray1.add(1,"two");  
            JSONArray jsonArray2=new JSONArray();  
            jsonArray2.add(0,"three");  
            jsonArray2.add(1,"four");  
            System.out.println("the JSONARRAY1:"+jsonArray1.toString());  
            System.out.println("the JSONARRAY2:"+jsonArray2.toString());  
            System.out.println("New concate array JSONArray1 and JSONArray2"+concatArray(jsonArray1,jsonArray2));  
       }  
 }  

The Output
 the JSONARRAY1:["one","two"]  
 the JSONARRAY2:["three","four"]  
 now new concate array JSONArray1 and JSONArray2["one","two","three","four"]  

Saturday, 10 August 2013

How to bind datasource with InitialContext programatically in java class

This following way data source binding with the InitialContext is used for when you are implementing Junit testing in the project because when you run Junit testing the project is not deploy so if you initialized data source in tomee.xml and web.xml is not initialize.so for this reason you have to invoked one method for the initialize the data source problematically like following way.

Here i am showing example with java and MySQL if you are using any other database then you just need to
change 'url'  properties and 'driverClassName' properties.

Here i created two methods
1)initialdsn()
    This method binding the data source with InitialContext so in future we can get using jndi lookup.
2)checkdsn()
    This method is showing that how you will access data source.

NOTE:Don't forget to include jar file into the classpath.

 import java.sql.Connection;  
 import java.sql.ResultSet;  
 import java.sql.Statement;  
 import java.util.Properties;  
 import javax.naming.Context;  
 import javax.naming.InitialContext;  
 import javax.sql.DataSource;  
 import org.apache.commons.dbcp.BasicDataSourceFactory;  
 public class DSNDEMO {  
      public static void initialdsn()throws Exception  
      {  
                System.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.apache.naming.java.javaURLContextFactory");  
                System.setProperty(Context.URL_PKG_PREFIXES,"org.apache.naming");   
                Properties properties = new Properties ();  
                properties.setProperty("url", "jdbc:mysql://localhost:3306/ops");  
                properties.setProperty("driverClassName","com.mysql.jdbc.Driver");  
                properties.setProperty("maxActive", "10");  
                properties.setProperty("maxIdle", "8");  
                properties.setProperty("minIdle", "10");  
                properties.setProperty("maxWait", "10");  
                properties.setProperty("testOnBorrow", "true");  
                properties.setProperty("username", "root");  
                properties.setProperty("password", "");  
                properties.setProperty("validationQuery", "SELECT 1");  
                properties.setProperty("removeAbandoned", "true");  
                properties.setProperty("removeAbandonedTimeout", "1");  
                properties.setProperty("logAbandoned", "true");  
                DataSource ds = BasicDataSourceFactory.createDataSource(properties);  
                InitialContext ic = new InitialContext();  
                ic.createSubcontext("java:");  
                ic.createSubcontext("java:/comp");  
                  ic.createSubcontext("java:/comp/env");  
                ic.createSubcontext("java:/comp/env/jdbc");  
                 ic.bind("java:/comp/env/jdbc/mydb", ds);  
      }  
      public static void checkdsn()throws Exception  
      {  
           Context initContext = new InitialContext();  
            Context webContext = (Context)initContext.lookup("java:/comp/env");  
          DataSource ds = (DataSource) webContext.lookup("jdbc/mydb");  
          Connection con=ds.getConnection();  
          Statement stmt=con.createStatement();  
          ResultSet rs=stmt.executeQuery("select *from student_master");  
          while(rs.next())  
          {  
               System.out.println(rs.getString(1));  
          }  
      }  
 public static void main(String args[])throws Exception  
 {  
           DSNDEMO.initialdsn();  
           DSNDEMO.checkdsn();  
      }  
 }  

For this you have to download this  naming-common-4.1.31.jar and you need to include in your classpath or you can download from here

So for the above program you need to include following jar file into classpath.

1)naming-common-4.1.31.jar  (This contains class org.apache.naming.java.javaURLContextFactory)
2)commons-pool-1.5.7.jar
3)commons-dbcp-1.4.jar
4)mysql-connector-java-3.0.17-ga-bin

for Junit you create one method and include the initialdsn() source code in that method.

if you are getting any exception then free for comment here.

Friday, 9 August 2013

How to encrypt password in java

This is one of the method for encrypt the password using MD5 and using this method you can encrypt but you can not decrypt the password .

 import java.security.MessageDigest;  
 public class PasswordEncryptDemo {  
      public static String Password(String plainText) throws Exception  
      {  
           MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5");  
           mdAlgorithm.update(plainText.getBytes());  
           byte[] digest = mdAlgorithm.digest();  
           StringBuffer hexString = new StringBuffer();  
           for (int i = 0; i < digest.length; i++)  
           {  
             plainText = Integer.toHexString(0xFF & digest[i]);  
             if (plainText.length() < 2)   
             {  
               plainText = "0" + plainText;  
             }  
             hexString.append(plainText);  
           }  
           return hexString.toString();  
      }  
      public static void main(String args[])throws Exception  
      {  
           String planinText="poolof123";  
           System.out.println("The plain text is:"+planinText);  
           System.out.println("The encrypted text is:"+PasswordEncryptDemo.Password(planinText));  
      }  
 }  

output:
 The plain text is:poolof123  
 The encrypted text is:15e3c36a6a68803819c5d25a053b5535  

Saturday, 25 May 2013

How to import our own java class file in jsp page.

This example is showing  how to create class file and how to use that class file in jsp page.
here I am showing example without using eclipse or any IDE.
When we are developing any project, we need to create one separate class file for connecting with database so here I am creating one class file which is java class file and  I will use whenever i need to connect with database.

First you  need to create class.
DatabaseConnection.java

package myCon;
import java.sql.*;
public class DatabaseConnection
{

    private static Connection connection;

    static
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost/cosociety", "root", "");
        } catch (Exception e)
        {
            System.out.println(e.toString());
        }
    }

    public static Connection getConnection()
    {
        return connection;
    }
  
}
The above java file which i created is to get connection with the database.
When you are creating class, you have to create package for that.If you are not creating package, then at run time jvm always search class file in default package and the class file will not found so jvm will throw errors.so for that we need to create package and our class file we need to store in package.
Now for compilation:
This following compilation is doing using the cmd.
C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\slvsc\inc>javac -
d .  DatabaseConnection.java
after executing the above command, your  class file will be available inside the package, "myConn".
Now you have to create structure for your project.
You have to put myConn package inside the
WEB-INF->classes
you have to create folder like above and put your package inside classes  folder.
Now structure is
WEB-INF->classes-> myCon->DatabaseConnection.class
Then you can call it using the following way.

The following example is used for retrieving data from employee table.
<%@ page import="myCon.DatabaseConnection"%> //this line used for import class in jsp page
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*" %>


<%!
    Connection connection;
    String sql="";
    Statement stmt;
    ResultSet rs,rsn;
%>
<%
   
  try
   {      
    connection=DatabaseConnection.getConnection();
    stmt=connection.createStatement();
    sql="select *from employee";
    rs=stmt.executeQuery(sql);
    while(rs.next())
    {
        out.println(rs.getString("EMP_Name"));
    }
   
   }
    catch(SQLException sa)
   {
        out.println("Error loading driver:" + sa.getMessage());   
   }

%>



How to give validation for email id and mobile number using pattern matching in java script

This is html file which checks for proper email id and mobile number using pattern matching in java script.

 <html>  
 <head>  
 <style>  
 .message  
 {  
 border:0px solid black;  
 background-color:orange;  
 height:20px;  
 width:180px;  
 text-align:center;  
 display:none;  
 }  
 .header11  
 {  
 border:0px solid black;  
 background-color:orange;  
 height:20px;  
 width:180px;  
 text-align:center;  
 display:none;  
 }  
 </style>  
 <script>  
 function validation()  
 {  
   var name=document.getElementById("name").value;  
   var email=document.getElementById("email").value;  
   var mono=document.getElementById("mono").value;  
   var add=document.getElementById("add").value;  
   var loc=document.getElementById("loc").value;  
   if(name=="" && email=="" && mono=="" && add=="" && loc=="")  
   {  
           document.getElementById("name").focus();  
     alert("please Fill the information!");  
     return false;  
   }  
      else if(name=="")  
   {  
             document.getElementById("name").value="";  
             document.getElementById("name").focus();  
       alert("please enter name");  
       return false;  
   }  
   else if(!email.match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/) || email=="")  
   {  
     alert("please enter Email id");  
           document.getElementById("email").value="";  
     document.getElementById("email").focus();  
     return false;  
   }  
   else if(!mono.match (/^(\+91-|\+91|0|9)?\d{10}$/) || mono=="")  
   {  
     alert("please enter Mobile Number");  
     document.getElementById("mono").value="";  
     document.getElementById("mono").focus();  
     return false;  
   }  
   else if(add.trim()=="")  
   {  
     alert("please enter Address");  
     document.getElementById("add").value="";  
     document.getElementById("add").focus();  
     return false;  
   }  
   else if (!loc.match(/^[a-zA-Z]+$/) || loc=="")  
   {  
     alert("please enter Location");  
     document.getElementById("loc").value="";  
     document.getElementById("loc").focus();  
     return false;  
   }  
   else  
        return true;  
 }  
 </script>  
 </head>  
 <body>  
 <div class="header">  
 <div class="header11" id="demo">All Fields manadatory</div>  
 <form action="connect.jsp" onsubmit="return validation()">  
 <div>Name<input type="text" id="name"></div></div>  
 <div>Email<input type="text" id="email" ></div>  
 <div>Mobile No<input type="text" id="mono"></div>  
 <div>Address<textarea rows="5" cols="20" id="add"></textarea></div>  
 <div>Location<input type="text" id="loc"></div>  
 <input type="submit" value="submit">  
 </form>  
 </div>  
 </body>  
 </html>  

Here we use meta-characters (can have special meanings in patterns--do not match themselves)
 meta-characters are:     \ | ( ) [ ] { } ^ $ * + ? .

 A meta-character is treated as a normal character if it is back-slashed.
 period is a special meta-character which matches any character except newline

In some places we use [],that means we can specify a sequence of characters ex..[abcd]. this exactly matches the specified text.we also specify the range or spans of characters by giving dashes.
ex:[a-z] this matches a character with small letter a to z .
 A caret at the left end of a class definition means the opposite.

    Character class abbreviations

   Abbr.       Equiv. Pattern          Matches

   \d               [0-9]                    a digit
   \D              [^0-9]                  not a digit
   \w           [A-Za-z_0-9]           a word character
   \W          [^A-Za-z_0-9]         not a word character
   \s             [ \r\t\n\f]         a whitespace character
   \S             [^ \r\t\n\f]       not a whitespace character


   Quantifiers

    {n} exactly n repetitions
    {m, n} at least m but not more than n
repetitions


Other quantifiers (just abbreviations for the most commonly used quantifiers)
      * means zero or more repetitions
          e.g., \d* means zero or more digits

      + means one or more repetitions
          e.g.,  \d+ means one or more digits

     ? Means zero or one
          e.g., \d? means zero or one digit

    Anchors

 The pattern can be forced to match only at the
      left end with ^; at the end with $

     e.g.1 (mobile number):
(/^(\+91-|\+91|0|9)?\d{10}$/)
in this example we are checking for the proper mobile number.
we gave the expression inside the / / symbol.So that expression will be compared to check the valid        contact number.
here we have given \ symbol.so that the literal meaning(plus) will be retained.
^ symbol is to check at the starting of the expression.

so here we are checking for +91 at the starting of the expression. The meaning of | symbol is 'or' meaning, if the previous condition doesn't match,it checks with the second pattern.so  /^(\+91-|\+91|0|9) is to check +91 'or' +90. and ? symbol is to check 1 or more occurrence of the previous pattern.and finally \d{10}$/  is for checking 10 digits at the end of the expression.


      e.g.2  (email):
    if(!email.match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/) || email=="")

     here we have given caret symbol inside /  /  that means it should check at the starting of the expression.
and also we specified the range..
so ^[_a-z0-9-]+  is to find one or more occurrence of small letter a to z and digits from 0 to 9 at the starting of the expression.

   (\.[_a-z0-9-]+)*  is to literally match the " . "  symbol since its literal meaning is obtained by giving \ symbol and one or more occurrence of alphabets and numeric.  * symbol is to check zero or more occurrence of the pattern.

(\.[a-z]{2,3})$/) and $ at the end of the expression means it checks the pattern at the end of the expression.
here a character should be there at least 2 times but not more than 3 times.

Wednesday, 15 May 2013

How to display pdf file in html page

This is following example will display pdf file using iframe.

 <html>  
      <head>  
           <title>pDf file Display demo</title>  
 </head>  
 <body>  
      <iframe src="TAX.PA.pdf" title="your_title" align="top" height="620" width="100%" frameborder="0" scrolling="auto" target="_self">  
 </body>  
 </html>  

here just you need to give src="pdf file name" then its will display the pdf file name in html page.

Monday, 29 April 2013

How to generate dynamic row and delete that row using add and delete button using jQuery

Hi friends. I am sharing with you that how to generate dynamic row and also delete that dynamic generated row this concept is used when u will developed billing software because in billing software we do not know how many item purchase by customer. So base on customer item we need to generate row or this can be used in the storing contact details of person. Here I giving example for storing contact details of person

For This example we need to include the jQuery.js file.

This GenerateRow.html  file which is generated row and delete row.


 <html>  
 <head>  
 <script src="jquery.js"></script>  
 <script>  
 var k;  
 $(document).ready(function()  
 {  
      k=1;     //for first row  
      $("#rdata").append(showData());  
      $("#add").live('click',function()  
     {  
               k++;        
       $('#rdata').append(showData());  
                $("#counter").val(k);      
     });  
 });  
 function lremove(l)  
 {  
            var lid=l.id;  
            var rowno = lid.match(/\d+$/);  
            if(rowno>1)  //if only one row then i am now allow to remove.if more than then remove that row
             {  
                 $("#line"+rowno).remove();  
             }  
 }  
 function showData()  
 {       
           var str="<table><tr id='line"+k+"'>"  
                     +"<td align='center' width='20'>"  
                          +"<font face='calibri' size='2' color='#'><b>"+k+")</b></font>"  
                     +"</td>"  
                     +"<td align='center' width='150'>"  
                     +"<input type='text' name='name"+k+"' id='name"+k+"' >"  
                     +"</td>"  
                  +"<td align='center' width='80'>"  
                          +"<input type='text' name='number"+k+"' id='number"+k+"' value=''>"  
               +"</td>"  
                  +"<td align='center'>"  
               +"<input type='button' id='add' value='+' height='15' width='15'/></td>"  
                     +"<td><input type='button' value='x' id='remove"+k+"' onclick='lremove(this)' src='Delete.png' height='30' width='30'/></td>"  
                +"</tr></table>";  
       return str;  
 }  
 </script>  
 </head>  
 <body>  
 <table>  
 <caption>Storing Mobile Number</catption>  
 <tr>  
      <td width='70'></td>  
      <td width='140' align='left'>Name</td>  
      <td width='150' align='left'>Mobile Number</td>  
 </tr>  
 </table>  
 <form name="frminfom" action="ConnectRowGenerate.jsp">  
      <div id="rdata">  
      </div>  
      <input type="hidden" value="1" name="counter" id="counter">  
      <input type="submit" value="submit">  
      <input type="reset" value="clear">  
 </form> 
  </body>  
 </html>  

in this above example i used the

$(document).ready(function()
{
   
    code
});
this above function of jQuery which is called after document will be load or after your document will be ready.
inside this i am writing following code.

k=1;   
$("#rdata").append(showData());

k-> variable i used for giving each row unique name.
rdata-> is an div id in which i need to add a row

append(showData())
this append method is used for append content at last in div(rdata).

showData() is an function which it will return the Dynamically generated row so that row i am passing as a parameter of append so its will append to rdata (div tag).
eg.append(showData()).

The ShowData function containt
str="<table><tr id='line"+k+"'>"
.....
return str;

here i used table and i am storing this table into the str variable because i need to return thats why and i assigning the unique row id
like  id='line"+k"'
so this will replace as line1 after u generated second row it will line2 as k variable will increase when you add the new row.


$("#add").live('click',function()
{
});
this function will invokes when user click on the add button
the live() is an method which is providing the fecilities for firing the on click(othere even) event on new generated add button if you will not used live then its add only one row.

Removing row
<input type='button' value='x' id='remove"+k+"' onclick='lremove(this)' src='Delete.png' height='30' width='30'/>


here when user click on remove button i am passing the 'this' object which is reffere the current row remove button object and in function
function lremove(l)
Now here  'this' is an object will replace with 'l' object name and get id from object.
var lid=l.id
now lid will store the id of remove button..e.g remove1,remove2..
var rowno = lid.match(/\d+$/);
this will extract last digits from the string.
e.g remove1 then its will return 1.

$("#line"+rowno).remove();
here line is common when you generating row its one row value containt line1,line2.
so line will same just i need to contacate the number of line and  remove() method is used for remove the specific tag.

How to Read values using jsp file ConnectRowGenerate.jsp when user click on submit button.
code.
 <%  
 int counter=Integer.parseInt(request.getParameter("counter"));  
 for(int i=1;i<=counter;i++)  
 {  
       try  
       {  
        String name=request.getParameter("name"+i);  
        String number=request.getParameter("number"+i);  
    out.println(name + " "+number+"<br>");  
   }  
   catch(Exception e)  
   {  
           continue;  
      }  
 }  
 %>  


Now we will understand above code
counter variable which containt thea number of row add in page.

try and catch block as if user will removed line from middle and we try to read that value which is not available then it will throw exception so for that i am writing code in try and catch block and if it will throw error then its will go in catch block and again its will continue reading with next row or line.

output:
when you open GenerateRow.html its will show like following.




if you click on add button it will add new row.

if you click on delete button it will remove row but here first row its not remove as i am gave validation so now when u click on submit its will call the ConnectRowGenerate.jsp file and its will display the data.
 
You can download above example from  here

Saturday, 27 April 2013

how to read an XML file via DOM XML parser in java

The XML is very simple language that allows the developers to store the structured data into XML files.XML is designed to transport and store data.

XML Document Example
In this tutorial, we will show you how to read an XML file via DOM XML parser. DOM parser parses the entire XML document and loads it into memory; then models it in a “TREE” structure for easy traversal or manipulation.
In short, it turns a XML file into DOM or Tree structure, and you have to traverse a node by node to get what you want.

e.g of your  personalinfo.xml file

 <?xml version="1.0"?>  
 <company>  
      <staff id="1">  
           <firstname>ishwar</firstname>  
           <lastname>Panjari</lastname>  
           <nickname>ish</nickname>  
           <salary>1000</salary>  
      </staff>  
      <staff id="2">  
           <firstname>jaydip</firstname>  
           <lastname>Raol</lastname>  
           <nickname>DK</nickname>  
           <salary>2000</salary>  
      </staff>  
 </company>  

when you create xml file you need to specify the version of xml file.  i created <company>---</company> this is called as root element of xml file.other its called node.eg. staff.

 import javax.xml.parsers.DocumentBuilderFactory;  
 import javax.xml.parsers.DocumentBuilder;  
 import org.w3c.dom.Document;  
 import org.w3c.dom.NodeList;  
 import org.w3c.dom.Node;  
 import org.w3c.dom.Element;  
 import java.io.File;  
 public class ReadXMLFile {  
  public static void main(String argv[]) {  
   try {  
      File fXmlFile = new File("personalInfo.xml");//personalInfo.xml is xml file name  
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();  
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();  
      Document doc = dBuilder.parse(fXmlFile);  
      System.out.println("Root element :" + doc.getDocumentElement().getNodeName());  
      NodeList nList = doc.getElementsByTagName("emp");//here emp is the tag in xml file  
      System.out.println("----------------------------");  
      for (int temp = 0; temp < nList.getLength(); temp++) {  
           Node nNode = nList.item(temp);  
           System.out.println("\nCurrent Element :" + nNode.getNodeName());  
           if (nNode.getNodeType() == Node.ELEMENT_NODE) {  
                Element eElement = (Element) nNode;  
                System.out.println("Staff id : " + eElement.getAttribute("id"));  
                System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());  
                System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());  
                System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());  
                System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());  
           }  
      }  
   } catch (Exception e) {  
      e.printStackTrace();  
   }  
  }  
 }  

here we used the classes
DocumentBuilderFactory:Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.

DocumentBuilder:Defines the API to obtain DOM Document instances from an XML document. Using this class, an application programmer can obtain a Document from XML.

An instance of this class can be obtained from the DocumentBuilderFactory.newDocumentBuilder() method. Once an instance of this class is obtained, XML can be parsed from a variety of input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources.


output:

Root element :company
----------------------------
Current Element :emp
Staff id : 1
First Name : ishwar
Last Name : Panjari
Nick Name : ish
Salary : 1000

Current Element :emp
Staff id : 2
First Name : jaydip
Last Name : Raol
Nick Name : DK
Salary : 2000

Friday, 5 April 2013

How to read Multiple checkbox value and Radio button value at client side and serverside using jsp


Html file

 <html>  
 <head>  
 <title>Check Box Example</title>  
 <script src="jquery.js"></script>  
 <script>  
 function checkdisp()  
 {  
       $('input[name="hobby"]:checked').each(function()  
       {  
      alert("Check Button Value:"+$(this).val());  
    });  
      alert("The Radio Button Value:"+$('input[name="gen"]:checked').val());  
 }  
 </script>  
 </head>  
 <body>  
 <form name="frmpdf" action="connectCheck.jsp" method="GET">  
 Hobbies:<br>  
            <input type="checkbox" name="hobby" value="Cricket">Cricket<br>  
            <input type="checkbox" name="hobby" value="Movie">Watching Movie<br>  
            <input type="checkbox" name="hobby" value="Book">Reading Book<br>  
            <br>  
 Gender:<input type="radio" value="Male" name="gen" Checked>Male  
           <input type="radio" value="Female" name="gen">Female  
           <br>  
            <input type="button" value="ClientSide" onclick="checkdisp()">  
            <input type="submit" value="ServerSide">  
 </form>  
 </body>  
 </html>  


jsp file
connectCheck.jsp
 <%  
      out.println("CheckBox Value");  
      String[] checkb=request.getParameterValues("hobby");  
      try  
      {  
           for(int i=0;i<checkb.length;i++)  
                out.println(checkb[i]);  
           out.println("Radio Button value");  
           String radiob=request.getParameter("gen");  
           out.println(radiob);  
      }  
      catch(Exception e)  
      {  
           out.println("erro "+e.toString());  
      }  
 %>  

Client side : when you click on clientSide button it will display value of selected Checkbox and Radio button in Html File using jquery.

Server side:after selecting value in html page when you click on servierSide button it  will got to connectCheck.jsp page that print the selected checkbox and Radio button value.
           i used try and catch block because if user is not selected checkbox value and you try to access then its will throw error so handling exceptin i used try and catch block.

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>