Monday, March 30, 2009

Java : Sorting User Objects using Comparable / Comparator in Ascending or Descending order

Comparable



java.lang.Comparable

  • int objOne.compareTo(objTwo)

  • Returns
    negative if objOne < objTwo
    zero if objOne == objTwo
    positive if objOne > objTwo

  • You must modify the class whose
    instances you want to sort.

  • Only one sort sequence can be created

  • Implemented frequently in the API by:
    String, Wrapper classes, Date, Calendar...



//Complete code for SortingObject.java using Comparable


import java.util.*;

class Employee implements Comparable<Employee>//using Comparable
{
private Integer empId;
private String name;

Employee(Integer empId,String name)
{
this.empId=empId;
this.name=name;
}

public String toString()
{
return "ID: "+empId+" Name: "+name+"\n";
}

public int compareTo(Employee e)
{

return empId.compareTo(e.empId);//Sorting in Ascending order of empId
//return e.empId.compareTo(empId);//Sorting in Descending order of empId
//return name.compareTo(e.name);//Sorting in Ascending order of name
//return e.name.compareTo(name);//Sorting in Descending order of name


}
}

public class SortingObject
{
public static void main(String[] args)
{
ArrayList<Employee> employeeArray=new ArrayList<Employee>();

employeeArray.add(new Employee(11,"Ram"));
employeeArray.add(new Employee(44,"Amol"));
employeeArray.add(new Employee(9,"Kanchan"));
employeeArray.add(new Employee(22,"Madan"));
employeeArray.add(new Employee(13,"Ashwini"));

System.out.println("Before Sorting.....");
System.out.println(employeeArray);

Collections.sort(employeeArray);

System.out.println("After Sorting.....");
System.out.println(employeeArray);
}
}//end



Comparator



java.util.Comparator

  • int compare(objOne, objTwo)

  • Returns
    negative if objOne < objTwo
    zero if objOne == objTwo
    positive if objOne > objTwo

  • You build a class separate from the class whose instances you
    want to sort.

  • Many sort sequences can be created

  • Meant to be implemented to sort instances of third-party
    classes.




//Complete code for SortingObject.java using Comparator


import java.util.*;

class Employee
{
private Integer empId;
private String name;

Employee(Integer empId,String name)
{
this.empId=empId;
this.name=name;
}

public String getName()
{
return name;
}

public Integer getEmpId()
{
return empId;
}

public String toString()
{
return "ID: "+empId+" Name: "+name+"\n";
}
}

class EmployeeComparator implements Comparator<Employee>//using Comparator
{
public int compare(Employee a,Employee b)
{
return a.getEmpId().compareTo(b.getEmpId());//Sorting in Ascending order of empId
//return b.getEmpId().compareTo(a.getEmpId());//Sorting in Descending order of empId
//return a.getName().compareTo(b.getName());//Sorting in Ascending order of name
//return b.getName().compareTo(a.getName());//Sorting in Descending order of name
}
}

public class SortingObject
{
public static void main(String[] args)
{
ArrayList<Employee> employeeArray=new ArrayList<Employee>();

employeeArray.add(new Employee(11,"Ram"));
employeeArray.add(new Employee(44,"Amol"));
employeeArray.add(new Employee(9,"Kanchan"));
employeeArray.add(new Employee(22,"Madan"));
employeeArray.add(new Employee(13,"Ashwini"));

System.out.println("Before Sorting.....");
System.out.println(employeeArray);

EmployeeComparator empComp = new EmployeeComparator();

Collections.sort(employeeArray,empComp);

System.out.println("After Sorting.....");
System.out.println(employeeArray);
}
}//end

Java : Simple Example of PreparedStatement

Prepared statements are the ability to set up a statement once, and then execute it many times with different parameters. They are designed to replace building ad hoc query strings, and do so in a more secure and efficient manner. A typical prepared statement would look something like:

SELECT * FROM Employee WHERE emp_id = ?

The '?' is what is a called a placeholder. When you execute the above query, you would need to supply the value for it, which would replace the '?' in the query bove.

Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency.

//code for PreparedStatementDemo.java

import java.sql.*;
public class PreparedStatementDemo
{
public static void main(String[] args) throws Exception
{
Connection con;

PreparedStatement ps;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Loading Drivers

con=DriverManager.getConnection("jdbc:odbc:oracledsn","scott","tiger");//Making Connection

ps=con.prepareStatement("SELECT * FROM Employee where emp_id=?");//this is prepare statement
//observe the '?'

ps.setInt(1,11);//we can also use setString("String"); for checking String

ResultSet rset=ps.executeQuery();//Execute the Prepared Statement

while(rset.next())//Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}

ps.close();//Closeing Connection and PreparedStatement
con.close();
}
}

Java : Calling a Stored Procedure in a Database

Simple program for calling a stored procedure in a oracle database

In this example we are using both IN and OUT parameters, Simply passing two IN parameters and getting Addition as OUT parameter ie a = b + c.

