Wednesday 3 April 2013

File handling though BufferedReader, Bufferwriter Class in java

package com.scannerclass;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class IoEditFileEample {

    public static void main(String[] args) throws IOException {

        File f=new File("E:/Temp/appendOldFile.txt");
        if (!f.exists()) {
   f.createNewFile();
  }
        
        FileInputStream fs = null;
        InputStreamReader in = null;
        BufferedReader br = null;

        StringBuffer sb = new StringBuffer();

        String textinLine;
      
        
        try {
             fs = new FileInputStream(f);
             in = new InputStreamReader(fs);
             br = new BufferedReader(in);

            while(true)
            {
                textinLine=br.readLine();
                if(textinLine==null)
                    break;
                sb.append(textinLine);
            }
              String textToEdit1 = "";
              int cnt1 = sb.indexOf(textToEdit1);
              sb.replace(cnt1,cnt1+textToEdit1.length(),"New Append text");

              String textToEdit2 = "";
              int cnt2 = sb.indexOf(textToEdit2);
              sb.replace(cnt2,cnt2+textToEdit2.length(),"Second new edit text");

              fs.close();
              in.close();
              br.close();

            } catch (FileNotFoundException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            }
            catch (Exception e) {
                e.printStackTrace();
              }

            try{
                FileWriter fstream = new FileWriter(f);
                BufferedWriter outobj = new BufferedWriter(fstream);
                outobj.write(sb.toString());
                outobj.close();

            }catch (Exception e){
              System.err.println("Error: " + e.getMessage());
            }
    }
}

In ArrayList setdata getdata Example in java

//---- You can use this example to understand how to set and get data in java --- //

package aman.sort;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Run {

/**
 * @param args
 */
public static void main(String[] args) {

List dataBean = new ArrayList();
try {
String ch;
do{
DataBean bean = new DataBean();
ch="";
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the User :");
    String name = br.readLine();
    bean.setName(name);
    System.out.println("Enter the Id :");
    int id = (Integer.parseInt(br.readLine()));
    bean.setId(id);
    dataBean.add(bean);
    System.out.println("Press 'y' for input again data... ");
    ch = br.readLine();
}while((ch.equals("y"))||ch.equals("Y"));
}
catch(Exception e) {
System.out.println("Error occured due to input invalid data..."+e);
}
for(Object obj: dataBean) {
DataBean getbean  = (DataBean)obj;
System.out.println("name is :"+getbean.getName()+"Id is:"+getbean.getId());
}

}

}


//=================================================

package aman.sort;

public class DataBean {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Simple HTML form with jquery validation

<html>
 <center>
     <a target ="_blank" href ="http://ramsis-code.blogspot.in">Aman Kumar's Blog</a><br>
<a target ="_blank" href ="http://ramsis-code.blogspot.in">Use latest code</a>
 </center>
<head>

<script src="jquery-1.8.3.js"> </script>
<script type="text/javascript">
   
$(document).ready(function() {
function Reset(){
alert("hello");
$("#uname").val('');
$("#lname").val('');
$("#phone").val('');
$("#mdata").val('');
$("#emailid").val('');
$("#datepicker").val('');
$("#address").val('');
$("#city").val('');
 $("#lblmsg").html('');
}
//$("#uname").live('blur', function() {
//var checklength = $(this).val().length;
// if(checklength === 0)
// {
    // $("#uname").css('border-color','red');
// }
// else
// {
// $("#uname").css('border-color','');
// }
// });
$("#btnsubmit").click(function () {
if ($("#uname").val().length === 0) {
                    $("#lblmsg").text('Please enter the Name.');
                    $("#uname").focus();
//$("#uname").css('border-color','red');
                    return false;
                } 
else if($("#lname").val().length === 0){
      $("#lblmsg").text('Please enter the Last Name.');
                                       $("#lname").focus();
  return false;
}
else if($("#phone").val().length === 0){
      $("#lblmsg").text('Please enter the Phone.');
  return false;
}
else if($("#mdata").val().length === 0){
      $("#lblmsg").text('Please enter the date.');
  return false;
}
else if($("#emailid").val().length === 0){
      $("#lblmsg").text('Please enter the email id.');
  return false;
}
else if($("#datepicker").val().length === 0){
      $("#lblmsg").text('Please enter the date.');
  return false;
}
else if($("#address").val().length === 0){
      $("#lblmsg").text('Please enter the address.');
  return false;
}
else if($("#city").val().length === 0){
      $("#lblmsg").text('Please enter the city.');
  return false;
}
        });
});
    </script>
</head>

<body>
<table width="100%">
  <tbody>
    
<tr>
  <td colspan="2"></td>
</tr>
<tr>
  <td width="20%">
 
