Sunteți pe pagina 1din 19

STREAMS AND COLLECTIONS

// Implementing array list collection class


import java.util.*; public class ArrayListDemo { public static void main(String args[]) { ArrayList al = new ArrayList(); al.add(10); al.add(11); al.add(12); al.add(20); System.out.println("\n Array List Is : " + al); System.out.println("\n Size = " + al.size()); al.remove(2); System.out.println("\n Array List Is : " + al); System.out.println("\n Size = " + al.size()); } }

// file1.java Using character stream //FileReader


import java.io.*; class file1 { public static void main(String args[]) { File infile = new File("d:\\file1.java"); FileReader ins = null; try { ins = new FileReader(infile); int ch; while( (ch = ins.read() ) != -1) { char c = (char)ch; System.out.print(c); } ins.close(); } catch(IOException e) { } }/// end main }// end class

// file2.java Using ByteStreams //FileInputStream


import java.io.*; class file3 { public static void main(String args[]) { FileInputStream infile = null; int temp; try { infile = new FileInputStream("d:\\file3.java"); while( (temp = infile.read() ) != -1) { System.out.print((char)temp); } infile.close(); } catch(IOException e) { } }/// end main }// end class

SOCKET PROGRAMMING

Section 2 Socket Programming Topic 1 Connecting to a Server :The server software is continuously running on the remote machine , waiting for any network traffic that wants to chat with port no 13. When the operating system on remote computer receives a network package that contains a request to connect to port no 13 , it wakes up the listening server process and establish the connection. The connection stays up until it is terminated by any by one of the parties. Fig 3-2 Program : Listing 3-1 import java.io.*; import java.net.*; import java.util.*; /** * This program makes a socket connection to the atomic clock in Boulder, Colorado, and prints the * time that the server sends.

*/ public class SocketTest { public static void main(String[] args) { try { Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13); try { InputStream inStream = s.getInputStream(); Scanner in = new Scanner(inStream); while (in.hasNextLine()) { String line = in.nextLine(); System.out.println(line); } } finally { s.close(); } } catch (IOException e) { e.printStackTrace(); } } } OUTPUT-1 run: 55613 11-02-21 06:11:11 00 0 0 907.6 UTC(NIST) * BUILD SUCCESSFUL (total time: 2 seconds) OUTPUT-1 55613 11-02-21 06:11:40 00 0 0 258.3 UTC(NIST) * BUILD SUCCESSFUL (total time: 1 second) Explanation : The first line opens a socket ( which is an abstraction for the network software that enables communication out and into this program ). We pass the remote address and the port number to the socket constructor. If the connection fails then the UnknownHostException is thrown. If there is another problem then an IOException is thrown. Because UnknownHostException is a subclass of IOException we just catch the superclass.

Once the socket is open The getInputstream in java.net.Socket returns an InpuitStream object Once you get the stream this program simply prints each line. Topic-2 Socket Timeouts : You can decide what time value is reasonable for your particular application. Then call the setSoTimeout method to set the timeout value (in milliseconds) Socket s = new Socket(); s.setSoTimeout(10000); If the host is unreachable, your application waits for a long time and you are at the mercy of the underlying operating system to time out eventually. If the timeout value is set for the socket then all subsequent read and write operations throws SocketTimeoutException when the timeout has been reached before the operation has completed its work.

Topic 3 Internet Addresses :The java.net package support IPv6 Internet addresses. You can use InetAddress class if you need to convert host names and internet addresses(IP addresses). The static method getByName returns an InetAddress object of a host for example: InetAddress address = InetAddress.getByName(time-A.timefreq.bldrdoc.gov); It returns InetAddress object that contain 132.163.4.104 You can get bytes with getAddress method Byte[] addressbytes = address.getAddress(); Use the static method getLocalHost to get the address of your local host. InetAddress address = InetAddress.getLocalHost(); Listing 3-2: InetAddressTest.java

import java.net.*; public class InetAddressTest { public static void main(String[] args) { try { if (args.length > 0) { String host = args[0]; InetAddress[] addresses = InetAddress.getAllByName(host); for (InetAddress a : addresses) System.out.println(a); } else { InetAddress localHostAddress = InetAddress.getLocalHost(); System.out.println(localHostAddress); } } catch (Exception e) { e.printStackTrace(); } } } Topic 3 Implementing Servers and clients : We develop a server that can send and receive information to or from clients. Once you start the server program it waits for a client to connect to its port.( the key in the communication is port number) If a client know it then it can connect to server otherwise not. The command ServerSocket sc = new ServerSocket (1096) ; Establish a server that monitors ports 1096. The command Socket client = sc.accept(); Tells the program to wait indefinitely until a client connects to that port. Once someone connects to this port by sending correct request over the network(correct port no) this method returns a Socket object that represent the connection that was made.

In the program everything that the server sends becomes the input of the client and displays on its screen. All the output from the client becomes the input to the server and displayed on its screen. Program from manual Client.java and Server.java

Socket Programming

package Sock; import java.io.*; import java.net.*; public class Client { public static void main(String args[]) { try { Socket server; String str=""; DataInputStream d=new DataInputStream(System.in); PrintStream toserver; BufferedReader fromserver; server=new Socket("192.168.0.204",1096); InputStreamReader isr=new InputStreamReader(server.getInputStream()); fromserver= new BufferedReader(isr); toserver=new PrintStream(server.getOutputStream()); while(true) { str=":"+d.readLine(); toserver.println(str); str=fromserver.readLine(); System.out.println(str); } } catch(Exception e) { System.out.println(e); }

} }

package Sock; import java.io.*; import java.net.*; public class Server { public static void main(String args[]) { ServerSocket sc; Socket client; DataInputStream d; PrintStream toClient; BufferedReader fromClient; String str=""; try { d=new DataInputStream(System.in); sc=new ServerSocket(1096); System.out.println("ServerStarted"); client=sc.accept(); InputStreamReader isr=new InputStreamReader(client.getInputStream()); fromClient=new BufferedReader(isr); toClient=new PrintStream(client.getOutputStream()); while(true) { str=fromClient.readLine(); System.out.println(str); str=":"+d.readLine(); toClient.println(str); } } catch(Exception e) { System.out.println(e); } } }

Topic 4 Half Close :The half-close provide the ability for one end of a socket connection to terminate its output while still receiving data from the other end. You close the output stream of a socket , thereby indicating to the server the end of the requested data , but keep the input stream open. The protocol is useful only for one-shot service such as HTTP where the client connects, issues its request, catches the response and then disconnects . This is done by Socket.shutdownOutput(); Sets the output stream to end of stream. Topic 5 Making URL Connection Java support many classes and interfaces to support URL(Uniform Resource Locator) connections .The important classes are 1. URL class. 2. URI class 3. URLConnection class 1. Class URI:- Every URL is a URI but every URI is not a URL. It provides several methods to deal with resources over the internet. 2. Class URL :- URL is a combination of four things (a) the protocol (b) host name or host IP Port number (d) the file path For example : http://java.sun.com/j2se/1.4.2/docs/api/java/net/URL.htm Here :1. http is the protocol, 2. java.sun.com is the host name, 3. j2se/1.4.2/docs/api/java/net/URL.htm is the file path. 4. If port no is not given the default port number is used. The default port number for http is 80. The Constructors of URLConnection :- 4 constructors 1. URL(String protocolName,String hostname ,int portno,String FileName) throws MalFormedURLException

2. URL(String protocolName,String hostname ,String FileName) throws MalFormedURLException 3. URL(String str) MalFormedURLException 4. URL(String urlContext,String str) Methods of URL class:-

Method Name
String getProtocol() String getHost() int getPort() String getFile() URLConnetion openConnetion throws IOException InputStream openStream() throws IOException Object getContent() throws IOException Example ://URL demo class import java.net.*;

Used For
Give protocol used Give host name as string Give port number Give the file name Returns an URLConnection object. Open a connection and returns an object of input stream Return an object type. The type is dependent on URL. If the target URL is an Image then an object of type image is returned.

public class URLDemo { public static void main(String args[]) { try { URL http_url = new URL("http://www.rediff.com/sports"); System.out.println(" Protocol Name" + http_url.getProtocol()); System.out.println("Port Number = " + http_url.getPort()); System.out.println(" Host Name = " + http_url.getHost()); System.out.println("File Name = " + http_url.getFile()); } catch(Exception e) { } } } 3. Class URLConnection :It provide some methods by which u can send some information to the server.

Constructor is : URLConnection(URL urlstring) URL http_url = new URL(http://www.indianrailway.gov.in_); URLConnection urlc = new URLConnection(http_url); OR URL http_url = new URL(http://www.indianrailway.gov.in_); URLConnection urlc = http_url.openConnection(); Four Steps :1. Obtain an object of URLConnection from openConnection() method of URL. 2. You can set any request properties. 3. Connect to resource using connect() method 4. Query for the header information 5. Now you can access all the data resource. // Url connection example import java.io.*; import java.net.*; import java.util.Date; public class URLConnectiondemo { public static void main(String args[]) { try { URL url = new URL("http://www.indianrail.gov.in"); URLConnection urlconn = url.openConnection(); urlconn.connect(); System.out.println("Content Type " + urlconn.getContentType()); System.out.println("Content Length = " + urlconn.getContentLength()); } catch(Exception e) { System.out.println(e); } } }

UNIT 3 JDBC

DataBase : Collection of tables Provide efficient storage and retrieval of data. There are a no of vendors or database packages in the market Eg Oracle, DB2,Sybase,Microsoft SQL Server, MS Access etc JDBC is used to connect with the database. JDBC: A standard API to work on data source. It provide all database related operations such as Making connection, process database result, and also support heterogeneous environments. It provides an interface to connect with databases. It provides a group of classes and interfaces that facilitates to easy access to database and perform operations on database. JDBC Drivers : Various vendors of databases provides their own APIs (vendor specific APIs) to interact with databases. Its the responsibility of the intermediate layer to make the native calls to these APIs. The JDBC driver will work as a middle layer between the data source and the application. Types of jdbc drivers page 83 Fig 3.1 and 3.2 Kanika Lakhani JDBC Architectures fig 3.2 Kanika Lakhani JDBC Clients Fig 3.3 Kanika Lakhani To use JDBC drivers the developer can use four approaches 1. Type -1 JDBC-ODBC Bridge 2. Type-2 Native API Partly Java Driver 3. Type-3 JDBC-Net Pure java Driver 4. Type-4 Native-Protocol Pure Java Driver Type -1 JDBC-ODBC Bridge : It uses Open database Connectivity ODBC as the prime interface to data source. The type-1 driver provides a bridge between the JDBC API and ODBC API . The bridge is responsible to convert the JDBC calls to corresponding ODBC calls and finally request to data source using ODBC libraries, that must be required at client side.

J2SE contains the classes for JDBC-ODBoC bridge. But You have to create Data Source Name using ODBC manager. Fig 3.4 Type-2 Native API Partly Java Driver : Here the client makes the JDBC calls and these calls are interpreted into vendor specific APIs, finally from vendor specific APIs to database to perform the operation on it. Database process the request and send the result back through the vendor specific API which will forwarded back to the JDBC driver. Now here JDBC driver will convert the response(result) to the JDBC standards and send to java application The driver can be used where there is the need of high performance and large transaction volume. Fig 3.5 Type-3 JDBC-Net Pure java Driver : Type 3 driver work as middleware server between a no of java clients to multiple vendor database. The client application sends the request to intermediate data access server, by making the JDBC call through a JDBC driver. The intermediate data access server completes the request to the database using native driver. Fig 3.6 Type-4 Native-Protocol Pure Java Driver : Type 4 driver converts JDBC API request directly to networking protocols of vendor specific . By making socket connection with database they communicate with the database. Fig 3.7 Structured Query Language (SQL) :It is standard query language to the Relational databases.It use DML and DDL statements. 1. DML Data Manipulation Language :It is used to manipulate the database. It uses the commands such as Select, insert, delete and update. (a) Select Commands :Eg. Select * from Employee where salary > 50000 (b) Insert :Eg Insert into employee(empid,firstname) values(1111,Vijay Kumar)

(c) Delete :Eg. Delete from employee where firstname = Vijay Kumar (d) Update :Eg. Update employee set salary = salary + 5000 where firstname = Vijay 2. DDL Data Definition Language :It is used to define the database. It uses the commands such as create table, drop table and alter table Create Table :Eg. Create table <table name> (<comumn name> datatype [size] ) Drop Table :It is used to drop table from database . Eg. Drop table <table name> Alter Table :It is used to add column, to redefine column, to add integrity constraint etc. Steps to add an ODBC data source( Steps to define a data source name) : Press start button and type ODBC to open odbc connection manager. Click on add Select edit Select data source name Select the driver Locate the database Click OK and Apply. Now you can use this Data Source Name to connect with that database in your program.

Program No. 5 Java Database Connectivity // Select *


package jdbc; import java.sql.*; import java.lang.*; public class Base { public static void main(String[] args) { // TODO Auto-generated method stub try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:Login1"); Statement stmt=con.createStatement(); String s="Select * from College where course Like '%e'"; ResultSet rs=stmt.executeQuery(s); while(rs.next()) { String st=rs.getString("course"); System.out.println(st); } con.close(); } catch(Exception ex) { System.out.println("there is an exception"+ex); } }// end main }// end class

// Inserting a row
import java.sql.*; import java.lang.*; public class insert1 { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:vinod"); Statement stmt=con.createStatement(); String s="insert into student(roll_no,student_name) values(110,'Rohit')"; int n= stmt.executeUpdate(s); System.out.println("Insert Successful" + n + "Row Inserted"); con.close(); } catch(Exception ex) { System.out.println("there is an exception"+ex); }

}// end main }// end class

// Executing Prepared Statements


import java.sql.*; import java.lang.*; public class prepare { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:vinod"); Statement stmt=con.createStatement(); String str = "select * from student where roll_no > ?"; PreparedStatement ps = con.prepareStatement(str); ps.setInt(1,105); String s="Select * from student"; ResultSet rs=ps.executeQuery(); while(rs.next()) { System.out.println(""); String st=rs.getString("roll_no"); System.out.print("\t" + st); st=rs.getString("student_name"); System.out.print("\t" + st); } System.out.println(""); con.close(); } catch(Exception ex) { System.out.println("there is an exception"+ex); } }// end main }// end class

// resultset metadata
import java.sql.*; import java.lang.*; public class metadata1 { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:vinod"); Statement stmt=con.createStatement(); String s="Select * from student"; ResultSet rs=stmt.executeQuery(s); // metadata of resultset ResultSetMetaData rsmd=rs.getMetaData( ); int count = rsmd.getColumnCount( ); System.out.println("No Of Columns = " + count); System.out.println(""); con.close(); } catch(Exception ex) { System.out.println("there is an exception"+ex); } }// end main }// end class

S-ar putea să vă placă și