//Here is complete tested code for Procedure.java

import java.sql.*;
public class Procedure
{
public static void main(String[] args) throws Exception
{
Connection con;

CallableStatement cs;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers

con=DriverManager.getConnection("jdbc:odbc:oracledsn","scott","tiger");//Step 2: Making Connection

cs=con.prepareCall("{call AddNumbers(?,?,?)}");//Calling procedure

cs.registerOutParameter(1,Types.INTEGER);//Registering 1st parameter
// Register the type of the OUT parameter

//2nd parameter
cs.setInt(2,15);//here values can also be taken as command line argument

//3rd parameter
cs.setInt(3,20);

// Execute the stored procedure and retrieve the OUT value
cs.execute();

System.out.println(cs.getInt(1));//output as 35 ie 15+20
}
}
//end




This is How Procedure is created in oracle


create or replace procedure AddNumbers(a out number, b in number, c in number)
as
begin
a:=b+c;
end AddNumbers;

Java : Java Database Connectivity (JDBC), Explained All four types with simple example

There are four types of JDBC drivers explained with simple examples using oracle database:

Type 1 : JDBC-ODBC bridge plus ODBC driver.

This driver translates JDBC method calls into ODBC function calls.
The Bridge implements Jdbc for any database for which an Odbc driver is available.

/********Code for Type1.java**********/

import java.sql.*;
public class Type1
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers

con=DriverManager.getConnection("jdbc:odbc:madan","scott","tiger");//Step 2: Making Connection

stat=con.createStatement();//Step 3: Creating JDBC Statement

String query = "SELECT * FROM Employee";

ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement

while(rset.next())//Step 5: Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}

Type 2 : Native-API, partly Java driver.

Type 2 drivers use the Java Native Interface (JNI) to make calls to a local
database library API. This driver converts the JDBC calls into a database
specific call for databases such as SQL, ORACLE etc.

Note : to set path

set Classpath=%Classpath%;.;D:\oracle\ora92\jdbc\lib\Classes12.jar

/********Code for Type2.java**********/

import java.sql.*;
public class Type2
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers

con=DriverManager.getConnection("jdbc:oracle:oci8:@madan","scott","tiger");//Step 2: Making Connection

stat=con.createStatement();//Step 3: Creating JDBC Statement

String query = "SELECT * FROM Employee";

ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement

while(rset.next())//Step 5: Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}

Type 3 : JDBC-Net, pure Java driver.

Type 3 drivers are pure Java drivers that uses a proprietary network protocol to
communicate with JDBC middleware on the server.Its requests are passed through the
network to the middle-tier server. The middle-tier then translates the request to the
database. The middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.

Type 4 : Native-protocol, pure Java driver.


Type 4 drivers communicates directly with the database engine rather than through
middleware or a native library, they are usually the fastest JDBC drivers available.
This driver directly converts the java statements to SQL statements.

Note : to set path

set Classpath=%Classpath%;.;D:\oracle\ora92\jdbc\lib\Classes111.jar

/********Code for Type4.java**********/


import java.sql.*;
public class Type4
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers

con=DriverManager.getConnection("jdbc:oracle:thin:@madan:1521:oracle9","scott","tiger");//Step 2: Making Connection

stat=con.createStatement();//Step 3: Creating JDBC Statement

String query = "SELECT * FROM Employee";

ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement

while(rset.next())//Step 5: Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}

Monday, March 16, 2009

java : Simple java program to read mails from your gmail account

Connecting GMail using POP3 connection with SSL

POP (Post Office Protocol 3)
This protocol defines a single mailbox for a single user and a standardized way for users to access mailboxes and download messages to their computer.


To run this code u need to download Java Mail API and JavaBeans Activation Framework


/*Here is the complete tested code for ReadGmailAccount.java*/


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

public class ReadGmailAccount
{
public static void main(String[] args)
{
Properties props = System.getProperties();

props.put("mail.pop3.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");
props.setProperty("mail.pop3.port", "995");
props.setProperty("mail.pop3.socketFactory.port", "995");

Session session = Session.getDefaultInstance(props,null);

URLName urln = new URLName("pop3","pop.gmail.com",995,null,"madan712@gmail.com","*******");//password


try
{
Store store = session.getStore(urln);

store.connect();

Folder folder = store.getFolder("INBOX");

folder.open(Folder.READ_ONLY);

Message[] message = folder.getMessages();

for (int i = 0; i < message.length; i++)
{

System.out.println("------------ Message " + (i + 1) + " ------------");

System.out.println("Subject : " + message[i].getSubject());
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);

System.out.print("Message : ");

InputStream stream = message[i].getInputStream();
while (stream.available() != 0)
{
System.out.print((char) stream.read());
}
}

folder.close(true);
store.close();
}
catch (Exception ex)
{
System.out.println("Exception occured"+ex);
ex.printStackTrace();
}
}
}

Java : Simple java program to Send Email from Gmail with attachments using JavaMail API

