Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
PART 24 Java Network Applications 24.1 Java Socket Programming A socket is a software endpoint that establishes bidirectional communication between a server program and one or more client programs. A server program typically provides resources to a network of client programs. Client programs send requests to the server program, and the server program responds to the request. Using threads, a multi-threaded server program can accept a connection from a client, start a thread for that communication, and continue listening for requests from other clients. The java.net package provides support for the two common network protocols: TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP. UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications. When the connection is made, the server creates a socket object on its end of the communication. The client and server can now communicate by writing to and reading from the socket. The following steps occur when establishing a TCP connection between two computers using sockets: 1. The server instantiates a ServerSocket object, denoting which port number communication is to occur on. 2. The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port. 3. A client instantiates a Socket object, specifying the server name and port number to connect to. 4. The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, the client now has a Socket object capable of communicating with the server. After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream. TCP is a two way communication protocol, so data can be sent across both streams at the same time. SimpleServer.Java import java.net.*; import java.io.*; public class SimpleServer extends Thread { private ServerSocket serverSocket; public SimpleServer(int port) throws IOException { serverSocket = new ServerSocket(port); serverSocket.setSoTimeout(100000); } public void run() { while(true) { try { System.out.println("Waiting for client on port "+ serverSocket.getLocalPort()); Socket server = serverSocket.accept(); System.out.println("Just connected to " + server.getRemoteSocketAddress()); DataInputStream in = new DataInputStream(server.getInputStream()); System.out.println(in.readUTF()); DataOutputStream out = new DataOutputStream(server.getOutputStream()); out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!"); server.close(); }catch(SocketTimeoutException s) { System.out.println("Socket timed out!"); break; }catch(IOException e) { e.printStackTrace(); break; } } } public static void main(String [] args) { try { // use TCP 6666 port Thread t = new SimpleServer(6666); t.start(); }catch(IOException e) { e.printStackTrace(); } } } SimpleClient.Java import java.net.*; import java.io.*; public class SimpleClient { public static void main(String [] args) { String serverName = "localhost"; int port = 6666; try { System.out.println("Connecting to " + serverName + " on port " + port); Socket client = new Socket(serverName, port); System.out.println("Just connected to " + client.getRemoteSocketAddress()); OutputStream outToServer = client.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); out.writeUTF("Hello from " + client.getLocalSocketAddress()); InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); System.out.println("Server says " + in.readUTF()); client.close(); }catch(IOException e) { e.printStackTrace(); } } } 24.2 Sending E-mail To send an email using your Java Application is simple enough but to start with you should have JavaMail API installed on your machine. You can download latest version of JavaMail from Java's standard website. http://www.oracle.com/technetwork/java/javamail/index-138643.html Download and unzip files, you will find a number of jar files for both the applications. You need to add mail.jar files in your CLASSPATH (In Eclipse drag and drop into src folder, right click mail.jar and select Build Path-> Add to Build Path) Here is an example to send a simple email via GOOGLE GMAIL SMTP SERVER. Here it is assumed that your localhost is connected to the internet and capable enough to send an email. import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendEmail { public static void main(String[] args) { // Sender's email ID needs to be mentioned String from = "[email protected]"; String pass = "123456"; // Recipient's email ID needs to be mentioned. String to = "[email protected]"; String host = "smtp.gmail.com"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", host); properties.put("mail.smtp.user", from); properties.put("mail.smtp.password", pass); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Now set the actual message message.setText("This is actual message"); // Send message Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } } } 24.3 Java Applets An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API. There are some important differences between an applet and a standalone Java application, including the following: An applet is a Java class that extends the java.applet.Applet class. A main() method is not invoked on an applet, and an applet class will not define main(). Applets are designed to be embedded within an HTML page. When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's machine. A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment. The JVM on the user's machine creates an instance of the applet class and invokes various methods during the applet's lifetime. Life Cycle of an Applet: Four methods in the Applet class give you the framework on which you build any serious applet: init: This method is intended for whatever initialization is needed for your applet. start: This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages. paint: Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. stop: This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet. destroy: This method is only called when the browser shuts down normally. "Hello, World" Applet: The following is a simple applet named HelloWorldApplet.java: import java.applet.*; import java.awt.*; public class HelloWorldApplet extends Applet { public void paint (Graphics g) { g.drawString ("Hello World", 25, 50); } } Applet CLASS: Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods that a derived Applet class may call to obtain information and services from the browser context. Invoking an Applet: An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser. The <applet> tag is the basis for embedding an applet in an HTML file. Below is an example that invokes the "Hello, World" applet: <html> <title> Hello World Applet</title> <applet code="HelloWorldApplet.class" width="320" height="120"> </applet> </html> The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and height are also required to specify the initial size of the panel in which an applet runs. The applet directive must be closed with a </applet> tag. Specifying Applet Parameters: The following example demonstrates how to make an applet respond to setup parameters specified in the document. The Applet.getParameter() method fetches a parameter given the parameter's name (the value of a parameter is always a string). import java.applet.*; import java.awt.*; public class appletParameter extends Applet { private String strDefault = "Hello! Java Applet."; public void paint(Graphics g) { String strParameter = getParameter("Message"); if (strParameter == null) strParameter = strDefault; setBackground(Color.GREEN); g.drawString(strParameter, 50, 25); } } The following is an example of an HTML file with an appletParameter.class embedded in it. The HTML file specifies both parameters to the applet by means of the <param> tag. <html> <title>Applet Test</title> <h1> This is the applet: </h1> <applet code="appletParameter.class" width="800" height="100"> <param name="message" value="This is HTML parameter Text."> </applet> </html> Note: Parameter names are not case sensitive. PART 25 Java Database Connectivity (JDBC) 25.1 What is JDBC ? JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks commonly associated with database usage: Making a connection to a database Creating SQL or MySQL statements Executing that SQL or MySQL queries in the database Viewing & Modifying the resulting records 25.2 JDBC Architecture The JDBC Architecture consists of two layers: JDBC API: This provides the application-to-JDBC Manager connection. JDBC Driver API: This supports the JDBC Manager-to-Driver Connection. Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application: 25.3 Common JDBC Components The JDBC API provides the following interfaces and classes: DriverManager: This class manages a list of database drivers. Driver: This interface handles the communications with the database server. You will interact directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. Connection : This interface with all methods for contacting a database. Statement : You use objects created from this interface to submit the SQL statements to the database. ResultSet: These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data. SQLException: This class handles any errors that occur in a database application. 25.6 Install Database Install a database that is most suitable for you. You can have plenty of choices and most common are: MySQL DB: MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation. In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier. Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. PostgreSQL DB: PostgreSQL is an open source database. You can download it fromPostgreSQL Official Site. The Postgres installation contains a GUI based administrative tool called pgAdmin III. JDBC drivers are also included as part of the installation. Oracle DB: Oracle DB is an commercial database. Oracle installation includes a GUI based administrative tool called Enterprise Manager. JDBC drivers are also included as part of the installation. 25.7 Set up MySQL Database For this tutorial we are going to use MySQL database. When you install any of the above database, its administrator ID is set to root and gives provision to set a password of your choice. Using root ID and password you can either create another users ID and password or you can use root ID and password for your JDBC application. There are various database operations like database creation and deletion, which would need administrator ID and password. 25.7.1 Create Database To create the EMP database, use the following steps: Step 1: Open a Command Prompt and change to the installation directory as follows: C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin> Note: The path to mysqld.exe may vary depending on the install location of MySQL on your system. Step 2: Start the database server by executing the following command, if it is already not running. C:\Program Files\MySQL\bin>mysqld C:\Program Files\MySQL\bin> Step 3: Create the EMP database by executing the following command C:\Program Files\MySQL\bin> mysqladmin create EMP -u root -p Enter password: ******** C:\Program Files\MySQL\bin> 25.7.2 Create Table To create the Employees table in EMP database, use the following steps: Step 1: Open a Command Prompt and change to the installation directory as follows: C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin> Step 2: Login to database as follows C:\Program Files\MySQL\bin>mysql -u root -p Enter password: ******** mysql> Step 3: Create the table Employee as follows: mysql> use EMP; mysql> create table Employees -> ( -> id int not null, -> age int not null, -> first varchar (255), -> last varchar (255) -> ); Query OK, 0 rows affected (0.08 sec) mysql> 25.7.3 Create Data Records Finally you create few records in Employee table as follows: mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali'); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal'); Query OK, 1 row affected (0.00 sec) mysql> Now you are ready to start experimenting with JDBC. Next tutorial would give your a sample example on JDBC Programming. 25.8 Creating JDBC Application There are following six steps involved in building a JDBC application: Import the packages . Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. Register the JDBC driver: Requires that you initialize a driver so you can open a communications channel with the database. Open a connection: Requires the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database. Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to the database. Extract data from result set: Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set. Clean up the environment: Requires explicitly closing all database resources. This sample example can serve as a template when you need to create your own JDBC application in the future. //STEP 1. Import required packages import java.sql.*; public class FirstExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/EMP"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql); //STEP 5: Extract data from result set while(rs.next()){ //Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); //Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } //STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end FirstExample Now let us compile above example as follows: C:\>javac FirstExample.java C:\> When you run FirstExample, it produces following result: C:\>java FirstExample Connecting to database... Creating statement... ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal C:\>