  </td> 
  <td width="80%">
     <form action="" method="POST">     
    <table width="100%" align="center">    
<tbody>  
<tr><td width="10%">User Name </td><td width="70%"><input type="text" name="uname" id="uname"/> </td></tr>
<tr><td width="10%">Last Name</td> <td width="70%"><input type="text" name="lname" id="lname"/></td></tr>
<tr><td width="10%">Phone Number </td> <td width="70%"><input type="text" value="+91 "  name="phone" id="phone" /></td></tr>
<tr><td width="10%">Data </td> <td width="70%"><input type="text" name="mdate" id="mdata"/></td></tr>
<tr><td width="10%">Email Id </td> <td width="70%"><input type="text" name="emailid" id="emailid"/></td></tr>

<tr><td width="10%">Date</td><td width="70%"><input   type="text" name="crdate" id="datepicker" /></td></tr>
<tr><td width="10%">Address</td> <td width="70%"><input type="text" name="address" id="address"/></td></tr>
<tr><td width="10%">City</td> <td width="70%"><input type="text" name="city" id="city"/></td></tr>
<tr> <td>&nbsp;</td><td  align="left" ><input class ="" type="submit" name="submit" value="Submit" style="margin-left:5px;" id="btnsubmit"/>
<input class ="" type="reset" name="" value="Reset" id="btnreset" style="margin-left:5px;"/></td></tr>
<tr>
<td width="10%"></td><td colspan ="1">
<label id ="lblmsg" style="color:Red;"></label>
</td>
</tr>
</tbody>  
    </table> 
  </form>
  </td>
</tr>
<tr>
  <td colspan="2"></td>
</tr>
 </tbody> 
</table>
</body>
</html>

Tuesday 2 April 2013

Ajax Call onkeyup Event in jsp

// ----------  Save as index.jsp --------------------- //

<%@ page import="java.util.*" %>
<%@ page import="java.sql.*"  %>
<%@ page import="java.io.*" %>
<%@ page import="java.text.*"  %>

<% 
  Connection con = null;
  ResultSet rs = null;
  Statement stmt = null;
  
  Class.forName("net.sourceforge.jtds.jdbc.Driver");
  con = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.7.128:1433/amantrn","sa","abcd");
  stmt = con.createStatement();
%>

<%-- <% --%>
<!--   String Query1="SELECT [id],[username],[password],[email],[profile] FROM [admin]"; -->
<!--   stmt = con.createStatement(); -->
<!--   ResultSet rs1 = stmt.executeQuery(Query1); -->
  
<!-- %> -->

<script language="javascript" type="text/javascript">
var xmlHttp;
function modifyData(Str) {
var versionIds = [ "Msxml2.XMLHTTP", "Microsoft.XMLHTTP",
"Microsoft.XMLDOM", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0",
"Msxml2.XMLHTTP.4.0", "Msxml2.XMLHTTP.3.0",
"Msxml2.XMLHTTP.2.6", "Microsoft.XMLHTTP.1.0",
"Microsoft.XMLHTTP.1" ];
if (typeof XMLHttpRequest != "undefined") {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
for ( var i = 0; i < versionIds.length; i++) {
try {

return new ActiveXObject(versionIds[i]);

} catch (e) {
alert("Browser does not support XMLHTTP Request");
}
}
new XDomainRequest();
}
if (xmlHttp == null) {
alert("Browser does not support XMLHTTP Request");
return;
}
var url = "modify.jsp?";
url += "id=" + Str;
url += "&sid=" + Math.random();
xmlHttp.onreadystatechange = stateChange;
xmlHttp.open("POST", url, true);
xmlHttp.send(null);
function stateChange() {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
var abc = xmlHttp.responseText.split("~");
//alert(abc);
document.getElementById('id').value = abc[0];//id
document.getElementById('name').value = abc[1];//Username
document.getElementById('pass').value = abc[2];//Password
document.getElementById('email').value = abc[3];//Email
//document.getElementById("id").value = abc[4];//Profile
}
}
}

</script>

<table>
  <tr>
   <td>Id:</td>
     <td><input type="text" name="id" id="id" value="" onblur='modifyData(this.value);'/></td>
  </tr>
    <tr>
   <td>Name:</td> 
    <td><input type="text" name="name" id="name" value=""/></td>
  </tr>
   <tr>
   <td>Password:</td>
   <td><input type="password" name="pass" id="pass" value="" /></td>
  </tr>
   <tr>
   <td>Email:</td>
   <td><input type="text" name="email" id="email" value="" /></td>
  </tr>
  <tr>
  <td><input type="reset" value="Clear"></td>
  <td></td>
  </tr>

</table>


// ---------------- Save as  modify.jsp ----------------- //



<%@ page import="java.util.*" %>
<%@ page import="java.sql.*"  %>
<%@ page import="java.io.*" %>
<%@ page import="java.text.*"  %>

<% 
  Connection con = null;
  ResultSet rs = null;
  Statement stmt = null;
  
  Class.forName("net.sourceforge.jtds.jdbc.Driver");
  con = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.7.128:1433/amantrn","sa","abcd");
  stmt = con.createStatement();