Java offers an API called Java Mail API from where we can send emails from java program. This article describes how we can send email (Gmail) with attachments using Java.

To send message with attachment we need to create an email with javax.mail.Multipart
object which basically will contains the email text message and then add a file to the second block, which both of them is an object of avax.mail.internet.MimeBodyPart.
In this example we also use the javax.activation.FileDataSource.


To run this code u need to download Java Mail API and JavaBeans Activation Framework





/*Here is the complete tested code for SendMailGmail.java*/


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

public class SendMailGmail
{
public static void main(String[] args)
{
Properties props = new Properties();
props.put("mail.smtp.user","madan712@gmail.com");

props.put("mail.smtp.host","smtp.gmail.com");

props.put("mail.smtp.port","465");

props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.debug","false");

props.put("mail.smtp.socketFactory.port","465");

props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");

try
{
Session session = Session.getDefaultInstance(props,null);
session.setDebug(true);

MimeMessage msg = new MimeMessage(session);
msg.setSubject("Java Mail");

Multipart multipart = new MimeMultipart();

MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("This Mail is send through Java API");

MimeBodyPart filePart = new MimeBodyPart();

FileDataSource fds = new FileDataSource("TextFile.txt");//file to attach
filePart.setDataHandler(new DataHandler(fds));
filePart.setFileName(fds.getName());

multipart.addBodyPart(textPart);
multipart.addBodyPart(filePart);

msg.setContent(multipart);

msg.setFrom(new InternetAddress("madan712@gmail.com"));

msg.addRecipient(Message.RecipientType.TO, new InternetAddress("madan@indiagames.com"));

msg.addRecipient(Message.RecipientType.CC, new InternetAddress("madan_chaudhary@rediffmail.com"));

msg.saveChanges();

Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com","madan712@gmail.com","******");//password

transport.sendMessage(msg, msg.getAllRecipients());

transport.close();

}
catch (Exception ex)
{
System.out.println("Exception occured"+ex);
ex.printStackTrace();
}
}
}

Friday, March 6, 2009

Javascript : Simple Autocomplete Textarea or Textbox

Creating an Simple Autosuggest Textbox with JavaScript

Creating a Textbox with JavaScript Auto-Complete feature (similar to google search when typing few key stroke it gives auto sugession).
Here is the complete code for Auto suggest Textbox, Auto fill Textbox Example using Javascript, HTML and CSS.

Auto Complete script displays a dropdown wordlist and select a word to complete a textbox entry.

You can use it in Textarea or Textbox according to your requirement. It supports multiple words one after other using key stroke or mouse control. I have put all code in a single file however you can split the javascript according to your requirement.

Please Note : This is open source code available on internet, you can customize it according to your requirement.

/*Here is the complete code*/


