| Main | Resume | Projects | My Best Ideas | Hobbies | Employment | My Best Sites | Java Tips | Oracle Tips |
|
To open the given URL in the default Browser from Command Line |
|
|
To render the html page with selected tables, its columns and its contents |
|
Program: To Read a String from Command Line
*/
import
java.io.InputStreamReader;
import java.io.BufferedReader ;
import java.io.IOException;
public class readString {
public
static void main (String[] args)
{
InputStreamReader
reader = new InputStreamReader (System.in);
BufferedReader myInput = new BufferedReader (reader);
String str= new String();
try {
str
= myInput.readLine();
}
catch (IOException e) {
System.out.println
("Exception raised: " + e);
System.exit(-1);
}
System.out.println ("You have written: "+str);
}
}
===============================================================
/*
*/
import java.awt.Graphics;
import java.util.*;
import java.text.DateFormat;
import java.applet.Applet;
/*
<applet code=Clock.class height=300, width=300>
</applet>
*/
public class Clock extends Applet implements Runnable {
private Thread clockThread = null;
public void start() {
if (clockThread == null) {
clockThread = new Thread(this, "Clock");
clockThread.start();
}
}
public void run() {
Thread myThread = Thread.currentThread();
while (clockThread == myThread) {
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e){
// the VM doesn't want us to sleep anymore,
// so get back to work
}
}
}
public void paint(Graphics g) {
// get the time and convert it to a date
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
// format it and display it
DateFormat dateFormatter = DateFormat.getTimeInstance();
g.drawString(dateFormatter.format(date), 5, 10);
}
// overrides Applet's stop method, not Thread's
public void stop() {
clockThread = null;
}
}
===============================================================
/*
*/
import java.net.*;
import java.io.*;
public class ConnectTo1 {
public static void main(String[] args) {
String myStringUrl;
String inputLine;
if (args.length==0) {
System.out.print ("\nUsage: ConnectTo URL");
System.exit(1);
}
myStringUrl = new String(args[0]);
try {
URL myUrl=new URL(myStringUrl);
InputStreamReader in = new InputStreamReader(myUrl.openStream());
BufferedReader reader = new BufferedReader(in);
while ((inputLine = reader.readLine()) != null)
System.out.println(inputLine);
in.close();
} catch (MalformedURLException e) {
System.out.println (myStringUrl+ " is not a valid URL.");
System.exit(1);
} catch (IOException e) {
System.out.println ("Unable to connect to "+myStringUrl);
System.exit(1);
}
}
}
==============================================================
/*
*/
import java.net.*;
import java.io.*;
public class OpenBrowser {
public static void main(String[] args) throws Exception {
Process p=null;
Runtime r=null;
if(args.length <= 0) {
System.out.println("\nUsage : OpenBrowser <URL> ");
System.exit(0);
}
try {
r = Runtime.getRuntime();
p = r.exec("rundll32 url.dll,FileProtocolHandler " + args[0]);
p.waitFor();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
==============================================================
/*
*/
public class Rand {
public static void main(String a[]) {
java.util.Random rand = new java.util.Random();
for(int i=10; i<25; i++){
System.out.println("Number #" + i + " => " + rand.nextInt(100));
}
}
}
==============================================================
/*
*/
package comsrini.srini.codebase;
import java.sql.*;
import java.util.StringTokenizer;
public class Renderer {
private ResultSet rs = null;
private ResultSetMetaData rsmd = null;
public Renderer() {
}
public String getTables(Statement stmt) throws Exception {
StringBuffer tables = new StringBuffer();
try {
rs = stmt.executeQuery("SELECT * FROM TAB");
if(rs.next()) {
do {
tables.append("<option value='" + rs.getString(1) + "'>" + rs.getString(1));
}while(rs.next());
}else {
return null;
}
} catch(Exception e) {
e.printStackTrace();
return null;
}
return tables.toString();
}
public String getColumns(Statement stmt,String table) throws Exception {
StringBuffer columns = new StringBuffer();
try {
rs = stmt.executeQuery("SELECT * FROM " + table + " WHERE 1=2");
rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int cindx=1;
while(cindx <= numberOfColumns) {
columns.append("<option value='" + rsmd.getColumnName(cindx) +"'>" + rsmd.getColumnName(cindx));
cindx++;
}//while
}catch(Exception e) {
e.printStackTrace();
return null;
}
return columns.toString();
}
public String getRows(Statement stmt,String[] fields, String table) throws Exception {
StringBuffer rows = new StringBuffer();
String pdt = "";
String sql = "SELECT ";
int cindx=-1;
while (++cindx < fields.length){
sql += fields[cindx] + ",";
}
int len = sql.length();
sql = sql.substring(0,len-1) + " FROM " + table;
try {
rs = stmt.executeQuery(sql);
rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
cindx=1;
int recCount = 1;
rows.append("<tr><th colspan='" + numberOfColumns + "'>Table : <i>" + table + "</i></th></tr><tr>");
while(cindx <= numberOfColumns) {
pdt = rsmd.getColumnName(cindx);
cindx++;
rows.append("<th bgcolor='purple'><font face='Arial' size='3' color='white'>" + pdt + "</font></th>");
}//Column heading
rows.append("</tr>");
while(rs.next()) {
cindx=1;
rows.append("<tr>");
while(cindx <= numberOfColumns){
pdt=rs.getString(cindx);
cindx++;
rows.append("<td><font face='Arial' size='2'>" + pdt + "</font></td>");
};//inner while to print data of all fields
rows.append("</tr>");
recCount++;
}; //outer while to get next record
rows.append("<tr><th colspan='" + numberOfColumns +"'>Total records : " + (recCount-1) + "</th></tr>");
}catch(Exception e) {
e.printStackTrace();
return e.getMessage();
}
return rows.toString();
}
public String getRows(Statement stmt,String sql,int start,int end) throws Exception {
StringBuffer rows = new StringBuffer();
try {
rs = stmt.executeQuery(sql);
rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int cindx=1;
int recCount = 1;
String pdt ="";
rows.append("<table border=1><tr>");
while(cindx <= numberOfColumns) {
pdt = rsmd.getColumnName(cindx);
cindx++;
rows.append("<th bgcolor='purple'><font face='Arial' size='3' color='white'>" + pdt + "</font></th>");
}//Column heading
rows.append("</tr>");
while(recCount != start)
recCount++;
while(rs.next() && (recCount <= end) ) {
cindx=1;
rows.append("<tr>");
while(cindx <= numberOfColumns){
pdt=rs.getString(cindx);
cindx++;
rows.append("<td><font face='Arial' size='2'>" + pdt + "</font></td>");
};//inner while to print data of all fields
rows.append("</tr>");
recCount++;
}; //outer while to get next record
rows.append("<tr><th colspan='" + numberOfColumns +"'>Total records : " + (recCount-1) + "</th></tr></table>");
}catch(Exception e) {
e.printStackTrace();
return e.getMessage();
}
return rows.toString();
}
public String getSQLExecuterMessage(Statement stmt,String sql, int start,int end) {
StringBuffer rows = new StringBuffer();
int cindx= 1;
int cnt = 1;
int recCount = 1;
String sqlStatment = "";
StringTokenizer st = new StringTokenizer(sql,";");
try {
while (st.hasMoreTokens()){
sqlStatment = st.nextToken();
sqlStatment = sqlStatment.trim();
if(sqlStatment == null || sqlStatment.equals("")) {
continue; // Skip improper/blank Statements
}
else {
String checkStmtType = sqlStatment.substring(0,6);
if(checkStmtType.equalsIgnoreCase("insert") || checkStmtType.equalsIgnoreCase("update") || checkStmtType.equalsIgnoreCase("delete") || checkStmtType.equalsIgnoreCase("alter ")) {
int modifiedRecordsCount = stmt.executeUpdate(sqlStatment);
if(modifiedRecordsCount > 0) {
rows.append("<hr><b>" + modifiedRecordsCount + " rows Deleted </b>");
}
else if(checkStmtType.equalsIgnoreCase("alter ") && modifiedRecordsCount == 0) {
rows.append("<hr>Table Altered");
}
}else {
rows.append("<hr>" + getRows(stmt,sqlStatment,start,end));
}
}
}
}catch(Exception e) {
e.printStackTrace();
return "Error : " + e.getMessage();
}
return rows.toString();
}//method
}
==============================================================
/*
####################################################################
####################################################################
Interface
*/
import java.rmi.*;
public interface SriInt extends java.rmi.Remote
{
public void printMessage() throws java.rmi.RemoteException;;
public String getResult(int a, int b) throws java.rmi.RemoteException;
}
/*
Implementation class
*/
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.LocateRegistry;
class SriImp extends UnicastRemoteObject implements SriInt
{
public SriImp() throws java.rmi.RemoteException {}
public void printMessage() throws java.rmi.RemoteException
{
System.out.println("\n\nThis will be printed in Server side when the object is gets binded");
}
public String getResult(int a, int b) throws java.rmi.RemoteException {
System.out.println("From client Side.....");
System.out.println("A = " + a);
System.out.println("B = " + b);
return ("Result ===> " + (a+b));
}
}
/*
Client
*/
import java.util.*;
import java.net.*;
import java.rmi.*;
import java.rmi.RMISecurityManager;
import java.rmi.registry.LocateRegistry;
public class SClient
{
public static void main( String args[] )
{
int a;
int b;
//System.setSecurityManager( new RMISecurityManager());
System.setSecurityManager (new RMISecurityManager() {
public void checkConnect (String host, int port) {}
public void checkConnect (String host, int port, Object context) {}
});
try
{
System.out.println("\n\nStarting Client..........");
//String url = new String( "//"+ args[0] + "/sriObj");
String url = new String( "//localhost/sriObj");
System.out.println("Calc Server Lookup: url =" + url);
SriInt sri = (SriInt) Naming.lookup( url );
if( sri != null )
{
//print just a message
sri.printMessage();
try{
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
}catch(Exception e) {
System.out.println("Error Occured assuming default values...");
a = 10;
b =100;
}
System.out.println(sri.getResult(a,b));
} else {
System.out.println("Requested Remote object is null.");
}
}
catch( Exception e )
{
System.out.println("An error occured");
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
/*
Server
*/
import java.util.*;
import java.rmi.*;
import java.rmi.RMISecurityManager;
import java.rmi.registry.LocateRegistry;
public class SServer
{
public static void main( String args[] )
{
//System.setSecurityManager( new RMISecurityManager());
System.setSecurityManager (new RMISecurityManager() {
public void checkConnect (String host, int port) {}
public void checkConnect (String host, int port, Object context) {}
});
try
{
System.out.println("Starting calcServer");
SriImp sri = new SriImp();
System.out.println("\nBinding Server......");
Naming.rebind("sriObj", sri );
System.out.println("\nServer is waiting");
}
catch( Exception e )
{
System.out.println("An error occured");
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
******************************** XML **********************************
Program : To echo a simpl;e XML file using SAX
*/
import java.io.*;
import org.xml.sax.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
//set classpath=F:\MyUtils\Work\XML\parser.jar;F:\MyUtils\Work\XML\jaxp.jar;F:\MyUtils\Work\XML\xerces.jar
public class Echo extends HandlerBase {
static private Writer out;
private String indentString = " "; // Amount to indent
private int indentLevel = 0;
public static void main (String argv[]) {
if (argv.length != 1) {
System.err.println ("Usage: cmd filename");
System.exit (1);
}
// Use the default (non-validating) parser
// Use the validating parser
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
try {
// Set up output stream
out = new OutputStreamWriter (System.out, "UTF8");
// Parse the input
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( new File(argv [0]), new Echo() );
} catch (SAXParseException spe) {
// Error generated by the parser
System.out.println ("\n** Parsing error"
+ ", line " + spe.getLineNumber ()
+ ", uri " + spe.getSystemId ());
System.out.println(" " + spe.getMessage() );
// Unpack the delivered exception to get the exception it contains
Exception x = spe;
if (spe.getException() != null)
x = spe.getException();
x.printStackTrace();
} catch (SAXException sxe) {
// Error generated by this application
// (or a parser-initialization error)
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace ();
}/*}catch (Throwable t) {
t.printStackTrace ();
}*/
System.exit (0);
}
public void setDocumentLocator (Locator l) {
try {
out.write ("LOCATOR");
out.write ("\n SYS ID: " + l.getSystemId() );
out.flush ();
} catch (IOException e) {
// Ignore errors
}
}
public void startDocument() throws SAXException {
nl();
nl();
emit ("START DOCUMENT");
nl();
emit ("<?xml version='1.0' encoding='UTF-8'?>");
nl();
}
public void endDocument () throws SAXException {
nl();
emit ("END DOCUMENT");
try {
nl();
out.flush ();
} catch (IOException e) {
throw new SAXException ("I/O error", e);
}
}
public void startElement (String name, AttributeList attrs) throws SAXException {
indentLevel++;
nl();
emit ("ELEMENT: ");
emit ("<"+name);
if (attrs != null) {
for (int i = 0; i < attrs.getLength (); i++) {
//emit (" ");
//emit (attrs.getName(i)+"=\""+attrs.getValue (i)+"\"");
nl();
emit(" ATTR: ");
emit (attrs.getName (i));
emit ("\t\"");
emit (attrs.getValue (i));
emit ("\"");
}
}
if (attrs.getLength() > 0) nl();
emit (">");
}
public void endElement (String name) throws SAXException {
nl();
emit ("END_ELM: ");
emit ("</"+name+">");
indentLevel--;
}
public void characters (char buf [], int offset, int len) throws SAXException {
nl(); emit ("CHARS: |");
String s = new String(buf, offset, len);
//emit (s);
//emit ("|");
if (!s.trim().equals("")) emit (s);
}
public void ignorableWhitespace (char buf [], int offset, int len) throws SAXException {
nl(); emit("IGNORABLE");
}
public void processingInstruction (String target, String data) throws SAXException {
nl();
emit ("PROCESS: ");
emit ("<?"+target+" "+data+"?>");
}
private void emit (String s) throws SAXException {
try {
out.write (s);
out.flush ();
} catch (IOException e) {
throw new SAXException ("I/O error", e);
}
}
private void nl () throws SAXException {
String lineEnd = System.getProperty("line.separator");
try {
out.write (lineEnd);
for (int i=0; i < indentLevel; i++) out.write(indentString);
} catch (IOException e) {
throw new SAXException ("I/O error", e);
}
}
// treat validation errors as fatal
public void error (SAXParseException e) throws SAXParseException
{
throw e;
}
// dump warnings too
public void warning (SAXParseException err) throws SAXParseException{
System.out.println ("** Warning"
+ ", line " + err.getLineNumber ()
+ ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
}
}
/*
Program: Using DOM
*/
//Add these lines to import the JAXP APIs you'll be using:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilder;
//Add these lines for the exceptions that can be thrown when the XML document is parsed:
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
//Add these lines to read the sample XML file and identify errors:
import java.io.File;
import java.io.IOException;
//Finally, import the W3C definition for a DOM and DOM exceptions:
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
import com.sun.xml.tree.XmlDocument;
public class DomEcho {
static Document document;
public static void main (String argv [])
{
if (argv.length != 1) {
System.err.println ("Usage: java DomEcho filename");
System.exit (1);
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
//Error handler
builder.setErrorHandler(
new org.xml.sax.ErrorHandler() { // ignore fatal errors (an exception is guaranteed)
public void fatalError(SAXParseException exception)
throws SAXException {
}
// treat validation errors as fatal
public void error (SAXParseException e)
throws SAXParseException
{
throw e;
}
// dump warnings too
public void warning (SAXParseException err)
throws SAXParseException
{
System.out.println ("** Warning"
+ ", line " + err.getLineNumber ()
+ ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
}
}
);
document = builder.parse( new File(argv[0]) );
XmlDocument xdoc = (XmlDocument) document;
xdoc.write (System.out);
} catch (SAXParseException spe) {
// Error generated by the parser
System.out.println ("\n** Parsing error"
+ ", line " + spe.getLineNumber ()
+ ", uri " + spe.getSystemId ());
System.out.println(" " + spe.getMessage() );
// Use the contained exception, if any
Exception x = spe;
if (spe.getException() != null)
x = spe.getException();
x.printStackTrace();
} catch (SAXException sxe) {
// Error generated by this application
// (or a parser-initialization error)
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
}
}// main
}// DomEcho
/*
XML File DTD and source
*/
<!ELEMENT START (NAME, ADDRESS, ZIPCODE)>
<!ATTLIST START
startdate CDATA #REQUIRED
enddate CDATA #IMPLIED
>
<!ELEMENT NAME (#PCDATA)>
<!ELEMENT ADDRESS (#PCDATA)>
<!ELEMENT ZIPCODE (#PCDATA)>
<?xml version='1.0' encoding='ISO-8859-1'?>
<!DOCTYPE START SYSTEM "xml1.dtd">
<!-- A SAMPLE set of slides -->
<START startdate="today" enddate="tommorow">
<NAME>Srinivasa.V</NAME>
<ADDRESS>D-405, Pride Appartments</ADDRESS>
<ZIPCODE>560076</ZIPCODE>
</START>
=====================================================================
Program: To use Security Manager
*/
import java.io.*;
public class PasswordSecurityManager extends SecurityManager {
private String password;
private BufferedReader buffy;
public PasswordSecurityManager(String p, BufferedReader b) {
super();
this.password = p;
this.buffy = b;
}
private boolean accessOK() {
int c;
String response;
System.out.println("What's the secret password?");
try {
response = buffy.readLine();
if (response.equals(password))
return true;
else
return false;
} catch (IOException e) {
return false;
}
}
public void checkRead(FileDescriptor filedescriptor) {
if (!accessOK())
throw new SecurityException("Not a Chance!");
}
public void checkRead(String filename) {
if (!accessOK())
throw new SecurityException("No Way!");
}
public void checkRead(String filename, Object executionContext) {
if (!accessOK())
throw new SecurityException("Forget It!");
}
public void checkWrite(FileDescriptor filedescriptor) {
if (!accessOK())
throw new SecurityException("Not!");
}
public void checkWrite(String filename) {
if (!accessOK())
throw new SecurityException("Not Even!");
}
public void checkPropertyAccess(String s) { }
public void checkPropertiesAccess() { }
}
import java.io.*;
public class SecurityManagerTest {
public static void main(String[] args) throws Exception {
BufferedReader buffy = new BufferedReader(
new InputStreamReader(System.in));
try {
System.setSecurityManager(
new PasswordSecurityManager("Booga Booga", buffy));
} catch (SecurityException se) {
System.err.println("SecurityManager already set!");
}
BufferedReader in = new BufferedReader(new FileReader("words.txt"));
PrintWriter out = new PrintWriter(new FileWriter("outputtext.txt"));
String inputString;
while ((inputString = in.readLine()) != null)
out.println(inputString);
in.close();
out.close();
}
}
/*
IO Bug in Java
*/
import java.io.*;
public class IOBug {
public static void main ( String args[ ] ) throws Exception {
DataOutputStream out = new DataOutputStream ( new BufferedOutputStream ( new FileOutputStream ( "Data.txt" ) ) ) ;
out.writeDouble ( 3.14 ) ;
out.writeBytes ( "The bug.\n" ) ;
out.writeBytes ( "Got it or not.\n" ) ;
out.writeDouble ( 3.14 ) ;
out.close( ) ;
DataInputStream in = new DataInputStream ( new BufferedInputStream ( new FileInputStream ( "Data.txt" ) ) ) ;
BufferedReader inbr = new BufferedReader ( new InputStreamReader ( in ) ) ;
System.out.println ( in.readDouble( ) ) ;
System.out.println ( inbr.readLine( ) ) ;
System.out.println ( inbr.readLine( ) ) ;
System.out.println ( in.readDouble( ) ) ;
}
}
Program: Typical Program
*/
public class num {
public static void main(String a[]) {
System.out.println((long)111111111*111111111);
}
}
Program : To print from a Frame
*/
import java.awt.*;
import java.awt.event.*;
public class PrintingTest extends Frame implements ActionListener {
PrintCanvas canvas;
public PrintingTest() {
super("Printing Test");
canvas = new PrintCanvas();
add("Center", canvas);
Button b = new Button("Print");
b.setActionCommand("print");
b.addActionListener(this);
add("South", b);
Button c = new Button("Cancel");
c.setActionCommand("cancel");
c.addActionListener(this);
add("North", c);
pack();
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("print")) {
PrintJob pjob = getToolkit().getPrintJob(this,
"Printing Test", null);
if (pjob != null) {
Graphics pg = pjob.getGraphics();
if (pg != null) {
canvas.printAll(pg);
pg.dispose(); // flush page
}
pjob.end();
}
}
if(cmd.equals("cancel")) {
this.dispose();
System.exit(0);
//this.close();
}
}
public static void main(String args[]) {
PrintingTest test = new PrintingTest();
test.show();
}
}
class PrintCanvas extends Canvas {
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
public void paint(Graphics g) {
/*Rectangle r = getBounds();
g.setColor(Color.yellow);
g.fillRect(0, 0, r.width, r.height);
g.setColor(Color.blue);
g.drawLine(0, 0, r.width, r.height);
g.setColor(Color.red);
g.drawLine(0, r.height, r.width, 0);*/
g.drawString("This is for Test Printing from Java Program",50,20);
}
}
/*
Program: To get and Set system Property
*/
import java.util.Properties;
import java.util.Enumeration;
import java.io.*;
class props1 {
static public void main(String args[]){
try {
FileInputStream fis = new FileInputStream("test.txt");
Properties p = new Properties();
p.load(fis);
System.out.println("===== BEFORE SET =======");
p.list(System.out);
p.setProperty("key1","Srini1");
p.setProperty("key2","Srini2");
p.setProperty("key3","Srini3");
p.setProperty("key4","Srini4");
p.setProperty("key5","Srini5");
System.out.println("===== AFTER SET =======");
p.list(System.out);
/*Enumeration e = p.keys();
String ele = "";
for(int i = 1; e.hasMoreElements(); i++){
ele = (String)e.nextElement();
System.out.println("Name = " + ele);
System.out.println("Value = " + p.get(ele));
}*/
} catch(Exception e) {
System.out.println(e);
}
}
}
Program: To read a Random file
*/
import java.io.*;
public class readFile {
readFile(String filename){
readFromFile(filename);
}
public void readFromFile(String filename){
try{
RandomAccessFile file = new RandomAccessFile(filename,"r");
System.out.println("file length is "+file.length());
System.out.println("=========================================\n");
String text = file.readLine();
while(text != null) {
System.out.println(text);
text = file.readLine();
}
file.close();
}catch(FileNotFoundException e){
System.out.println("exception occured is " + e);
}
catch(IOException e){
System.out.println("E----O-----F");
System.out.println("exception occured is " + e);
}
}
public static void main(String args[]){
System.out.println("\n\nUsing Random Access file ");
System.out.println("=========================================\n");
if(args.length == 0) {
System.out.println("No files to Read...\n");
System.out.println("======================\n\n");
System.out.println("USAGE : java readFile <filename>\n");
System.out.println("======================\n");
System.exit(0);
}
else {
System.out.println("Reading file..." + args[0]);
System.out.println("=========================================\n");
System.out.println("Its Contents...\n");
System.out.println("=========================================\n");
//readFile filetoread = new readFile(args[0]);
new readFile(args[0]);
}
}
}
Program: To copy a file
*/
import java.io.*;
public class ReadJava {
public static void main(String[] arguments) {
if (arguments.length < 2)
System.out.println("Usage: java ReadJava filename1 filename2");
else {
try {
File inFile = new File(arguments[0]);
FileInputStream in = new FileInputStream(inFile);
File outFile = new File(arguments[1]);
FileOutputStream out = new FileOutputStream(outFile);
boolean eof = false;
while (!eof) {
int input = in.read();
if (input == -1)
eof = true;
else
out.write(input);
}
in.close();
out.close();
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}
}
}
}
/*
Encoding & decoding Applet
*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintStream;
import java.util.EventObject;
import java.util.Random;
public class RegEncoder extends Applet
implements ActionListener
{
private Banner ban = null;
public TextArea detext = null;
public TextField eentext = null;
public Button codeer = null;
public Button texteer = null;
public Button cleareer = null;
public Button backeer = null;
public String oudetekst = null;
public static final int KOL = 50;
public Color achterkleur = null;
public Color voorkleur = null;
public Label passel = null;
public Label bovenel = null;
public void init()
{
String s = getParameter("BgColor");
achterkleur = s != null ? new Color(Integer.parseInt(s, 16)) : Color.black;
s = getParameter("FgColor");
voorkleur = s != null ? new Color(Integer.parseInt(s, 16)) : Color.green;
setBackground(achterkleur);
setForeground(voorkleur);
oudetekst = "";
detext = new TextArea();
eentext = new TextField();
cleareer = new Button(getParameter("Button1"));
backeer = new Button(getParameter("Button2"));
codeer = new Button(getParameter("Button3"));
texteer = new Button(getParameter("Button4"));
bovenel = new Label(getParameter("Label1"), 1);
passel = new Label(getParameter("Label2"));
setLayout(null);
addBanner();
bovenel.setBounds(10, 10, 400, 20);
detext.setBounds(10, 40, 400, 400);
detext.setBackground(Color.white);
detext.setForeground(Color.black);
eentext.setBounds(70, 450, 210, 20);
eentext.setBackground(Color.white);
eentext.setForeground(Color.black);
passel.setBounds(10, 450, 60, 20);
cleareer.setBounds(290, 450, 50, 20);
cleareer.addActionListener(this);
cleareer.setForeground(Color.black);
backeer.setBounds(350, 450, 50, 20);
backeer.addActionListener(this);
backeer.setForeground(Color.black);
codeer.setBounds(10, 480, 195, 20);
codeer.addActionListener(this);
codeer.setForeground(Color.black);
texteer.setBounds(215, 480, 195, 20);
texteer.addActionListener(this);
texteer.setForeground(Color.black);
add(detext);
add(eentext);
add(bovenel);
add(passel);
add(cleareer);
add(backeer);
add(codeer);
add(texteer);
}
public void paint(Graphics g)
{
}
public void actionPerformed(ActionEvent actionevent)
{
if(codeer == actionevent.getSource())
{
oudetekst = detext.getText();
detext.setText(getParameter("Wait"));
detext.setText(vercode(oudetekst, vertaal(eentext.getText())));
return;
}
if(texteer == actionevent.getSource())
{
oudetekst = detext.getText();
detext.setText(getParameter("Wait"));
detext.setText(verdecode(oudetekst, vertaal(eentext.getText())));
return;
}
if(cleareer == actionevent.getSource())
{
oudetekst = detext.getText();
detext.setText("");
return;
}
else
{
String s = detext.getText();
detext.setText(oudetekst);
oudetekst = s;
return;
}
}
public String vercode(String s, int ai[])
{
Random random = new Random();
String s1 = "000";
int i = 3;
for(int j = 0; j < s.length(); j++)
{
char c = s.charAt(j);
int k = c + ai[j % ai.length] * (j % 12 + 1);
s1 = s1 + (k / 100 - (k / 1000) * 10);
if(i++ >= 50)
{
s1 = s1 + "\n";
i = 0;
}
s1 = s1 + (k / 10 - (k / 100) * 10);
if(i++ >= 50)
{
s1 = s1 + "\n";
i = 0;
}
s1 = s1 + (k - (k / 10) * 10);
if(i++ >= 50)
{
s1 = s1 + "\n";
i = 0;
}
int l = c % 3;
for(int i1 = 0; i1 < l; i1++)
{
int j1 = random.nextInt() % 10;
s1 = s1 + (j1 < 0 ? -j1 : j1);
if(i++ >= 50)
{
s1 = s1 + "\n";
i = 0;
}
}
}
s1 = s1 + "000";
return s1;
}
public String verdecode(String s, int ai[])
{
String s1 = "";
int i = 0;
int j = 0;
try
{
while(j + 2 < s.length() && (s.charAt(j) != '0' || s.charAt(j + 1) != '0' || s.charAt(j + 2) != '0'))
j++;
if(j + 2 < s.length())
{
for(j += 3; j < s.length(); j++)
{
char c = s.charAt(j);
if(c >= '0' && c <= '9')
s1 = s1 + c;
}
s = "";
for(int k = 0; k + 2 < s1.length() && (s1.charAt(k) != '0' || s1.charAt(k + 1) != '0' || s1.charAt(k + 2) != '0');)
{
int l = (s1.charAt(k) - 48) * 100 + (s1.charAt(k + 1) - 48) * 10 + (s1.charAt(k + 2) - 48);
l -= ai[i % ai.length] * (i % 12 + 1);
k += 3 + l % 3;
s = s + (char)l;
i++;
}
return s;
}
else
{
return getParameter("Error");
}
}
catch(IndexOutOfBoundsException _ex)
{
return "Bug in program and text, please try again.";
}
}
public int[] vertaal(String s)
{
int ai[] = new int[s.length()];
int i = 0;
for(int j = 0; j < s.length(); j++)
{
char c = s.charAt(j);
if(c >= 'A' && c <= 'Z')
{
ai[j] = (c - 65) + 1;
i++;
}
if(c >= 'a' && c <= 'z')
{
ai[j] = (c - 97) + 1;
i++;
}
if(c >= '0' && c <= '9')
{
ai[j] = (c - 48) + 1;
i++;
}
}
if(i > 0)
{
int ai1[] = new int[i];
for(int k = 0; k < i; k++)
ai1[k] = ai[k];
return ai1;
}
int ai2[] = new int[5];
for(int l = 0; l < 5; l++)
ai2[l] = l;
return ai2;
}
public void addBanner()
{
Dimension dimension = getSize();
ban = new Banner(dimension.width, this);
ban.setBounds(0, dimension.height - 60, dimension.width, 60);
add(ban);
}
public RegEncoder()
{
}
}
Program: Soundex function of Oracle
*/
public class Soundex {
public static void main(String[] argv) {
if(argv.length <= 0) {
System.out.println("\n================================");
System.out.println(" Usage : java Soundex <string>");
System.out.println("================================");
System.exit(0);
}//if
else {
//for(int i=0; i<=argv.length; i++)
// System.out.println("i = " + i +" "+ argv[i]);
Sclass sc = new Sclass();
System.out.println("\n================================");
System.out.println(argv[0] + " === " + sc.getSoundex(argv[0].toUpperCase()) );
System.out.println("\n================================");
}//else
}//main
}//class
class Sclass {
//String[] code4String = {"BFPV","1","CGJKQSXZ","2","DT","3","L","4","MN","5","R","6"};
String sndx ="",
public String getSoundex(String str) {
sndx += str.charAt(0);
int indx = 0;
for(int i=0; i<str.length(); i++) {
if(i > 0 && str.charAt(i--) == str.charAt(i)) continue;
char ch = str.charAt(i);
if(sndx.length() == 4) return(sndx); //break if length exceeds
System.out.println("Value = " + ch + " " + indx + " " + sndx.charAt(indx));
switch(ch) {
case 'B':
case 'F':
case 'P':
case 'V':
if (indx >= 0 && sndx.charAt(indx) == '1') continue;
sndx += "1";
indx++;
break;
case 'C':
case 'G':
case 'J':
case 'K':
case 'Q':
case 'S':
case 'X':
case 'Z':
if (indx >= 0 && sndx.charAt(indx) == '2') continue;
sndx += "2";
indx++;
break;
case 'D':
case 'T':
if (indx >= 0 && sndx.charAt(indx) == '3') continue;
sndx += "3";
indx++;
break;
case 'L':
if (indx >= 0 && sndx.charAt(indx) == '4') continue;
sndx += "4";
indx++;
break;
case 'M':
case 'N':
if (indx >= 0 && sndx.charAt(indx) == '5') continue;
sndx += "5";
indx++;
break;
case 'R':
if (indx >= 0 && sndx.charAt(indx) == '6') continue;
sndx += "6";
indx++;
break;
default:
; //if other do nothing.....
}//switch-case
}//for
if(sndx.length() < 4)
while(sndx.length() <= 3) sndx += "0";
return(sndx);
}//method
}//class
/*
Web Scrawler Programs
*/
import java.util.*;
public class Spider1
{
private ArrayList linksFound;
private String keyWord;
private int MAXDEPTH = 1;
public Spider1(String initialSite, String searchFor)
{
linksFound = new ArrayList();
keyWord = searchFor;
crawl (initialSite, 0);
}
public void crawl(String location, int depth)
{
WebSite1 theSite = new WebSite1( location, keyWord );
theSite.process();
if ( theSite.isRelevant && !linksFound.contains( (String)location ) ){
System.out.println("location ==> " + location);
linksFound.add( location );
}
if ( depth < MAXDEPTH )
{
for ( int i = 0; i < theSite.links.size(); i++ )
{
String site = (String) theSite.links.get(i);
if ( !linksFound.contains( site ) ){
System.out.println(" ->>>>>> new site parsingg == "+site+" depth = "+(depth+1));
crawl( site, depth+1 );
}
}
}
}
public String toString()
{
String output = "";
System.out.println("################ Now Printing the links ##############");
for( int i = 0; i < linksFound.size(); i++ )
{
//output += ( linksFound.get(i) + "$" );
System.out.println(linksFound.get(i));
}
return output;
}
public static void main(String[] args)
{
Spider1 s = new Spider1("http://phoenix.marymount.edu/~bhoffman", "Programming");
//Spider1 s = new Spider1("http://www.rediff.com", "Nuke");
//Spider1 s = new Spider1("http://www.geocities.com/SiliconValley/Lakes/5365", "Usage");
//System.out.print( s.toString() );
s.toString();
}
}
// Sean McCauley 'WebSite1.java' created from Dr. Beryl Hoffman's example:
/** URLDemo.java : demos the URL class in java.net.
It opens a web page (given its URL) and prints out the results.
*/
import java.net.*; // for URL class
import java.io.*; // for BufferedReader
import java.util.*; // for ArrayList
public class WebSite1
{
private URL webPage;
private String keyword;
public ArrayList links;
private String currentSite;
public boolean isRelevant;
public WebSite1(String urlString, String k)
{
isRelevant = false;
links = new ArrayList();
keyword = k;
setCurrentSite(urlString);
try
{
webPage = new URL( urlString );
}
catch (MalformedURLException e)
{
System.out.println("Error: " + urlString + " is not a correct URL.");
System.exit(1);
}
}
private void setCurrentSite(String url)
{
if ( !url.endsWith("/") )
currentSite = ( url + "/" );
else
currentSite = url;
}
public void process()
{
// open the web page to read it
try
{
BufferedReader in = new BufferedReader(new InputStreamReader( webPage.openStream() ));
// read in web page into a big String
String line = "";
String input = "";
while( line != null )
{
line = in.readLine();
input += line;
}
int keywordTest = input.indexOf(keyword);
// System.out.println("keywordTest ==> "+ keywordTest);
if ( keywordTest != -1 )
{
isRelevant = true;
int linkStart = input.indexOf( "<a href=\"" );
int linkEnd = 0;
String newLink;
System.out.println(" linkStart " + linkStart);
while (linkStart != -1)
{
linkEnd = input.indexOf( "\">", linkStart );
newLink = input.substring(linkStart+9, linkEnd);
if ( !newLink.startsWith("#") && !newLink.startsWith("mailto:") ){
System.out.println("URL ===> " + (String) processLink( newLink ) );
links.add( (String) processLink( newLink ) );
}
linkStart = input.indexOf( "<a href=\"", linkEnd );
}
}
}
catch(IOException e)
{
System.out.println("Error: I/O Exception!");
}
}
private String processLink( String orig )
{
if( orig.startsWith("http://") )
return orig;
else
return ( currentSite + orig );
}
}
Program: To find keyword in a file
*/
//import statements
import java.io.*;
class MyException extends Exception {
MyException(String msg) {
System.out.println("===========================================================");
System.out.println(" Error: " + msg);
System.out.println("===========================================================");
}
}
public class FileSearch {
public static void main(String[] a) throws MyException {
int count=0;
int index=0;
try {
if(a.length < 2 ) {
System.out.println("Usage : java FileSearch <keyword> <filename>");
System.exit(0);
}
//Convert to lower case the searching keword
String lower2 = a[0].toLowerCase();
//System.out.println("System OS => " + System.getProperties("os.name"));
System.out.println("System OS => " + System.getProperties().getProperty("os.name"));
System.out.println("Java Home => " + System.getProperties().getProperty("java.home"));
File f = new File(a[1]);
if(f.exists()) {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String input;
while ((input = br.readLine()) != null) {
//Convert to lower case each line of file
String lower1 = input.toLowerCase();
int i=0;
while(i <= lower1.length()-lower2.length()) {
index = lower1.indexOf (lower2,i);
if ( index > -1) {
count++;
i=index;
}//if
i++;
}//inner while
}//outer while
System.out.println("===========================================================");
System.out.println("Total '" + lower2 + "' found in '" + a[1] + "' is " + count);
System.out.println("===========================================================");
}
else throw new MyException("File Not Found " + a[1]);
}//try
catch(Exception e) {
e.printStackTrace();
}
}//main
}//class
To find a file in the given drive
*/
import java.io.File;
import java.util.Date;
public class FindFile {
public static void main(String a[]) {
if(a.length < 2) {
System.out.println("\n\nUsage : java FindFile <dir_name> <filename>");
System.exit(0);
}
Date start = new Date();
System.out.println("\n\nFinding.......file " + a[1] + " \nPlease Wait.....!!");
System.out.println("\n\nResult := " + findFile(a[0], a[1]));
Date end = new Date();
System.out.print(end.getTime() - start.getTime());
System.out.println(" total milliseconds");
}
static public String findFile(String dir, String to_find) {
int i;
String results;
String dir_list[]=(new File(dir)).list();
for (i = 0; i < dir_list.length; i++) {
File to_test = new File(dir,dir_list[i]);
if (to_test.isDirectory()) {
results = findFile(to_test.getAbsolutePath(),to_find);
if (results.length() > 0) return results;
} else {
//System.out.println("Checking " + to_test.getName());
if ((to_test.getName()).equalsIgnoreCase(to_find))
return to_test.getAbsolutePath();
}
}
return "";
}
}
//import statements
//import java.awt.TextArea;
import java.awt.event.*;
import java.awt.*;
import java.io.File;
import java.io.*;
This simple class creates the Thread to copy one file content to other
and u have control over the copy process
*/
===========================================================
public class CT1 extends Frame implements ActionListener {
MyProcess myp = null;
Button create = new Button("Create");
Button cancel = new Button("Cancel");
Button quit = new Button("Quit");
CT1() {
create.addActionListener(this);
cancel.addActionListener(this);
quit.addActionListener(this);
Panel panel= new Panel();
panel.add(create);
panel.add(cancel);
panel.add(quit);
add(panel);
addWindowListener(new WinClosing());
setBounds(100, 100, 600, 500);
//pack();
setVisible(true);
}
public void actionPerformed(java.awt.event.ActionEvent e) {
String name = e.getActionCommand();
if(name.equals("Create")) {
myp = new MyProcess();
myp.start();
System.out.println("Inside Create");
System.out.println("isAlive() ===> " + myp.isAlive());
} else if(name.equals("Cancel")){
try {
if(myp != null) {
System.out.println("isAlive() ===> " + myp.isAlive());
Thread moribund = myp;
myp = null;
moribund.interrupt();
}
}catch(Exception ee) {
ee.printStackTrace();
}
System.out.println("Inside Cancel myp = " + myp);
}else if(name.equals("Quit")) {
System.exit(0);
}
}
//Main method
public static void main(String args[]) {
CT1 ct = new CT1();
}
}//CT class
class WinClosing extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}//class
class MyProcess extends Thread {
public void run(){
System.out.println("In myProcess...run()" );
String str;
try {
BufferedReader br = new BufferedReader(new FileReader("in.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
while ((str = br.readLine()) != null) {
System.out.println("Writing Word : " + str);
bw.write(str + System.getProperty("line.separator"));
try {
Thread.sleep(1000);
}catch(Exception e) {
e.printStackTrace();
}
}
bw.flush();
br.close();
bw.close();
} catch (FileNotFoundException fnfe) {
System.out.println(fnfe);
return;
} catch (IOException ioe) {
System.out.println(ioe);
}
}//run
}//MyProcess
/*class MyProcess extends Object implements Runnable {
private volatile boolean stopRequested;
private Thread runThread;
public void run() {
runThread = Thread.currentThread();
stopRequested = false;
System.out.println("In myProcess...run()" );
String str;
try {
BufferedReader br = new BufferedReader(new FileReader("in.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
while ((str = br.readLine()) != null && !stopRequested ) {
System.out.println("Writing Word : " + str);
bw.write(str + System.getProperty("line.separator"));
try {
Thread.sleep(1000);
} catch ( InterruptedException x ) {
Thread.currentThread().interrupt(); // re-assert interrupt
}
}//while write
bw.flush();
br.close();
bw.close();
} catch (FileNotFoundException fnfe) {
System.out.println(fnfe);
return;
} catch (IOException ioe) {
System.out.println(ioe);
}
}//run
public void stopRequest() {
stopRequested = true;
if ( runThread != null ) {
runThread.interrupt();
}
}
}*/
===========================================================
/*
Program to find CD Drive on a Computer
*/
import java.io.File;
import java.io.StringReader;
import java.io.FileOutputStream;
/**
This class used Detect the CD Drive name
and write it into a text file.
*/
public class CD_Drive {
public static void main(String[] args) {
String foundRNot =null;
int c;
try {
File[] roots = File.listRoots();
for (int i=1;i<roots.length;i++) {
System.out.println("Checking Drive : " + roots[i]);
foundRNot = findFile(roots[i].toString(),"autorun.ini");
if(foundRNot != null) {
System.out.println("\nCD Drive \" " + roots[i] + "\"");
//writeToFile();
StringReader strReader = new StringReader(roots[i].toString());
FileOutputStream fos = new FileOutputStream("D:\\jakarta-tomcat\\webapps\\NordCompo\\CD_Drive.txt");
while ((c = strReader.read()) != -1) {
fos.write((char) c);
}
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
}//main()
static public String findFile(String dir, String to_find) {
String fileList[] = (new File(dir)).list();
for (int i = 0; i < fileList.length; i++) {
File to_test = new File(dir,fileList[i]);
if (to_test.isFile()) {
if ((to_test.getName()).equalsIgnoreCase(to_find))
return to_test.getAbsolutePath();
}
}
return null;
}//method
}//class
/*
Program touse BufferedReader
*/
import java.io.*;
public class TestFOS {
public static void main(String args[]) {
int c;
try {
BufferedInputStream bis =
new BufferedInputStream(new FileInputStream("jrr.txt"));
FileOutputStream fos = new FileOutputStream("jrr.txt.copy");
while ((c = bis.read()) != -1) {
fos.write((char) c);
}
fos.close();
bis.close();
} catch (FileNotFoundException fnfe) {
System.out.println(fnfe);
return;
} catch (IOException ioe) {
System.out.println(ioe);
}
}
}
import java.io.*;
import java.sql.*;
import java.util.*;
import oracle.jdbc.driver.OracleTypes;
Connecting to Oracle DB using oracle driver
*/
public class OraDB1{
private static final int one = 1;
public static void main(String[] argv) {
Connection conn =null;
Statement stmt =null;
ResultSet rset=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Connecting to database Please Wait !!");
conn = DriverManager.getConnection("jdbc:oracle:thin:srini/sri@cyber:1521:cyber");
System.out.println("Connection Complete....");
stmt = conn.createStatement();
rset = stmt.executeQuery("SELECT * FROM tree");
while(rset.next()) {
System.out.println(rset.getString(1) + " " + rset.getString(2) + " " + rset.getString(3));
System.out.println(rset.getString(1) + " " + rset.getString(2) + " " + rset.getString(3));
System.out.println(rset.getString(1) + " " + rset.getString(2) + " " + rset.getString(3));
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}//main
}
import java.io.*;
import java.sql.*;
import java.util.*;
import oracle.jdbc.driver.OracleTypes;
/*
Connecting to Oracle DB using jdbs driver
*/
public class OraDB2 {
private static final int one = 1;
public static void main(String[] argv) {
Connection conn =null;
Statement stmt =null;
ResultSet rset=null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:malu","srini","srini");
stmt = conn.createStatement();
rset = stmt.executeQuery("SELECT * FROM tsal");
while(rset.next())
System.out.println(rset.getString(1) + " " + rset.getString(2) + " " + rset.getString(3));
System.out.println(rset.getString(1) + " " + rset.getString(2) + " " + rset.getString(3));
//System.out.println(rset.getString(1));
//System.out.println(rset.getString(1));
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}//main
}
import java.io.*;
import java.sql.*;
import java.util.*;
import oracle.jdbc.driver.OracleTypes;
/*
Calling a Stored Procedure From Oracle
*/
public class OraDB {
private static final int one = 1;
public static void main(String[] argv) {
Connection conn =null;
CallableStatement stmt =null;
ResultSet rset=null;
try {
if(argv.length == 0) {
System.out.println("\nUsage : java OraDB <Value>");
System.exit(0);
}
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Connecting to database Please Wait !!");
conn = DriverManager.getConnection("jdbc:oracle:thin:srini/sri@cyber:1521:cyber");
System.out.println("Connection Complete....");
System.out.println("\nCalling Procedure..");
stmt = conn.prepareCall("{ call oraDB.proc_oraDB(?,?) }");
stmt.setString(1,argv[0]);
stmt.registerOutParameter(2,OracleTypes.CURSOR);
stmt.execute();
rset = (ResultSet)stmt.getObject(2);
while(rset.next())
System.out.println(rset.getString(1) + " " + rset.getString(2) + " " + rset.getString(3));
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}//main
}
import java.io.*;
import java.sql.*;
import java.util.*;
//import
oracle.jdbc.driver.OracleTypes;
import oracle.sql.*;
import
oracle.jdbc.driver.*;
//import
oracle.jdbc.driver.OracleResultSet;
public class Java_Oracle {
private static final int one = 1;
public static void main(String[] argv) {
Connection conn
=null;
CallableStatement stmt =null;
ResultSet rset=null;
try {
/*
Connection Code
*/
System.out.println("\n\nConnecting......to
Oracle....Wait !!\n\n");
Class.forName("oracle.jdbc.driver.OracleDriver");
conn =
DriverManager.getConnection("jdbc:oracle:thin:srini/sri@cyber:1521:cyber");
System.out.println("Connected !!\n\n");
/*
This call gets the Cursor
*/
stmt
= conn.prepareCall("{ call Java_Oracle.proc_oraDB(?,?,?,?,?,?,?)
}");
//stmt.setString(1,"Soma");
stmt.registerOutParameter(1,OracleTypes.CHAR);
stmt.registerOutParameter(2,OracleTypes.DATE);
stmt.registerOutParameter(3,OracleTypes.DECIMAL);
stmt.registerOutParameter(4,OracleTypes.DOUBLE);
stmt.registerOutParameter(5,OracleTypes.FLOAT);
stmt.registerOutParameter(6,OracleTypes.INTEGER);
stmt.registerOutParameter(7,OracleTypes.CURSOR);
//Excecution
stmt.execute();
//Results
//String c =
(String) stmt.getObject(1);
java.util.Date date = stmt.getDate(2);
float f = stmt.getFloat(3); //Decimal
double d =
stmt.getDouble(4);
float f1 =
stmt.getFloat(5);
int i = stmt.getInt(6);
//System.out.println("Char => "+ c);
System.out.println("Date => "+ date);
System.out.println("Decimal => "+ f);
System.out.println("Double => "+ d);
System.out.println("Float => "+ f1);
System.out.println("Int => "+ i);
System.out.println("Cursor => \n");
rset = (ResultSet)stmt.getObject(7);
OracleResultSet ors = (OracleResultSet) rset;
/*while(rset.next())
System.out.println(rset.getString(1) + " " + rset.getString(2)
+ " " + rset.getString(3));*/
CharacterSet cs=null;
while(ors.next()) {
System.out.println(ors.getString(1) + " " + ors.getString(2) +
" " + ors.getString(3) + " " + ors.getCHAR(4));
Datum rawdatum = ors.getOracleObject(4);
cs = ((CHAR)rawdatum).getCharacterSet();
break;
}
System.out.println("Char Set ==> " + cs);
ors.close();
stmt.close();
conn.close();
}catch (Exception
e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}//main
}
import java.sql.*;
import oracle.jdbc.*;
public class StProcExample {
public static void main(String[] args) throws SQLException {
int ret_code;
Connection conn = null;
CallableStatement pstmt = null;
try {
//Load and register Oracle driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
System.out.println("Connecting to Database Srini....WAIT!!");
//Establish a connection
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:srini","scott","tiger");
System.out.println("Connected!!");
int i_deptno = 10;
System.out.println("\n\nResult!!\n\n");
pstmt = conn.prepareCall("{call p_highest_paid_emp(?,?,?,?)}");
pstmt.setInt(1, i_deptno);
pstmt.registerOutParameter(2, Types.INTEGER);
pstmt.registerOutParameter(3, Types.VARCHAR);
pstmt.registerOutParameter(4, Types.FLOAT);
pstmt.executeUpdate();
int o_empno = pstmt.getInt(2);
String o_ename = pstmt.getString(3);
float o_sal = pstmt.getFloat(4);
System.out.print("The highest paid employee in dept "+i_deptno+" is: "+o_empno+" "+o_ename+" "+o_sal);
pstmt.close();
conn.close();
} catch (SQLException e) {
ret_code = e.getErrorCode();
System.err.println(ret_code + e.getMessage());
conn.close();
}//catch
}//main
}//class
/**
#######################
Procedure
#######################
CREATE OR REPLACE PROCEDURE p_highest_paid_emp
(ip_deptno NUMBER,
op_empno OUT NUMBER,
op_ename OUT VARCHAR2,
op_sal OUT NUMBER)
IS
v_empno NUMBER;
v_ename VARCHAR2(20);
v_sal NUMBER;
BEGIN
SELECT empno, ename, sal
INTO v_empno, v_ename, v_sal
FROM emp e1
WHERE sal = (SELECT MAX(e2.sal)
FROM emp e2
WHERE e2.deptno = e1.deptno
AND e2.deptno = ip_deptno)
AND deptno = ip_deptno;
op_empno := v_empno;
op_ename := v_ename;
op_sal := v_sal;
END;
/
**/
import java.sql.*;
import java.io.*;
import oracle.jdbc.driver.*;
public class RefCursorExample {
public static void main(String[] args) throws SQLException, IOException {
int ret_code;
Connection conn = null;
CallableStatement cstmt = null;
ResultSet rset = null ;
try {
System.out.println("Connecting to Database Srini....WAIT!!");
//Load and register Oracle driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
//Establish a connection
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:srini", "scott", "tiger");
System.out.println("Connected!!");
int i_deptno = 10;
cstmt = conn.prepareCall("{call pkg_test.sp_get_list(?,?)}");
// Register the OUT parameter of the PL/SQL function as
// a OracleTypes.CURSOR datatype
cstmt.setInt(1, i_deptno);
cstmt.registerOutParameter(2,OracleTypes.CURSOR);
//cstmt.executeUpdate();
cstmt.executeQuery();
// Obtain the cursor returned by the PL/SQL function using getObject()
// and cast it to the ResultSet object.
rset = (ResultSet) cstmt.getObject(2);
System.out.println("\nEMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO");
System.out.println("========================================================");
while (rset.next()) {
System.out.println(rset.getInt(1)+" "+ rset.getString(2)+" "+rset.getString(3)+" "+rset.getInt(4)+" "+rset.getDate(5)+" "+rset.getFloat(6)+" "+rset.getFloat(7)+" "+rset.getInt(8)+"\n");
}
System.out.println("========================================================");
rset.close();
cstmt.close();
conn.close();
} catch (SQLException e) {
ret_code = e.getErrorCode();
System.err.println(ret_code + " " + e.getMessage());
conn.close();
}
}//main
}//class
/**
#######################
Package Spec
#######################
CREATE OR REPLACE PACKAGE pkg_test AS
TYPE cur_result IS REF CURSOR;
PROCEDURE sp_get_list (v_in_dept_number IN NUMBER,list OUT cur_result);
END pkg_test;
/
#######################
Package Body
#######################
CREATE OR REPLACE PACKAGE BODY pkg_test AS
PROCEDURE sp_get_list(v_in_dept_number IN NUMBER,list OUT cur_result)IS
BEGIN
OPEN list FOR
SELECT *
FROM emp
WHERE deptno = v_in_dept_number;
END sp_get_list;
END pkg_test;
/
**/