%>

<%
  String id = request.getParameter("id").trim();

  String Query1="SELECT [id],[username],[password],[email],[profile] FROM [admin] where id like '"+id+"%' ";
  stmt = con.createStatement();
  ResultSet rs1 = stmt.executeQuery(Query1);
  while(rs1.next()){
%>

<%=rs1.getString("id").trim()%>~<%=rs1.getString("username")%>~<%=rs1.getString("password")%>~<%=rs1.getString("email")%>~
<% }%>

Div hide using Jquery


<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            #divid {
          background: Red;
          padding: 20px 20px 20px;
          position: relative;
          border-top: solid 2px #000000;
          }
         #divid #deleteid {
         position: absolute;
          top: 20px;
          right: 20px;
          cursor: pointer;
          }
        </style> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js">
        <script src="jquery-1.8.2.js"></script> 
        <script type="text/javascript">
        $(document).ready(function(){
            $('#chkno').click(function() {
               
               // $('#divid').slideUp ('slow');
                //$("#divid").animate({ opacity: 'hide' }, "slow");
                $("#divid").fadeOut('medium');
            })
     $('#chkyes').click(function() {
        // $('#divid').slideDown('slow');
         $("#divid").fadeIn('medium');
            })
        });
        
       
      </script>
    </head>
    <body>
        <form> 
         <input type="radio" id ="chkyes" name="radio" value="yes"   /> yes<br />
         <input type="radio" id ="chkno" name="radio" value="no"   /> no  
         <div id="divid">
         <h3>If you click yes. 'Div' will show</h3>
         <H3>if you click no. then 'Div' will hide </H3>
        </div>
        </form>
    </body>
</html>

Constructor Calling in java


// ----------- Constructor Calling in java --------------//


class Acun{
Acun(){
System.out.println("Super Class Constructor is print...");
}
}
class Bcun extends Acun{
Bcun(){
System.out.println("B sub class constructor is print...");
}
}
class Ccun extends Bcun{
Ccun(){
System.out.println("C sub class constructor is print...");
}
}

class Constructor_Call {
public static void main(String args[]){
  Ccun c = new Ccun();
  // new Ccun();
}
}

//---------------------------------------
Answer is:

Super Class Constructor is print...
B sub class constructor is print...
C sub class constructor is print...

Use of Comparator class for sorting ArrayList Objects

// ---------- Use of Comparator class for sorting ArrayList ------------ //

import java.util.*;

public class SortByComparator {
  Integer empcode;
  String name;
public SortByComparator(){
empcode = 1001;
name = "chetan";
}
public SortByComparator(int empcode, String name ){
this.empcode = empcode;
this.name = name;
}
public String toString(){
return "Emp code is:"+empcode+"Emp name is:"+name;
}
}

class  SortByName implements Comparator <SortByComparator>{
      public int compare(SortByComparator o1, SortByComparator o2){
      return o1.name.compareToIgnoreCase(o2.name);
      }
}
class SortByEmpCode implements Comparator <SortByComparator>{
public int compare(SortByComparator o1, SortByComparator o2){
return o1.empcode.compareTo(o2.empcode);
}
}

class SortRun{
public static void main(String args[]){
List <SortByComparator> l = new ArrayList <SortByComparator>();
l.add(new SortByComparator());
l.add(new SortByComparator(9002,"Brijaes"));
l.add(new SortByComparator(2004,"kapil"));
l.add(new SortByComparator(1005,"Aman Kumar"));
l.add(new SortByComparator(2001,"suraj"));
System.out.println("\nBefore Sorting:"+l);
Collections.sort(l, new SortByName());
//Collections.sort(l, new SortByEmpCode());
System.out.println("\nAfter sorting:"+l);
}
}

// Sorting of Srting and Integer Arraylist use of Comparator Interface 

package TestCollection;
import java.util.*;

public class Sample1 {

public static void main(String args[]){

List <Integer> list = new ArrayList <Integer>();
list.add(10);
list.add(200);
list.add(50);
list.add(26);
list.add(15);
list.add(80);
list.add(40);
list.add(30); 

List <String> list1 = new ArrayList <String> ();

list1.add("Deepak");
list1.add("manoj");
list1.add("Aman");
list1.add("vijay");
list1.add("Brijesh");
list1.add("Amit");
list1.add("chetan");

Collections.sort(list,new MyIntComparable());
for(Integer integer : list){
System.out.println(integer);


Collections.sort(list1, new MyStringComparable());
for(String string : list1){
System.out.println(string);
}
}
}

class MyIntComparable implements Comparator <Integer>{

public int compare(Integer o1, Integer o2){

return (o1<o2 ? -1 : (o1==o2 ? 0 : 1));

}
class MyStringComparable implements Comparator <String>{
public int compare(String s1, String s2){
return s1.compareToIgnoreCase(s2);
//return (s1<s2 ? -1 : (s1==s2 ? 0 : 1));

}