<html>
 <head>
  <title> Simple Auto Complete Drop Down </title>
  <script language="javascript">
    // List of words to show in drop down
    var customarray = new Array("bank", "back", "priya","hindu","mandar", "madan","nik","cat",
                                "kind","fight","argue","append","run","sad","silk","light",
                                "little","rate","orange","office","lucky","cable","monitor",
                                "narration","early","pick","put","hungry","gain","gift","java",
                                "junction","vegtable","fan","north","needle","winter","nation",
                                "carry","dance","danger","iteration","facile","yahoo","quick",
                                "quee","arrangement","vechicle","urban","xerox","zeebra","xML",
                                "sundeep","sun","priyanka","leo","Rahul","Sita","Geeta","Amol");

    //****************************************************************************
    function actb(obj,ca){
    /* ---- Public Variables ---- */
    this.saec_timeOut = -1; // Autocomplete Timeout in ms (-1: autocomplete never time out)
    this.saec_lim = 4;    // Number of elements autocomplete can show (-1: no limit)
    this.saec_firstText = false; // should the auto complete be limited to the beginning of keyword?
    this.saec_mouse = true; // Enable Mouse Support
    this.saec_delimiter = new Array(';',' ');  // Delimiter for multiple autocomplete. Set it to empty array for single autocomplete
    this.saec_startcheck = 1; // Show widget only after this number of characters is typed in.
    /* ---- Public Variables ---- */
   
    //Customize style according to your requirement
    /* --- Styles --- */
    this.saec_bgColor = '#999999';
    this.saec_textColor = '#ffffff';
    this.saec_hColor = '#000000';
    this.saec_fFamily = 'verdana';
    this.saec_fSize = '15px';
    this.saec_hStyle = 'text-decoration:underline;font-weight:bold';
    /* --- Styles --- */

    /* ---- Private Variables ---- */
    var saec_delimwords = new Array();
    var saec_cdelimword = 0;
    var saec_delimchar = new Array();
    var saec_display = false;
    var saec_pos = 0;
    var saec_total = 0;
    var saec_curr = null;
    var saec_rangeu = 0;
    var saec_ranged = 0;
    var saec_bool = new Array();
    var saec_pre = 0;
    var saec_toid;
    var saec_tomake = false;
    var saec_getpre = "";
    var saec_mouse_on_list = 1;
    var saec_kwcount = 0;
    var saec_caretmove = false;
    this.saec_keywords = new Array();
    /* ---- Private Variables---- */
   
    this.saec_keywords = ca;
    var saec_self = this;

    saec_curr = obj;
   
    addEvent(saec_curr,"focus",saec_setup);
    function saec_setup(){
        addEvent(document,"keydown",saec_checkkey);
        addEvent(saec_curr,"blur",saec_clear);
        addEvent(document,"keypress",saec_keypress);
    }

    function saec_clear(evt){
        if (!evt) evt = event;
        removeEvent(document,"keydown",saec_checkkey);
        removeEvent(saec_curr,"blur",saec_clear);
        removeEvent(document,"keypress",saec_keypress);
        saec_removedisp();
    }
    function saec_parse(n){
        if (saec_self.saec_delimiter.length > 0){
            var t = saec_delimwords[saec_cdelimword].trim().addslashes();
            var plen = saec_delimwords[saec_cdelimword].trim().length;
        }else{
            var t = saec_curr.value.addslashes();
            var plen = saec_curr.value.length;
        }
        var tobuild = '';
        var i;

        if (saec_self.saec_firstText){
            var re = new RegExp("^" + t, "i");
        }else{
            var re = new RegExp(t, "i");
        }
        var p = n.search(re);
               
        for (i=0;i<p;i++){
            tobuild += n.substr(i,1);
        }
        tobuild += "<font style='"+(saec_self.saec_hStyle)+"'>"
        for (i=p;i<plen+p;i++){
            tobuild += n.substr(i,1);
        }
        tobuild += "</font>";
            for (i=plen+p;i<n.length;i++){
            tobuild += n.substr(i,1);
        }
        return tobuild;
    }
    function saec_generate(){
        if (document.getElementById('tat_table')){ saec_display = false;document.body.removeChild(document.getElementById('tat_table')); }
        if (saec_kwcount == 0){
            saec_display = false;
            return;
        }
        a = document.createElement('table');
        a.cellSpacing='1px';
        a.cellPadding='2px';
        a.style.position='absolute';
        a.style.top = eval(curTop(saec_curr) + saec_curr.offsetHeight) + "px";
        a.style.left = curLeft(saec_curr) + "px";
        a.style.backgroundColor=saec_self.saec_bgColor;
        a.id = 'tat_table';
        document.body.appendChild(a);
        var i;
        var first = true;
        var j = 1;
        if (saec_self.saec_mouse){
            a.onmouseout = saec_table_unfocus;
            a.onmouseover = saec_table_focus;
        }
        var counter = 0;
        for (i=0;i<saec_self.saec_keywords.length;i++){
            if (saec_bool[i]){
                counter++;
                r = a.insertRow(-1);
                if (first && !saec_tomake){
                    r.style.backgroundColor = saec_self.saec_hColor;
                    first = false;
                    saec_pos = counter;
                }else if(saec_pre == i){
                    r.style.backgroundColor = saec_self.saec_hColor;
                    first = false;
                    saec_pos = counter;
                }else{
                    r.style.backgroundColor = saec_self.saec_bgColor;
                }
                r.id = 'tat_tr'+(j);
                c = r.insertCell(-1);
                c.style.color = saec_self.saec_textColor;
                c.style.fontFamily = saec_self.saec_fFamily;
                c.style.fontSize = saec_self.saec_fSize;
                c.innerHTML = saec_parse(saec_self.saec_keywords[i]);
                c.id = 'tat_td'+(j);
                c.setAttribute('pos',j);
                if (saec_self.saec_mouse){
                    c.style.cursor = 'pointer';
                    c.onclick=saec_mouseclick;
                    c.onmouseover = saec_table_highlight;
                }
                j++;
            }
            if (j - 1 == saec_self.saec_lim && j < saec_total){
                r = a.insertRow(-1);
                r.style.backgroundColor = saec_self.saec_bgColor;
                c = r.insertCell(-1);
                c.style.color = saec_self.saec_textColor;
                c.style.fontFamily = 'arial narrow';
                c.style.fontSize = saec_self.saec_fSize;
                c.align='center';
                replaceHTML(c,'\\/');
                if (saec_self.saec_mouse){
                    c.style.cursor = 'pointer';
                    c.onclick = saec_mouse_down;
                }
                break;
            }
        }
        saec_rangeu = 1;
        saec_ranged = j-1;
        saec_display = true;
        if (saec_pos <= 0) saec_pos = 1;
    }
    function saec_remake(){
        document.body.removeChild(document.getElementById('tat_table'));
        a = document.createElement('table');
        a.cellSpacing='1px';
        a.cellPadding='2px';
        a.style.position='absolute';
        a.style.top = eval(curTop(saec_curr) + saec_curr.offsetHeight) + "px";
        a.style.left = curLeft(saec_curr) + "px";
        a.style.backgroundColor=saec_self.saec_bgColor;
        a.id = 'tat_table';
        if (saec_self.saec_mouse){
            a.onmouseout= saec_table_unfocus;
            a.onmouseover=saec_table_focus;
        }
        document.body.appendChild(a);
        var i;
        var first = true;
        var j = 1;
        if (saec_rangeu > 1){
            r = a.insertRow(-1);
            r.style.backgroundColor = saec_self.saec_bgColor;
            c = r.insertCell(-1);
            c.style.color = saec_self.saec_textColor;
            c.style.fontFamily = 'arial narrow';
            c.style.fontSize = saec_self.saec_fSize;
            c.align='center';
            replaceHTML(c,'/\\');
            if (saec_self.saec_mouse){
                c.style.cursor = 'pointer';
                c.onclick = saec_mouse_up;
            }
        }
        for (i=0;i<saec_self.saec_keywords.length;i++){
            if (saec_bool[i]){
                if (j >= saec_rangeu && j <= saec_ranged){
                    r = a.insertRow(-1);
                    r.style.backgroundColor = saec_self.saec_bgColor;
                    r.id = 'tat_tr'+(j);
                    c = r.insertCell(-1);
                    c.style.color = saec_self.saec_textColor;
                    c.style.fontFamily = saec_self.saec_fFamily;
                    c.style.fontSize = saec_self.saec_fSize;
                    c.innerHTML = saec_parse(saec_self.saec_keywords[i]);
                    c.id = 'tat_td'+(j);
                    c.setAttribute('pos',j);
                    if (saec_self.saec_mouse){
                        c.style.cursor = 'pointer';
                        c.onclick=saec_mouseclick;
                        c.onmouseover = saec_table_highlight;
                    }
                    j++;
                }else{
                    j++;
                }
            }
            if (j > saec_ranged) break;
        }
        if (j-1 < saec_total){
            r = a.insertRow(-1);
            r.style.backgroundColor = saec_self.saec_bgColor;
            c = r.insertCell(-1);
            c.style.color = saec_self.saec_textColor;
            c.style.fontFamily = 'arial narrow';
            c.style.fontSize = saec_self.saec_fSize;
            c.align='center';
            replaceHTML(c,'\\/');
            if (saec_self.saec_mouse){
                c.style.cursor = 'pointer';
                c.onclick = saec_mouse_down;
            }
        }
    }
    function saec_goup(){
        if (!saec_display) return;
        if (saec_pos == 1) return;
        document.getElementById('tat_tr'+saec_pos).style.backgroundColor = saec_self.saec_bgColor;
        saec_pos--;
        if (saec_pos < saec_rangeu) saec_moveup();
        document.getElementById('tat_tr'+saec_pos).style.backgroundColor = saec_self.saec_hColor;
        if (saec_toid) clearTimeout(saec_toid);
        if (saec_self.saec_timeOut > 0) saec_toid = setTimeout(function(){saec_mouse_on_list=0;saec_removedisp();},saec_self.saec_timeOut);
    }
    function saec_godown(){
        if (!saec_display) return;
        if (saec_pos == saec_total) return;
        document.getElementById('tat_tr'+saec_pos).style.backgroundColor = saec_self.saec_bgColor;
        saec_pos++;
        if (saec_pos > saec_ranged) saec_movedown();
        document.getElementById('tat_tr'+saec_pos).style.backgroundColor = saec_self.saec_hColor;
        if (saec_toid) clearTimeout(saec_toid);
        if (saec_self.saec_timeOut > 0) saec_toid = setTimeout(function(){saec_mouse_on_list=0;saec_removedisp();},saec_self.saec_timeOut);
    }
    function saec_movedown(){
        saec_rangeu++;
        saec_ranged++;
        saec_remake();
    }
    function saec_moveup(){
        saec_rangeu--;
        saec_ranged--;
        saec_remake();
    }

    /* Mouse */
    function saec_mouse_down(){
        document.getElementById('tat_tr'+saec_pos).style.backgroundColor = saec_self.saec_bgColor;
        saec_pos++;
        saec_movedown();
        document.getElementById('tat_tr'+saec_pos).style.backgroundColor = saec_self.saec_hColor;
        saec_curr.focus();
        saec_mouse_on_list = 0;
        if (saec_toid) clearTimeout(saec_toid);
        if (saec_self.saec_timeOut > 0) saec_toid = setTimeout(function(){saec_mouse_on_list=0;saec_removedisp();},saec_self.saec_timeOut);
    }
    function saec_mouse_up(evt){
        if (!evt) evt = event;
        if (evt.stopPropagation){
            evt.stopPropagation();
        }else{
            evt.cancelBubble = true;
        }
        document.getElementById('tat_tr'+saec_pos).style.backgroundColor = saec_self.saec_bgColor;
        saec_pos--;
        saec_moveup();
        document.getElementById('tat_tr'+saec_pos).style.backgroundColor = saec_self.saec_hColor;
        saec_curr.focus();
        saec_mouse_on_list = 0;
        if (saec_toid) clearTimeout(saec_toid);
        if (saec_self.saec_timeOut > 0) saec_toid = setTimeout(function(){saec_mouse_on_list=0;saec_removedisp();},saec_self.saec_timeOut);
    }
    function saec_mouseclick(evt){
        if (!evt) evt = event;
        if (!saec_display) return;
        saec_mouse_on_list = 0;
        saec_pos = this.getAttribute('pos');
        saec_penter();
    }
    function saec_table_focus(){
        saec_mouse_on_list = 1;
    }
    function saec_table_unfocus(){
        saec_mouse_on_list = 0;
        if (saec_toid) clearTimeout(saec_toid);
        if (saec_self.saec_timeOut > 0) saec_toid = setTimeout(function(){saec_mouse_on_list = 0;saec_removedisp();},saec_self.saec_timeOut);
    }
    function saec_table_highlight(){
        saec_mouse_on_list = 1;
        document.getElementById('tat_tr'+saec_pos).style.backgroundColor = saec_self.saec_bgColor;
        saec_pos = this.getAttribute('pos');
        while (saec_pos < saec_rangeu) saec_moveup();
        while (saec_pos > saec_ranged) saec_movedown();
        document.getElementById('tat_tr'+saec_pos).style.backgroundColor = saec_self.saec_hColor;
        if (saec_toid) clearTimeout(saec_toid);
        if (saec_self.saec_timeOut > 0) saec_toid = setTimeout(function(){saec_mouse_on_list = 0;saec_removedisp();},saec_self.saec_timeOut);
    }
    /* ---- */

    function saec_insertword(a){
        if (saec_self.saec_delimiter.length > 0){
            str = '';
            l=0;
            for (i=0;i<saec_delimwords.length;i++){
                if (saec_cdelimword == i){
                    prespace = postspace = '';
                    gotbreak = false;
                    for (j=0;j<saec_delimwords[i].length;++j){
                        if (saec_delimwords[i].charAt(j) != ' '){
                            gotbreak = true;
                            break;
                        }
                        prespace += ' ';
                    }
                    for (j=saec_delimwords[i].length-1;j>=0;--j){
                        if (saec_delimwords[i].charAt(j) != ' ') break;
                        postspace += ' ';
                    }
                    str += prespace;
                    str += a;
                    l = str.length;
                    if (gotbreak) str += postspace;
                }else{
                    str += saec_delimwords[i];
                }
                if (i != saec_delimwords.length - 1){
                    str += saec_delimchar[i];
                }
            }
            saec_curr.value = str;
            setCaret(saec_curr,l);
        }else{
            saec_curr.value = a;
        }
        saec_mouse_on_list = 0;
        saec_removedisp();
    }
    function saec_penter(){
        if (!saec_display) return;
        saec_display = false;
        var word = '';
        var c = 0;
        for (var i=0;i<=saec_self.saec_keywords.length;i++){
            if (saec_bool[i]) c++;
            if (c == saec_pos){
                word = saec_self.saec_keywords[i];
                break;
            }
        }
        saec_insertword(word);
        l = getCaretStart(saec_curr);
    }
    function saec_removedisp(){
        if (saec_mouse_on_list==0){
            saec_display = 0;
            if (document.getElementById('tat_table')){ document.body.removeChild(document.getElementById('tat_table')); }
            if (saec_toid) clearTimeout(saec_toid);
        }
    }
    function saec_keypress(e){
        if (saec_caretmove) stopEvent(e);
        return !saec_caretmove;
    }
    function saec_checkkey(evt){
        if (!evt) evt = event;
        a = evt.keyCode;
        caret_pos_start = getCaretStart(saec_curr);
        saec_caretmove = 0;
        switch (a){
            case 38:
                saec_goup();
                saec_caretmove = 1;
                return false;
                break;
            case 40:
                saec_godown();
                saec_caretmove = 1;
                return false;
                break;
            case 13: case 9:
                if (saec_display){
                    saec_caretmove = 1;
                    saec_penter();
                    return false;
                }else{
                    return true;
                }
                break;
            default:
                setTimeout(function(){saec_tocomplete(a)},50);
                break;
        }
    }

    function saec_tocomplete(kc){
        if (kc == 38 || kc == 40 || kc == 13) return;
        var i;
        if (saec_display){
            var word = 0;
            var c = 0;
            for (var i=0;i<=saec_self.saec_keywords.length;i++){
                if (saec_bool[i]) c++;
                if (c == saec_pos){
                    word = i;
                    break;
                }
            }
            saec_pre = word;
        }else{ saec_pre = -1};
       
        if (saec_curr.value == ''){
            saec_mouse_on_list = 0;
            saec_removedisp();
            return;
        }
        if (saec_self.saec_delimiter.length > 0){
            caret_pos_start = getCaretStart(saec_curr);
            caret_pos_end = getCaretEnd(saec_curr);
           
            delim_split = '';
            for (i=0;i<saec_self.saec_delimiter.length;i++){
                delim_split += saec_self.saec_delimiter[i];
            }
            delim_split = delim_split.addslashes();
            delim_split_rx = new RegExp("(["+delim_split+"])");
            c = 0;
            saec_delimwords = new Array();
            saec_delimwords[0] = '';
            for (i=0,j=saec_curr.value.length;i<saec_curr.value.length;i++,j--){
                if (saec_curr.value.substr(i,j).search(delim_split_rx) == 0){
                    ma = saec_curr.value.substr(i,j).match(delim_split_rx);
                    saec_delimchar[c] = ma[1];
                    c++;
                    saec_delimwords[c] = '';
                }else{
                    saec_delimwords[c] += saec_curr.value.charAt(i);
                }
            }

            var l = 0;
            saec_cdelimword = -1;
            for (i=0;i<saec_delimwords.length;i++){
                if (caret_pos_end >= l && caret_pos_end <= l + saec_delimwords[i].length){
                    saec_cdelimword = i;
                }
                l+=saec_delimwords[i].length + 1;
            }
            var ot = saec_delimwords[saec_cdelimword].trim();
            var t = saec_delimwords[saec_cdelimword].addslashes().trim();
        }else{
            var ot = saec_curr.value;
            var t = saec_curr.value.addslashes();
        }
        if (ot.length == 0){
            saec_mouse_on_list = 0;
            saec_removedisp();
        }
        if (ot.length < saec_self.saec_startcheck) return this;
        if (saec_self.saec_firstText){
            var re = new RegExp("^" + t, "i");
        }else{
            var re = new RegExp(t, "i");
        }

        saec_total = 0;
        saec_tomake = false;
        saec_kwcount = 0;
        for (i=0;i<saec_self.saec_keywords.length;i++){
            saec_bool[i] = false;
            if (re.test(saec_self.saec_keywords[i])){
                saec_total++;
                saec_bool[i] = true;
                saec_kwcount++;
                if (saec_pre == i) saec_tomake = true;
            }
        }

        if (saec_toid) clearTimeout(saec_toid);
        if (saec_self.saec_timeOut > 0) saec_toid = setTimeout(function(){saec_mouse_on_list = 0;saec_removedisp();},saec_self.saec_timeOut);
        saec_generate();
    }
    return this;
}


    /* Event Functions */

    // Add an event to the obj given
    // event_name refers to the event trigger, without the "on", like click or mouseover
    // func_name refers to the function callback when event is triggered
    function addEvent(obj,event_name,func_name){
        if (obj.attachEvent){
            obj.attachEvent("on"+event_name, func_name);
        }else if(obj.addEventListener){
            obj.addEventListener(event_name,func_name,true);
        }else{
            obj["on"+event_name] = func_name;
        }
    }

    // Removes an event from the object
    function removeEvent(obj,event_name,func_name){
        if (obj.detachEvent){
            obj.detachEvent("on"+event_name,func_name);
        }else if(obj.removeEventListener){
            obj.removeEventListener(event_name,func_name,true);
        }else{
            obj["on"+event_name] = null;
        }
    }

    // Stop an event from bubbling up the event DOM
    function stopEvent(evt){
        evt || window.event;
        if (evt.stopPropagation){
            evt.stopPropagation();
            evt.preventDefault();
        }else if(typeof evt.cancelBubble != "undefined"){
            evt.cancelBubble = true;
            evt.returnValue = false;
        }
        return false;
    }

    // Get the obj that starts the event
    function getElement(evt){
        if (window.event){
            return window.event.srcElement;
        }else{
            return evt.currentTarget;
        }
    }
    // Get the obj that triggers off the event
    function getTargetElement(evt){
        if (window.event){
            return window.event.srcElement;
        }else{
            return evt.target;
        }
    }
    // For IE only, stops the obj from being selected
    function stopSelect(obj){
        if (typeof obj.onselectstart != 'undefined'){
            addEvent(obj,"selectstart",function(){ return false;});
        }
    }

    /*    Caret Functions     */

    // Get the end position of the caret in the object. Note that the obj needs to be in focus first
    function getCaretEnd(obj){
        if(typeof obj.selectionEnd != "undefined"){
            return obj.selectionEnd;
        }else if(document.selection&&document.selection.createRange){
            var M=document.selection.createRange();
            try{
                var Lp = M.duplicate();
                Lp.moveToElementText(obj);
            }catch(e){
                var Lp=obj.createTextRange();
            }
            Lp.setEndPoint("EndToEnd",M);
            var rb=Lp.text.length;
            if(rb>obj.value.length){
                return -1;
            }
            return rb;
        }
    }
    // Get the start position of the caret in the object
    function getCaretStart(obj){
        if(typeof obj.selectionStart != "undefined"){
            return obj.selectionStart;
        }else if(document.selection&&document.selection.createRange){
            var M=document.selection.createRange();
            try{
                var Lp = M.duplicate();
                Lp.moveToElementText(obj);
            }catch(e){
                var Lp=obj.createTextRange();
            }
            Lp.setEndPoint("EndToStart",M);
            var rb=Lp.text.length;
            if(rb>obj.value.length){
                return -1;
            }
            return rb;
        }
    }
    // sets the caret position to l in the object
    function setCaret(obj,l){
        obj.focus();
        if (obj.setSelectionRange){
            obj.setSelectionRange(l,l);
        }else if(obj.createTextRange){
            m = obj.createTextRange();       
            m.moveStart('character',l);
            m.collapse();
            m.select();
        }
    }
    // sets the caret selection from s to e in the object
    function setSelection(obj,s,e){
        obj.focus();
        if (obj.setSelectionRange){
            obj.setSelectionRange(s,e);
        }else if(obj.createTextRange){
            m = obj.createTextRange();       
            m.moveStart('character',s);
            m.moveEnd('character',e);
            m.select();
        }
    }

    /*    Escape function   */
    String.prototype.addslashes = function(){
        return this.replace(/(["\\\.\|\[\]\^\*\+\?\$\(\)])/g, '\\$1');
    }
    String.prototype.trim = function () {
        return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
    };
    /* --- Escape --- */

    /* Offset position from top of the screen */
    function curTop(obj){
        toreturn = 0;
        while(obj){
            toreturn += obj.offsetTop;
            obj = obj.offsetParent;
        }
        return toreturn;
    }
    function curLeft(obj){
        toreturn = 0;
        while(obj){
            toreturn += obj.offsetLeft;
            obj = obj.offsetParent;
        }
        return toreturn;
    }
    /* ------ End of Offset function ------- */

    /* Types Function */

    // is a given input a number?
    function isNumber(a) {
        return typeof a == 'number' && isFinite(a);
    }

    /* Object Functions */

    function replaceHTML(obj,text){
        while(el = obj.childNodes[0]){
            obj.removeChild(el);
        };
        obj.appendChild(document.createTextNode(text));
    }

    //****************************************************************************
  </script>
 </head>

 <body>
  <textarea rows="4" cols="60" id="tb"></textarea>
  <!-- <input type="text" id="tb"> -->
    <script>
    var obj = actb(document.getElementById('tb'),customarray);
    </script>
 </body>
</html>



Output



Thursday, March 5, 2009

Java : Simple java program to write an Excel File using Apache POI

This is a simple java code to create Excel File, you can customize according to user need.. you can write multiple Excel file with multiple excel Sheet, write desire data etc

Note : to run this code u need to download POI

/* Here is the code for WriteExcel .java */


import java.io.*;
import java.util.*;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;

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

String excelFileName = "myExcelFile.xls";//name of excel file


String sheetName = "Sheet1";//name of sheet

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName) ;

//creating Random numbers
//Random is a inbuilt java class in 1.5 in util package
Random random = new Random();


//iterating r number of rows
for (int r=0;r < 10; r++ )
{
HSSFRow row = sheet.createRow(r);

//iterating c number of columns
for (int c=0;c < 5; c++ )
{
HSSFCell cell = row.createCell((short)c);
//createCell(short) method is Deprecated
//you can use createCell(int) method also

int temp = random.nextInt(100);//get random int values between 0 and 100

cell.setCellValue(temp);//write temp values
}
}

//You can also provide path where to save this excel file
FileOutputStream fileOut = new FileOutputStream(excelFileName);

wb.write(fileOut);//write out this workbook to an Outputstream.
fileOut.flush();
fileOut.close();
}
}

Tuesday, March 3, 2009

java : simple program to send mails using Gmail (ie javamail API)

Here is the code to send mail using gmail

Note: to run this code u need to download JavaMail 1.4.2  jar files

/*Here is the complete tested code for Gmail.java */

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class Gmail
{
public static void main(String[] args)
{
Properties props = new Properties();
props.put("mail.smtp.user","madan712@gmail.com");
props.put("mail.smtp.host","smtp.gmail.com");
props.put("mail.smtp.port","465");

props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.debug","true");

props.put("mail.smtp.socketFactory.port","465");

props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");

try
{
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);

MimeMessage msg = new MimeMessage(session);
msg.setSubject("Testing");
msg.setText("Hi !! how are you??");

msg.setFrom(new InternetAddress("madan712@gmail.com"));

msg.addRecipient(Message.RecipientType.TO, new InternetAddress("madan@indiagames.com"));

msg.addRecipient(Message.RecipientType.CC, new InternetAddress("madan_chaudhary@rediffmail.com"));

msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com","madan712@gmail.com","********");//password
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();

}
catch (Exception ex)
{
System.out.println("Exception occured");
ex.printStackTrace();
}
}
}




this is common exception every one gets if your server doesn't responds....



Exception in thread "main" javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
at javax.mail.Service.connect(Service.java:288)
at javax.mail.Service.connect(Service.java:169)
at javax.mail.Service.connect(Service.java:118)
at SimpleMail.main(SimpleMail.java:23)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
... 5 more