Test

Powered by Blogger.

Wednesday, 18 July 2012

JDBC basics

The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database.




JDBC helps you to write java applications that manage these three programming activities:
  1. Connect to a database
  2. Send queries and update statements to the database
  3. Retrieve and process the results with database.

     
     
     
    Connection con = DriverManager.getConnection
               ( "jdbc:myDriver:wombat", "myLogin","myPassword");
         
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
    while (rs.next()) {
     int x = rs.getInt("a");
     String s = rs.getString("b");
     float f = rs.getFloat("c");
     }
    This short code fragment instantiates a DriverManager object to connect to a database driver and log into the database, instantiates a Statement object that carries your SQL language query to the database; instantiates a ResultSet object that retrieves the results of your query, and executes a simple while loop, which retrieves and displays those results.



JDBC includes four components:
  1. The JDBC API 

    The JDBC™ API provides programmatic access to relational data from the Java™ programming language. Using the JDBC API, applications can execute SQL statements, retrieve results, and propagate changes back to an underlying data source. The JDBC API can also interact with multiple data sources in a distributed, heterogeneous environment.


    The JDBC API is part of the Java platform, which includes the
    Java™ Standard Edition (Java™ SE ) and the Java™ Enterprise Edition (Java™ EE). The JDBC 4.0 API is divided into two packages: java.sql and javax.sql. Both packages are included in the Java SE and Java EE platforms.

  2. JDBC Driver Manager 

    The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture.

    The Standard Extension packages javax.naming and javax.sql let you use a DataSource object registered with a Java Naming and Directory Interface™ (JNDI) naming service to establish a connection with a data source. You can use either connecting mechanism, but using a DataSource object is recommended whenever possible.
  3. JDBC Test Suite

    The JDBC driver test suite helps you to determine that JDBC drivers will run your program. These tests are not comprehensive or exhaustive, but they do exercise many of the important features in the JDBC API.
  4. JDBC-ODBC Bridge

    The Java Software bridge provides JDBC access via ODBC drivers. Note that you need to load ODBC binary code onto each client machine that uses this driver. As a result, the ODBC driver is most appropriate on a corporate network where client installations are not a major problem, or for application server code written in Java in a three-tier architecture.
This Trail uses the first two of these these four JDBC components to connect to a database and then build a java program that uses SQL commands to communicate with a test Relational Database. The last two components are used in specialized environments to test web applications, or to communicate with ODBC-aware DBMSs.

JDBC Architecture

Two-tier and Three-tier Processing Models

The JDBC API supports both two-tier and three-tier processing models for database access.

Figure 1: Two-tier Architecture for Data Access.



In the two-tier model, a Java applet or application talks directly to the data source. This requires a JDBC driver that can communicate with the particular data source being accessed. A user's commands are delivered to the database or other data source, and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. The network can be an intranet, which, for example, connects employees within a corporation, or it can be the Internet.

In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive because the middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages.
Figure 2: Three-tier Architecture for Data Access.
The DBMS-proprietary protocol provides two-way communication between the database server and the server machine. HTTP, RMI, CORBA or other calls provide two way communication between the server machine and the client machine

Until recently, the middle tier has often been written in languages such as C or C++, which offer fast performance. However, with the introduction of optimizing compilers that translate Java bytecode into efficient machine-specific code and technologies such as Enterprise JavaBeans™, the Java platform is fast becoming the standard platform for middle-tier development. This is a big plus, making it possible to take advantage of Java's robustness, multithreading, and security features.

With enterprises increasingly using the Java programming language for writing server code, the JDBC API is being used more and more in the middle tier of a three-tier architecture. Some of the features that make JDBC a server technology are its support for connection pooling, distributed transactions, and disconnected rowsets. The JDBC API is also what allows access to a data source from a Java middle tier.

Storing image in db using jdbc

Assuming you have a table with a blob field and you want to save a file and store it in the database table or you want to read from a blob object stored in a database, you can use these below java code snippets to write file and read file from database.
The sample table is created as below to have a blob field to store file.


CREATE TABLE t1 (c1 INT PRIMARY KEY NOT NULL, c2 BLOB(5M));


Then use the below code snippet to insert an image file as follows.
 
PreparedStatement pstmt = conn.prepareStatement ("INSERT INTO t1 VALUES (?,?)");
pstmt.setInt (1, 100);
File fBlob = new File ( "image1.gif" );
FileInputStream is = new FileInputStream ( fBlob );
pstmt.setBinaryStream (2, is, (int) fBlob.length() );
pstmt.execute ();
...

 

Retrieving a BLOB or in other words retrieving the image file stored in the database as follows:
 
Statement stmt = conn.createStatement ();
ResultSet rs= stmt.executeQuery("SELECT * FROM t1");
while(rs.next()) {
int val1 = rs.getInt(1);
InputStream val2 = rs.getBinaryStream(2);
...
} rs.close();

sending mail through java

SENDING MAIL THROUGH JAVA
You can use the JavaMail API to send emails from your Java application. Though the JavaMail API allows you to do many things including the ability to retrieve and read the emails or sending emails etc, this sample java program demonstrates how to send email from your Java application. Remember to change the email host (String host) to your email server host, otherwise it won't work. import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SimpleSendEmail {
public static void main(String[] args) {
// Collect the necessary information to send a simple message
// Make sure to replace the values for host, to, and from with
// valid information.
// host - must be a valid smtp server that you currently have
// access to.
// to - whoever is going to get your email
// from - whoever you want to be. Just remember that many smtp
// servers will validate the domain of the from address
// before allowing the mail to be sent.

String host = "server.myhost.com";
String to = "YourFriend@someemail.com";
String from = "Me@myhost.com";
String subject = "My First Email";
String messageText = "I am sending a message using the"
+ " JavaMail API.\n"
+ "Here type your message.";
boolean sessionDebug = false;
// Create some properties and get the default Session.
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
Session session = Session.getDefaultInstance(props, null);
// Set debug on the Session so we can see what is going on
// Passing false will not echo debug info, and passing true
// will.

session.setDebug(sessionDebug);
try {
// Instantiate a new MimeMessage and fill it with the
// required information.
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
// Hand the message to the default transport service
// for delivery.
Transport.send(msg);
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
}

Wednesday, 11 July 2012

JDBC

Introduction to JDB


Java started as an elegant and promising Web programming language. Thereafter, its transition to hard-core computing environment
 is a phenomenal feat. Apart from its significance on client-side programming, Java has been outstanding in developing mission-critical
 enterprise-scale applications and hence its immense contribution to server-side computing gets all round attention. Thus Java as
 a programming language for enterprise computing has been doing well for the past couple of years. As every enterprise includes a
 database, Sun Microsystems has to come with necessary features for making Java to shine in database programming as well.
 In this overview, we discuss about the role of Java Database Connectivity in accomplishing database programming with ease.



Database Programming with Java
Database Programming with Java

Java provides database programmers some distinct advantages, such as easy object to relational mapping, database independence
 and distributed computing. For languages, such as C++ and Smalltalk, there is a need for tools for mapping their objects to
 relational entities. Java provides an alternative to these tools that frees us from the proprietary interfaces associated with
 database programming. With the "write once, compile once, run anywhere" power that JDBC offers us, Java's database connectivity
 allows us to concentrate on the translation of relational data into objects instead of how we can get that data from the database.

A Java database application does not care what its database engine is. No matter how many times the database engine changes,
 the application itself need never change. In addition, a company can build a class library that maps its business objects to
 database entities in such a way that applications do not even know whether or not their objects are being stored in a database.

Java affects the way we distribute and maintain application. Currently a Web application allows user to download a bunch of flight
 information as an HTML page. While viewing the page for a particular flight, suppose some one makes a reservation for a seat on that
 flight and this process will not be available to the viewers as the page is just a copy of data from the database. To view the change
 that just occurred, the viewers again have to contact the database to get the latest data. If we reconstruct the same Web application
 using Java RMI to retrieve the data from a single flight object on the server, any number of users can view the data simultaneously and
 if there is any reservation or any change taking place, immediately the changes made to the data will be sent back to all the users and
 hence the users can avail the latest data at any time. Thus JDBC can combine with Java RMI to develop distributed enterprise-scale
 mission-critical three-tier database applications.
JDBC for Relational Databases

There are three main database technologies. They are relational, object and object-relational. A Java application can access any one
 of these database architectures. The overwhelming majority of today's database applications use relational databases. The JDBC API is
 thus heavily biased toward relational databases and their standard query language, SQL. Relational databases find and provide
 relationships between data and Java, as a object solution makes common cause with relational database technology due to the
 fact that object-oriented philosophy dictates that an object's behavior is inseparable from its data. In choosing the
 object-oriented reality of Java, we need to create a translation layer that maps the relational world into our object
 world. Thus with the goal of accessing relational databases, JDBC API specification has been defined by Sun Microsystems
 with the help of popular database vendors.

 What is JDBC?

JDBC is essentially an Application Programming Interface (API) for executing SQL statements, and extracting the results.
Using this API, we can write database clients, such as Java applets, servlets and Enterprise JavaBeans, that connect to a
relational database, such as Oracle, MySQL, Sybase, Informix, Ingres, PostgreSQL, or any other database that implements this API,
 execute SQL statements, and process the results extracted from the database.
JDBC Versions

JDBC 2.0 API is the latest version of JDBC API available in the java.sql package. The previous version focused primarily on basic
 database programming services such as creating connections, executing statements and prepared statements, running batch queries, etc.
 However, the current API supports batch updates, scrollable resultsets, transaction isolation, and the new SQL:1999 data types such as
 BLOB and CLOB in addition to the SQL2 data types.

JDBC 2.0 Optional Package API is available in the javax.sql package and is distributed with the enterprise edition of Java 2, that is J2EE.
 The optional package addresses Java Naming and Directory Interface (JNDI)-based data sources for managing connections, connection pooling,
 distributed transactions, and rowsets.
The Benefits of JDBC

The JDBC API provides a set of implementation-independent generic database access methods for the above mentioned SQL-compliant databases.
 JDBC abstracts much of the vendor-specific details and generalizes the most common database access functions. Thus resulted a set of classes
 and interfaces of the java.sql package that can be used with any database providing JDBC connectivity through a vendor-specific JDBC driver
 in a consistent way. Thus if our application conforms to the most commonly available database features, we should be able to reuse
 an application with another database simply by switching to a new JDBC driver. In other words, JDBC enables us to write applications
 that access relational databases without any thought as to which particular database we are using.

Also database connectivity is not just connecting to databases and executing statements. In an enterprise-level application environment
, there are some important requirements to be met, such as optimizing network resources by employing connection pooling, and implementing
distributed transactions. JDBC has all these features in accomplishing advanced database programming.
The JDBC Drivers

A database vendor typically provides a set of APIs for accessing the data managed by the database server. Popular database vendors have
 supplied some proprietary APIs for client access. Client applications written in native languages such as C and C++ can make these API
 calls for database access directly. The JDBC API provides a Java-language alternative to these vendor-specific APIs. Though this takes
 away the need to access vendor-specific native APIs for database access, the implementation of the JDBC layer still need to make these
 native calls for data access.

JDBC accomplishes its goals through a set of Java interfaces, each gets implemented differently by different vendors. The set of classes
 that implement the JDBC interfaces for a particular database engine is called a JDBC driver. Hence the necessity of a JDBC driver for
 each database server. In building a database application, we do not have to think about the implementation of these underlying classes
 at all as the whole point of using JDBC is to hide the specifics of each database and let us concentrate on our application.
 A JDBC driver is a middleware layer that translates the JDBC calls to the vendor-specific APIs. The Java VM uses the JDBC
 driver to translate the generalized JDBC calls into vendor-specific database calls that the database understands.

There are a number of approaches for connecting from our application to a database server via a database driver.

JDBC-ODBC Bridge - Open Database Connectivity (ODBC) was developed to create a single standard for database access in the Windows
environment. ODBC is a Windows API standard for SQL and it is based on X/Open Call-Level Interface (CLI) specification, which is
a standard API for database access. CLI is intended to be vendor, platform, and database neutral. But ODBC API defines a set of
 functions for directly accessing the data without the need for embedding SQL statements in client applications coded in higher
 level languages.

The JDBC API is originally based on the ODBC API. Thus, it becomes feasible for the first category of JDBC drivers providing
a bridge between the JDBC API and the ODBC API. This bridge translates the standard JDBC calls to corresponding ODBC calls. The
 driver then delegates these calls to the data source. Here, the Java classes for the JDBC API and the JDBC-ODBC bridge are invoked
 within the client application process. Similarly, the ODBC layer executes in another process. This configuration requires the client
 application to have the JDBC-ODBC bridge API, the ODBC driver, and the native language level API, such as the OCI library for Oracle
 installed on each client machine.

Each data access call has to go through many layers, this approach for data access is inefficient for high-performance database
access requirements. Though this is not a preferred one, this has to be used in some situations for example, a Microsoft Access
2000 database can be only be accessed using the JDBC-ODBC bridge.

Part Java, Part Native Driver - This approach use a mixture of Java implementation and vendor-specific native APIs for data access.
 This one is a little bit faster than the earlier one. When a database call is made using JDBC, the driver translates the request
 into vendor-specific API calls. The database will process the request and send the results back through the API, which will forward
 them back to the JDBC driver. The JDBC driver will format the results to confirm to the JDBC standard and return them to the program.
 In this approach, the native JDBC driver, which is part Java and part native code, should be installed on each client along with the
 vendor-specific native language API. The native code uses vendor-specific protocols for communicating with the database. The improved
 efficiency makes this a preferred method over the use of the earlier one.

Intermediate Database Access Server This approach is based on intermediate (middleware) database servers with the ability to connect
multiple Java clients to multiple database servers. In this configuration, clients connect to various database servers via an intermediate
 server that acts as a gateway for multiple database servers. While the specific protocol used between clients and the intermediate server
 depends on the middleware server vendor, the intermediate server can use different native protocols to connect to different databases.
 The Java client application sends a JDBC call through a JDBC driver to the intermediate data access server. The middle-tier then handles
 the request using another driver, for example the above one, to complete the request. This is good because the intermediate server can
 abstract details of connections to database servers.

Pure Java Drivers - This a pure Java alternative to part Java, part native driver. These drivers convert the JDBC API calls to direct
network calls using vendor-specific networking by making direct socket connections with the database like Oracle Thin JDBC Driver.
 This is the most efficient method of accessing databases both in performance and development time. It also the simplest to deploy
 since there are no additional libraries or middleware to install. All major database vendors, such as Oracle, Sybase, and Microsoft,
 provide this type of drivers for their databases.
Alternatives to JDBC

There are two major alternatives to JDBC at present. They are ODBC and SQLJ, a non-approved Java standard for database access.

Without JDBC, only disparate, proprietary database access solutions exist. These solutions force the developer to build a layer
 of abstraction on top of them in order to create database-independent code. The ODBC solution provide this universal abstraction
 layer for languages, such as C and C++, and popular developmental tools, such as Delphi, PowerBuilder, and VisualBasic. But ODBC
 can not enjoy the platform independence of Java as ODBC is restricted to Windows platform. On using JDBC, the server application
 can pick the database at run time based on which client is connecting. Thus JDBC facilitates to change the database just by
 changing the JDBC URL and driver name without adding any new code.

connect to database using java



Connecting to a MySQL Database in Java


    

In java we have been provided with some classes and APIs with which we can make use of the database as we like.
Database plays as very important role in the programming because we have to store the values somewhere in the back- end.
So, we should know how we can manipulate the data in the database with the help of java,  instead of going to database for
a manipulation. We have many database provided like Oracle, MySQL etc. We are using MySQL for developing this application.

In this section, you will learn how to connect the MySQL database with the Java file. Firstly, we need to establish a
connection between MySQL and Java files with the help of MySQL driver .  Now we will make our  account in MySQL database
so that we can get connected to the database. After establishing a connection  we can access or retrieve data form MySQL
database. We are going to make a program on connecting to a MySQL database, after going through this program you will be
 able to establish a connection on your own PC.

Description of program:

This program establishes the connection between MySQL database and java files with the help of various types of APIs interfaces
and methods. If connection is established then it shows "Connected to the database" otherwise it will displays a message "Disconnected
from database".

Description of code:

Connection:
This is an interface in  java.sql package that specifies connection with specific database like: MySQL, Ms-Access, Oracle etc and
java files. The SQL statements are executed within the context of the Connection interface.

Class.forName(String driver):
This method is static. It attempts to load the class and returns class instance and takes string type value (driver) after that
 matches class with given string.

DriverManager:
It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be register with this class.

getConnection(String url, String userName, String password):
This method establishes a connection to specified database url. It takes three string types of arguments like:

    url: - Database url where stored or created your database
  userName: - User name of MySQL
  password: -Password of MySQL

con.close():
This method is used for disconnecting the connection. It frees all the resources occupied by the database.

printStackTrace():
The method is used to show error messages. If the connection is not established then exception is thrown and print the message.

import java.sql.*;

public class MysqlConnect{
  public static void main(String[] args) {
  System.out.println("MySQL Connect Example.");
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "jdbctutorial";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "root";
  String password = "root";
  try {
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection(url+dbName,userName,password);
  System.out.println("Connected to the database");
  conn.close();
  System.out.println("Disconnected from database");
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
}

java calculator

 JAVA CALCULATOR

/**
  This is a simple calculator program can any one take and use.

   */
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
//<applet code=Calculator height=300 width=200></applet>
public class Calculator extends JApplet {
   public void init() {
      CalculatorPanel calc=new CalculatorPanel();
      getContentPane().add(calc);
      }
   }

   class CalculatorPanel extends JPanel implements ActionListener {
      JButton
n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
      static JTextField result=new JTextField("0",45);
      static String lastCommand=null;
      JOptionPane p=new JOptionPane();
      double preRes=0,secVal=0,res;

      private static void assign(String no)
        {
         if((result.getText()).equals("0"))
            result.setText(no);
          else if(lastCommand=="=")
           {
            result.setText(no);
            lastCommand=null;
           }
          else
            result.setText(result.getText()+no);
         }

      public CalculatorPanel() {
         setLayout(new BorderLayout());
         result.setEditable(false);
         result.setSize(300,200);
         add(result,BorderLayout.NORTH);
         JPanel panel=new JPanel();
         panel.setLayout(new GridLayout(4,4));

         n7=new JButton("7");
         panel.add(n7);
         n7.addActionListener(this);
         n8=new JButton("8");
         panel.add(n8);
         n8.addActionListener(this);
         n9=new JButton("9");
         panel.add(n9);
         n9.addActionListener(this);
         div=new JButton("/");
         panel.add(div);
         div.addActionListener(this);

         n4=new JButton("4");
         panel.add(n4);
         n4.addActionListener(this);
         n5=new JButton("5");
         panel.add(n5);
         n5.addActionListener(this);
         n6=new JButton("6");
         panel.add(n6);
         n6.addActionListener(this);
         mul=new JButton("*");
         panel.add(mul);
         mul.addActionListener(this);

         n1=new JButton("1");
         panel.add(n1);
         n1.addActionListener(this);
         n2=new JButton("2");
         panel.add(n2);
         n2.addActionListener(this);
         n3=new JButton("3");
         panel.add(n3);
         n3.addActionListener(this);
         minus=new JButton("-");
         panel.add(minus);
         minus.addActionListener(this);

         dot=new JButton(".");
         panel.add(dot);
         dot.addActionListener(this);
         n0=new JButton("0");
         panel.add(n0);
         n0.addActionListener(this);
         
         equal=new JButton("=");
         panel.add(equal);
         equal.addActionListener(this);
         plus=new JButton("+");
         panel.add(plus);
         plus.addActionListener(this);
         add(panel,BorderLayout.CENTER);
      }
      public void actionPerformed(ActionEvent ae)
         {
      if(ae.getSource()==n1) assign("1");
      else if(ae.getSource()==n2) assign("2");
      else if(ae.getSource()==n3) assign("3");
      else if(ae.getSource()==n4) assign("4");
      else if(ae.getSource()==n5) assign("5");
      else if(ae.getSource()==n6) assign("6");
      else if(ae.getSource()==n7) assign("7");
      else if(ae.getSource()==n8) assign("8");
      else if(ae.getSource()==n9) assign("9");
      else if(ae.getSource()==n0) assign("0");
     
      else if(ae.getSource()==dot)
            {
             if(((result.getText()).indexOf("."))==-1)
                result.setText(result.getText()+".");
           }
      else if(ae.getSource()==minus)
             {
             preRes=Double.parseDouble(result.getText());
             lastCommand="-";
             result.setText("0");
             }
      else if(ae.getSource()==div)
             {
             preRes=Double.parseDouble(result.getText());
             lastCommand="/";
             result.setText("0");
             }
      else if(ae.getSource()==equal)
             {
             secVal=Double.parseDouble(result.getText());
             if(lastCommand.equals("/"))
                  res=preRes/secVal;
             else if(lastCommand.equals("*"))
                  res=preRes*secVal;
             else if(lastCommand.equals("-"))
                  res=preRes-secVal;
             else if(lastCommand.equals("+"))
                  res=preRes+secVal;
             result.setText(" "+res);
             lastCommand="=";
             }
      else if(ae.getSource()==mul)
             {
              preRes=Double.parseDouble(result.getText());
              lastCommand="*";
              result.setText("0");
              }
      else if(ae.getSource()==plus)
              {
              preRes=Double.parseDouble(result.getText());
              lastCommand="+";
              result.setText("0");
              }

       }
 }

java chat program

CHAT SIMULATION USING JAVA
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * This applet simulates a network chat, in which the user chats with
 * someone over a network.  Here, there is no network.  The partner is
 * simulated by a thread that emits strings at random.  The point
 * of the simulation is to show how to use a separate thread for receiving
 * information.

 * The applet has an input box where the user enters messages.  When
 * the user presses return, the message is posted to a text area.  In
 * a real chat program, it would be transmitted over the network.
 * When a (simulated) message is received from the other side, it is
 * also posted to this text area. 

 * The partner thread is started the first time the user sends
 * a message.
 */

public class ChatSimulation extends JApplet implements ActionListener, Runnable {

   private static String[] incomingMessages = {  // Simulated messages from chat partner.
      "Say, how about those Mets.",
      "My favorite color is gray.  What's yours?",
      "In a World without Walls, who needs Windows?  "
      + "In a World without Fences, who needs Gates?",
      "An empty vessel makes the most noise.",
      "Can you tell me what a Thread is?",
      "Do you always follow style rules when you program?",
      "Sometimes, I really, really hate computers.",
      "Do you remember the Pythagorean theorem?",
      "Have you tried the GIMP image processing program?",
      "I was thinking, How come wrong numbers are never busy?",
      "Do you know Murphy's Law?  You should.",
      "Are you getting bored yet?",
      "Everything should be made as simple as possible -- but not simpler.",
      "The revolution will not be televised."
   };

   private JTextArea transcript;  // A text area that shows transmitted and
                                  // received messages.

   private JTextField input;  // A text-input box where the use enters
                              // outgoing messages.

   private Thread runner;    // The thread the simulated the incoming messages.

   private boolean running;  // This is set to true when the thread is created.
                             // when it becomes false, the thread should exit.
                             // It is set to false in the applet's stop() method.

   /**
    * Initialize the applet.
    */
   public void init() {
      JPanel content = new JPanel();
      content.setBackground(Color.LIGHT_GRAY);
      content.setLayout(new BorderLayout(3,3));
      content.setBorder(BorderFactory.createLineBorder(Color.GRAY,3));
      transcript = new JTextArea();
      transcript.setEditable(false);
      content.add(new JScrollPane(transcript),BorderLayout.CENTER);
      JPanel bottom = new JPanel();
      bottom.setBackground(Color.LIGHT_GRAY);
      bottom.setLayout(new BorderLayout(3,3));
      content.add(bottom,BorderLayout.SOUTH);
      input = new JTextField();
      input.setBackground(Color.WHITE);
      input.addActionListener(this);
      bottom.add(input,BorderLayout.CENTER);
      JButton send = new JButton("Send");
      send.addActionListener(this);
      bottom.add(send,BorderLayout.EAST);
      bottom.add(new JLabel("Text to send:"),BorderLayout.WEST);
      setContentPane(content);
   }

  
   /**
    *  This will be called when the user clicks the "Send" button or presses
    *  return in the text-input box.  It posts the contents of the input box
    *  to the transcript.  If the thread is not running, it creates and starts
    *  a new thread.
    */
   public void actionPerformed(ActionEvent evt) {
      postMessage("SENT: " + input.getText());
      input.selectAll();
      input.requestFocus();
      if (running == false) {
         runner = new Thread(this);
         running = true;
         runner.start();
      }
   }
  

   /**
    * Add a line of text to the transcript area.
    * @param message text to be added; two line feeds is added at the end.
    */
   private void postMessage(String message) {
      transcript.append(message + "\n\n");
         // The following line is a nasty kludge that was the only way I could find to force
         // the transcript to scroll so that the text that was just added is visible in
         // the window.  Without this, text can be added below the bottom of the visible area
         // of the transcript.
      transcript.setCaretPosition(transcript.getDocument().getLength());
   }


   /**
    * The run method just posts messages to the transcript
    * at random intervals of 2 to 10 seconds.
    */
   public void run() {
      //
      postMessage("RECEIVED: Hey, hello there! Nice to chat with you.");
      while (running) {
         try {
               // Wait a random time from 2000 to 10000 milliseconds.
            Thread.sleep( 2000 + (int)(8000*Math.random()) );
         }
         catch (InterruptedException e) {
         }
         int msgNum = (int)(Math.random() * incomingMessages.length);
         postMessage("RECEIVED: " + incomingMessages[msgNum]);
      }
   }
  

   /**
    * When applet is stopped, make sure that the thread will
    * terminate by setting running to false.
    */
   public void stop() {
      running = false;
      runner = null;
   }


} // end class ChatSimulation

Java Web BROWSER

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.net.URL;
/* <applet code="SimpleWebBrowser.Class" height=400 width=500></applet>  */
/**
 * Defines a simple web browser that can load web pages from
 * URLs specified by the user in a "Location" box.  Almost all
 * the functionality is provided automatically by the JEditorPane
 * class.  The program loads web pages synchronously and can hang
 * indefinitely while trying to load a page.  See
 * SimpleWebBrowserWithThread for an asynchronous version.
 * This class can be run as a standalone application and has
 * a nested class that can be run as an applet.  The applet
 * version can probably only read pages from the server from which
 * it was loaded.
 */
public class SimpleWebBrowser extends JPanel {

   /**
    * The main routine simply opens a window that shows a SimpleWebBrowser panel.
    */
   public static void main(String[] args) {
      JFrame window = new JFrame("SimpleWebBrowser");
      SimpleWebBrowser content = new SimpleWebBrowser();
      window.setContentPane(content);
      window.setSize(600,500);
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      window.setLocation( (screenSize.width - window.getWidth())/2,
            (screenSize.height - window.getHeight())/2 );
      window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      window.setVisible(true);
   }
  
  
   /**
    * The public static class SimpleWebBrowser.Applet represents this program
    * as an applet.  The applet's init() method simply sets the content
    * pane of the applet to be a SimpleWebBrowser.  To use the applet on
    * a web page, use code="SimpleWebBrowser$Applet.class" as the name of
    * the class.
    */
   public static class Applet extends JApplet {
      public void init() {
         SimpleWebBrowser content = new SimpleWebBrowser();
         setContentPane( content );
      }
   }
  
  
   /**
    * The pane in which documents are displayed.
    */
   private JEditorPane editPane;
  
  
   /**
    * An input box where the user enters the URL of a document
    * to be loaded into the edit pane.  A value URL string has
    * to contain the substring "://".  If the string in the box
    * does not contain this substring, then "http://" is
    * prepended to the string.
    */
   private JTextField locationInput;
  
  
   /**
    * Defines a listener that responds when the user clicks on
    * a link in the document.
    */
   private class LinkListener implements HyperlinkListener {
      public void hyperlinkUpdate(HyperlinkEvent evt) {
         if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
            loadURL(evt.getURL());
         }
      }
   }
  
  
   /**
    * Defines a listener that loads a new page when the user
    * clicks the "Go" button or presses return in the location
    * input box.
    */
   private class GoListener implements ActionListener {
      public void actionPerformed(ActionEvent evt) {
         URL url;
         try {
            String location = locationInput.getText().trim();
            if (location.length() == 0)
               throw new Exception();
            if (! location.contains("://"))
               location = "http://" + location;
            url = new URL(location);
         }
         catch (Exception e) {
            JOptionPane.showMessageDialog(SimpleWebBrowser.this,
                  "The Location input box does not\nccontain a legal URL.");
            return;
         }
         loadURL(url);
         locationInput.selectAll();
         locationInput.requestFocus();
      }
   }

  
   /**
    * Construct a panel that contains a JEditorPane in a JScrollPane,
    * with a tool bar that has a Location input box and a Go button.
    */
   public SimpleWebBrowser() {
     
      setBackground(Color.BLACK);
      setLayout(new BorderLayout(1,1));
      setBorder(BorderFactory.createLineBorder(Color.BLACK,1));

      editPane = new JEditorPane();
      editPane.setEditable(false);
      editPane.addHyperlinkListener(new LinkListener());
      add(new JScrollPane(editPane),BorderLayout.CENTER);
     
      JToolBar toolbar = new JToolBar();
      toolbar.setFloatable(false);
      add(toolbar,BorderLayout.NORTH);
      ActionListener goListener = new GoListener();
      locationInput = new JTextField("math.hws.edu/javanotes/index.html", 40);
      locationInput.addActionListener(goListener);
      JButton goButton = new JButton(" Go ");
      goButton.addActionListener(goListener);
      toolbar.add( new JLabel(" Location: "));
      toolbar.add(locationInput);
      toolbar.addSeparator(new Dimension(5,0));
      toolbar.add(goButton);

   }
  
  
   /**
    * Loads the document at the specified URL into the edit pane.
    */
   private void loadURL(URL url) {
      try {
         editPane.setPage(url);
      }
      catch (Exception e) {
         editPane.setContentType("text/plain");
         editPane.setText( "Sorry, the requested document was not found\n"
               +"or cannot be displayed.\n\nError:" + e);
      }
   }
  
}

Sunday, 29 April 2012

RSS feed by XML using CSS

Improving an XML feed display through CSS and XSLT

XML feeds, though useful, are boring to look at in a browser because they are simple XML files. It's possible though to make them easier on the eye, and in this article we'll look at two ways of doing that. First, we'll use simple CSS properties to format each XML node, and then we'll use a little more complex but much more powerful XSL transformation.


Introduction

XML feeds have become a common way for people to keep updated on their favorite websites, no matter what specification they follow (RSS, Atom, etc.). XML files suffer though from poor usability by nature as they are not friendly to look at in the browser. Your feed handler (e.g. FeedDemon, FeedReader, NewsGator, etc.) will, of course, display them in a nicely formatted way, but in this article we'll see two ways to spice up their boring browser display:

    Using CSS definitions on the individual notes
    Applying an XSL Tranformation file

For our example, we'll assume that we are serving feeds in RSS 2.0 format, but the principles discussed should apply for any type of XML feed. You can rest assured that this type of formatting will not change the way your readers use your feeds. I first got this idea after reading a blog entry by Pete Freitag.
First, the original XML feed

So, Let's a take a look at a typical RSS 2.0 feed: an example of a possible "latest articles" feed for this site:
<?xml version="1.0" encoding="iso-8859-1"?>

<?xml-stylesheet type="text/css" href="itemof.css" ?>
     <rss version="2.0">
     <channel xmlns:html="http://www.w3.org/1999/xhtml">
   
      <html:hr/>
   
         <title>rtechinsane.in</title>
        <html:hr/>
         <link>http://www.rtechinsane.in</link>
         <description>The latest articles from rtechinsane.in</description>
         <language>en-us</language>
         <copyright>Copyright 2012 rtechinsane.in</copyright>
         <docs>http://blogs.law.harvard.edu/tech/rss/</docs>
         <lastBuildDate>Mon, 23 April 2012 00:00:00 MST</lastBuildDate>
        
         <item>
             <title>Improving an XML feed display through CSS and XSLT</title>
            <photo>
         <html:img src="img.jpg" width="80" height="80" />Flannel Bush
      </photo>
             <description>XML feeds, though useful, are boring to look at in a browser because they are simple XML files. It's possible though to make them easier on the eye, and in this article we'll look at two ways of doing that. First, we'll use simple CSS properties to format each XML node, and then we'll use a little more complex but much more powerful XSL transformation.</description>
             <pubDate>Sun, 06 Mar 2005 00:00:00 MST</pubDate>
             <link>http://www.rtechinsane.in/articles/show.cfm?id=24</link>
         </item>
        

         <item>
             <title>Identity fields in Oracle and SQL Server</title>
            <photo>
         <html:img src="img.jpg" width="80" height="90" />Flannel Bush
      </photo>
             <description>While it may be relatively easy to create an incrementing and unique identifier inside a table in SQL Server, things get tricky with Oracle. In this article, we'll see the differences between the two databases and offer a way of solving the problem.</description>
             <author>email@yoursite.com </author>
        <pubDate>Mon, 17 Mar 2003 00:00:00 MST</pubDate>
             <link>http://www.rtechinsane.in/articles/show.cfm?id=23</link>
         </item>

        
         <item>
             <title>Exporting Word files to HTML</title>
            <photo>
         <html:img src="img.jpg" width="80" height="80" />Flannel Bush
      </photo>
             <description>In this article we will first discuss the case for and against using Word as your HTML editor. Then we will see how to properly save a Word file to smaller, more compact HTML files. Third and last, we will see how to do this through code, and possibly create a batch process for converting numerous Word files to HTML at once.</description>
             <author>email@yoursite.com </author>
             <pubDate>Wed, 05 Mar 2003 00:00:00 MST</pubDate>
             <link>http://www.rtechinsane.in/articles/show.cfm?id=22</link>
         </item>

        
     </channel>
     </rss>

We are not doing anything new here. We are following the RSS 2.0 specification to create this feed: a channel wrapper with its feed properties, including as many item nodes as we want of the latest posts (with their own properties). Here's what this feed looks like through the browser:

XML Feed with no formatting

Basic yes, friendly to look at no. So, let's see how to improve this display.
Formatting through CSS

The principle here is that since a feed is made up of XML nodes, we can apply CSS formatting on them to change the way they display in the browser. First we need to add the CSS reference inside the XML file. This can be a full URL with the domain, or simply a website relative address:
1     <?xml version="1.0" encoding="ISO-8859-1" ?>
2     <?xml-stylesheet type="text/css" href="/includes/css/rssfeed.css" ?>
3     <rss version="2.0">

Under channel, we have the mandatory title, which is the feed title. To edit the display of this node to a bigger text size we can simply add this to our CSS:
1     channel title {
2         font-size:140%;
3     }


We can follow this principle to format the rest of the notes. One issue that we have to keep in mind is that if there is more than one node named title, then they will all inherit the same properties. In the example shown, the second tag will also display with font size 140%. To fix this, we will need to create a separate CSS property for it and change the size:
1     channel item title {
2         font-size:100%;
3     }

Our feeds most often contain properties that we may not necessarily want to have them display in our improved version. So. we can group all nodes that we want to hide and change their display property to hidden. The order of the nodes in the XML file will be maintained, unless you can figure out a way to change this through CSS.

Here is a complete CSS file as an example:
1     channel link, channel language, channel copyright, channel managingEditor, channel webMaster, channel docs, channel lastBuildDate {
2         display:none;
3     }
4     rss {
5         font-family:Verdana, Arial, Helvetica, sans-serif;
6         font-size:0.7em;
7         line-height:130%;
8         margin:1em;
9     }
10     /* HEADER */
11     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
12     channel title {
13         display:block;
14         padding:0.4em 0.2em;
15         color:#FFF;
16         border-bottom:1px solid black;
17         font-weight:bold;
18         font-size:140%;
19         background-color:#4483C7;
20     }
21     channel description {
22         display:block;
23         float:left;
24         font-size:130%;
25         font-weight:bold;
26         margin:0.5em;
27     }
28     /* CONTENT */
29     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
30     channel item {
31         background-color:#FFFFEE;
32         border:1px solid #538620;
33         clear:both;
34         display:block;
35         padding:0 0 0.5em;
36         margin:1em;
37     }
38     channel item title {
39         background-color:#538620;
40         border-bottom-width:0;
41         color:#FFF;
42         display:block;
43         font-size:110%;
44         font-weight:bold;
45         margin:0;
46         padding:0.3em 0.5em;
47     }
48     channel item description {
49         display: block;
50         float:none;
51         margin:0;
52         text-align: left;
53         padding:0.2em 0.5em 0.4em;
54         color: black;
55         font-size:100%;
56         font-weight:normal;
57     }
58     channel item link {
59         color:#666;
60         display:block;
61         font-size:86%;
62         padding:0 0.5em;
63     }
64     channel item pubDate {
65         color:#666;
66         display:block;
67         font-size:86%;
68         padding:0 0.5em;
69     }

   

Here's a screenshot of the resulting output:

XML feed with CSS formatting

RSS

Categories

Followers

Blog Archive

rTechIndia

RtechIndia->technology ahead

rtech

rtechindia

RtechIndia

Go rtechindia

Go rtechindia

RtechIndia

Wednesday, 18 July 2012

JDBC basics

The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database.




JDBC helps you to write java applications that manage these three programming activities:
  1. Connect to a database
  2. Send queries and update statements to the database
  3. Retrieve and process the results with database.

     
     
     
    Connection con = DriverManager.getConnection
               ( "jdbc:myDriver:wombat", "myLogin","myPassword");
         
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
    while (rs.next()) {
     int x = rs.getInt("a");
     String s = rs.getString("b");
     float f = rs.getFloat("c");
     }
    This short code fragment instantiates a DriverManager object to connect to a database driver and log into the database, instantiates a Statement object that carries your SQL language query to the database; instantiates a ResultSet object that retrieves the results of your query, and executes a simple while loop, which retrieves and displays those results.



JDBC includes four components:
  1. The JDBC API 

    The JDBC™ API provides programmatic access to relational data from the Java™ programming language. Using the JDBC API, applications can execute SQL statements, retrieve results, and propagate changes back to an underlying data source. The JDBC API can also interact with multiple data sources in a distributed, heterogeneous environment.


    The JDBC API is part of the Java platform, which includes the
    Java™ Standard Edition (Java™ SE ) and the Java™ Enterprise Edition (Java™ EE). The JDBC 4.0 API is divided into two packages: java.sql and javax.sql. Both packages are included in the Java SE and Java EE platforms.

  2. JDBC Driver Manager 

    The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture.

    The Standard Extension packages javax.naming and javax.sql let you use a DataSource object registered with a Java Naming and Directory Interface™ (JNDI) naming service to establish a connection with a data source. You can use either connecting mechanism, but using a DataSource object is recommended whenever possible.
  3. JDBC Test Suite

    The JDBC driver test suite helps you to determine that JDBC drivers will run your program. These tests are not comprehensive or exhaustive, but they do exercise many of the important features in the JDBC API.
  4. JDBC-ODBC Bridge

    The Java Software bridge provides JDBC access via ODBC drivers. Note that you need to load ODBC binary code onto each client machine that uses this driver. As a result, the ODBC driver is most appropriate on a corporate network where client installations are not a major problem, or for application server code written in Java in a three-tier architecture.
This Trail uses the first two of these these four JDBC components to connect to a database and then build a java program that uses SQL commands to communicate with a test Relational Database. The last two components are used in specialized environments to test web applications, or to communicate with ODBC-aware DBMSs.

JDBC Architecture

Two-tier and Three-tier Processing Models

The JDBC API supports both two-tier and three-tier processing models for database access.

Figure 1: Two-tier Architecture for Data Access.



In the two-tier model, a Java applet or application talks directly to the data source. This requires a JDBC driver that can communicate with the particular data source being accessed. A user's commands are delivered to the database or other data source, and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. The network can be an intranet, which, for example, connects employees within a corporation, or it can be the Internet.

In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive because the middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages.
Figure 2: Three-tier Architecture for Data Access.
The DBMS-proprietary protocol provides two-way communication between the database server and the server machine. HTTP, RMI, CORBA or other calls provide two way communication between the server machine and the client machine

Until recently, the middle tier has often been written in languages such as C or C++, which offer fast performance. However, with the introduction of optimizing compilers that translate Java bytecode into efficient machine-specific code and technologies such as Enterprise JavaBeans™, the Java platform is fast becoming the standard platform for middle-tier development. This is a big plus, making it possible to take advantage of Java's robustness, multithreading, and security features.

With enterprises increasingly using the Java programming language for writing server code, the JDBC API is being used more and more in the middle tier of a three-tier architecture. Some of the features that make JDBC a server technology are its support for connection pooling, distributed transactions, and disconnected rowsets. The JDBC API is also what allows access to a data source from a Java middle tier.

Storing image in db using jdbc

Assuming you have a table with a blob field and you want to save a file and store it in the database table or you want to read from a blob object stored in a database, you can use these below java code snippets to write file and read file from database.
The sample table is created as below to have a blob field to store file.


CREATE TABLE t1 (c1 INT PRIMARY KEY NOT NULL, c2 BLOB(5M));


Then use the below code snippet to insert an image file as follows.
 
PreparedStatement pstmt = conn.prepareStatement ("INSERT INTO t1 VALUES (?,?)");
pstmt.setInt (1, 100);
File fBlob = new File ( "image1.gif" );
FileInputStream is = new FileInputStream ( fBlob );
pstmt.setBinaryStream (2, is, (int) fBlob.length() );
pstmt.execute ();
...

 

Retrieving a BLOB or in other words retrieving the image file stored in the database as follows:
 
Statement stmt = conn.createStatement ();
ResultSet rs= stmt.executeQuery("SELECT * FROM t1");
while(rs.next()) {
int val1 = rs.getInt(1);
InputStream val2 = rs.getBinaryStream(2);
...
} rs.close();

sending mail through java

SENDING MAIL THROUGH JAVA
You can use the JavaMail API to send emails from your Java application. Though the JavaMail API allows you to do many things including the ability to retrieve and read the emails or sending emails etc, this sample java program demonstrates how to send email from your Java application. Remember to change the email host (String host) to your email server host, otherwise it won't work. import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SimpleSendEmail {
public static void main(String[] args) {
// Collect the necessary information to send a simple message
// Make sure to replace the values for host, to, and from with
// valid information.
// host - must be a valid smtp server that you currently have
// access to.
// to - whoever is going to get your email
// from - whoever you want to be. Just remember that many smtp
// servers will validate the domain of the from address
// before allowing the mail to be sent.

String host = "server.myhost.com";
String to = "YourFriend@someemail.com";
String from = "Me@myhost.com";
String subject = "My First Email";
String messageText = "I am sending a message using the"
+ " JavaMail API.\n"
+ "Here type your message.";
boolean sessionDebug = false;
// Create some properties and get the default Session.
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
Session session = Session.getDefaultInstance(props, null);
// Set debug on the Session so we can see what is going on
// Passing false will not echo debug info, and passing true
// will.

session.setDebug(sessionDebug);
try {
// Instantiate a new MimeMessage and fill it with the
// required information.
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
// Hand the message to the default transport service
// for delivery.
Transport.send(msg);
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
}

Wednesday, 11 July 2012

JDBC

Introduction to JDB


Java started as an elegant and promising Web programming language. Thereafter, its transition to hard-core computing environment
 is a phenomenal feat. Apart from its significance on client-side programming, Java has been outstanding in developing mission-critical
 enterprise-scale applications and hence its immense contribution to server-side computing gets all round attention. Thus Java as
 a programming language for enterprise computing has been doing well for the past couple of years. As every enterprise includes a
 database, Sun Microsystems has to come with necessary features for making Java to shine in database programming as well.
 In this overview, we discuss about the role of Java Database Connectivity in accomplishing database programming with ease.



Database Programming with Java
Database Programming with Java

Java provides database programmers some distinct advantages, such as easy object to relational mapping, database independence
 and distributed computing. For languages, such as C++ and Smalltalk, there is a need for tools for mapping their objects to
 relational entities. Java provides an alternative to these tools that frees us from the proprietary interfaces associated with
 database programming. With the "write once, compile once, run anywhere" power that JDBC offers us, Java's database connectivity
 allows us to concentrate on the translation of relational data into objects instead of how we can get that data from the database.

A Java database application does not care what its database engine is. No matter how many times the database engine changes,
 the application itself need never change. In addition, a company can build a class library that maps its business objects to
 database entities in such a way that applications do not even know whether or not their objects are being stored in a database.

Java affects the way we distribute and maintain application. Currently a Web application allows user to download a bunch of flight
 information as an HTML page. While viewing the page for a particular flight, suppose some one makes a reservation for a seat on that
 flight and this process will not be available to the viewers as the page is just a copy of data from the database. To view the change
 that just occurred, the viewers again have to contact the database to get the latest data. If we reconstruct the same Web application
 using Java RMI to retrieve the data from a single flight object on the server, any number of users can view the data simultaneously and
 if there is any reservation or any change taking place, immediately the changes made to the data will be sent back to all the users and
 hence the users can avail the latest data at any time. Thus JDBC can combine with Java RMI to develop distributed enterprise-scale
 mission-critical three-tier database applications.
JDBC for Relational Databases

There are three main database technologies. They are relational, object and object-relational. A Java application can access any one
 of these database architectures. The overwhelming majority of today's database applications use relational databases. The JDBC API is
 thus heavily biased toward relational databases and their standard query language, SQL. Relational databases find and provide
 relationships between data and Java, as a object solution makes common cause with relational database technology due to the
 fact that object-oriented philosophy dictates that an object's behavior is inseparable from its data. In choosing the
 object-oriented reality of Java, we need to create a translation layer that maps the relational world into our object
 world. Thus with the goal of accessing relational databases, JDBC API specification has been defined by Sun Microsystems
 with the help of popular database vendors.

 What is JDBC?

JDBC is essentially an Application Programming Interface (API) for executing SQL statements, and extracting the results.
Using this API, we can write database clients, such as Java applets, servlets and Enterprise JavaBeans, that connect to a
relational database, such as Oracle, MySQL, Sybase, Informix, Ingres, PostgreSQL, or any other database that implements this API,
 execute SQL statements, and process the results extracted from the database.
JDBC Versions

JDBC 2.0 API is the latest version of JDBC API available in the java.sql package. The previous version focused primarily on basic
 database programming services such as creating connections, executing statements and prepared statements, running batch queries, etc.
 However, the current API supports batch updates, scrollable resultsets, transaction isolation, and the new SQL:1999 data types such as
 BLOB and CLOB in addition to the SQL2 data types.

JDBC 2.0 Optional Package API is available in the javax.sql package and is distributed with the enterprise edition of Java 2, that is J2EE.
 The optional package addresses Java Naming and Directory Interface (JNDI)-based data sources for managing connections, connection pooling,
 distributed transactions, and rowsets.
The Benefits of JDBC

The JDBC API provides a set of implementation-independent generic database access methods for the above mentioned SQL-compliant databases.
 JDBC abstracts much of the vendor-specific details and generalizes the most common database access functions. Thus resulted a set of classes
 and interfaces of the java.sql package that can be used with any database providing JDBC connectivity through a vendor-specific JDBC driver
 in a consistent way. Thus if our application conforms to the most commonly available database features, we should be able to reuse
 an application with another database simply by switching to a new JDBC driver. In other words, JDBC enables us to write applications
 that access relational databases without any thought as to which particular database we are using.

Also database connectivity is not just connecting to databases and executing statements. In an enterprise-level application environment
, there are some important requirements to be met, such as optimizing network resources by employing connection pooling, and implementing
distributed transactions. JDBC has all these features in accomplishing advanced database programming.
The JDBC Drivers

A database vendor typically provides a set of APIs for accessing the data managed by the database server. Popular database vendors have
 supplied some proprietary APIs for client access. Client applications written in native languages such as C and C++ can make these API
 calls for database access directly. The JDBC API provides a Java-language alternative to these vendor-specific APIs. Though this takes
 away the need to access vendor-specific native APIs for database access, the implementation of the JDBC layer still need to make these
 native calls for data access.

JDBC accomplishes its goals through a set of Java interfaces, each gets implemented differently by different vendors. The set of classes
 that implement the JDBC interfaces for a particular database engine is called a JDBC driver. Hence the necessity of a JDBC driver for
 each database server. In building a database application, we do not have to think about the implementation of these underlying classes
 at all as the whole point of using JDBC is to hide the specifics of each database and let us concentrate on our application.
 A JDBC driver is a middleware layer that translates the JDBC calls to the vendor-specific APIs. The Java VM uses the JDBC
 driver to translate the generalized JDBC calls into vendor-specific database calls that the database understands.

There are a number of approaches for connecting from our application to a database server via a database driver.

JDBC-ODBC Bridge - Open Database Connectivity (ODBC) was developed to create a single standard for database access in the Windows
environment. ODBC is a Windows API standard for SQL and it is based on X/Open Call-Level Interface (CLI) specification, which is
a standard API for database access. CLI is intended to be vendor, platform, and database neutral. But ODBC API defines a set of
 functions for directly accessing the data without the need for embedding SQL statements in client applications coded in higher
 level languages.

The JDBC API is originally based on the ODBC API. Thus, it becomes feasible for the first category of JDBC drivers providing
a bridge between the JDBC API and the ODBC API. This bridge translates the standard JDBC calls to corresponding ODBC calls. The
 driver then delegates these calls to the data source. Here, the Java classes for the JDBC API and the JDBC-ODBC bridge are invoked
 within the client application process. Similarly, the ODBC layer executes in another process. This configuration requires the client
 application to have the JDBC-ODBC bridge API, the ODBC driver, and the native language level API, such as the OCI library for Oracle
 installed on each client machine.

Each data access call has to go through many layers, this approach for data access is inefficient for high-performance database
access requirements. Though this is not a preferred one, this has to be used in some situations for example, a Microsoft Access
2000 database can be only be accessed using the JDBC-ODBC bridge.

Part Java, Part Native Driver - This approach use a mixture of Java implementation and vendor-specific native APIs for data access.
 This one is a little bit faster than the earlier one. When a database call is made using JDBC, the driver translates the request
 into vendor-specific API calls. The database will process the request and send the results back through the API, which will forward
 them back to the JDBC driver. The JDBC driver will format the results to confirm to the JDBC standard and return them to the program.
 In this approach, the native JDBC driver, which is part Java and part native code, should be installed on each client along with the
 vendor-specific native language API. The native code uses vendor-specific protocols for communicating with the database. The improved
 efficiency makes this a preferred method over the use of the earlier one.

Intermediate Database Access Server This approach is based on intermediate (middleware) database servers with the ability to connect
multiple Java clients to multiple database servers. In this configuration, clients connect to various database servers via an intermediate
 server that acts as a gateway for multiple database servers. While the specific protocol used between clients and the intermediate server
 depends on the middleware server vendor, the intermediate server can use different native protocols to connect to different databases.
 The Java client application sends a JDBC call through a JDBC driver to the intermediate data access server. The middle-tier then handles
 the request using another driver, for example the above one, to complete the request. This is good because the intermediate server can
 abstract details of connections to database servers.

Pure Java Drivers - This a pure Java alternative to part Java, part native driver. These drivers convert the JDBC API calls to direct
network calls using vendor-specific networking by making direct socket connections with the database like Oracle Thin JDBC Driver.
 This is the most efficient method of accessing databases both in performance and development time. It also the simplest to deploy
 since there are no additional libraries or middleware to install. All major database vendors, such as Oracle, Sybase, and Microsoft,
 provide this type of drivers for their databases.
Alternatives to JDBC

There are two major alternatives to JDBC at present. They are ODBC and SQLJ, a non-approved Java standard for database access.

Without JDBC, only disparate, proprietary database access solutions exist. These solutions force the developer to build a layer
 of abstraction on top of them in order to create database-independent code. The ODBC solution provide this universal abstraction
 layer for languages, such as C and C++, and popular developmental tools, such as Delphi, PowerBuilder, and VisualBasic. But ODBC
 can not enjoy the platform independence of Java as ODBC is restricted to Windows platform. On using JDBC, the server application
 can pick the database at run time based on which client is connecting. Thus JDBC facilitates to change the database just by
 changing the JDBC URL and driver name without adding any new code.

connect to database using java



Connecting to a MySQL Database in Java


    

In java we have been provided with some classes and APIs with which we can make use of the database as we like.
Database plays as very important role in the programming because we have to store the values somewhere in the back- end.
So, we should know how we can manipulate the data in the database with the help of java,  instead of going to database for
a manipulation. We have many database provided like Oracle, MySQL etc. We are using MySQL for developing this application.

In this section, you will learn how to connect the MySQL database with the Java file. Firstly, we need to establish a
connection between MySQL and Java files with the help of MySQL driver .  Now we will make our  account in MySQL database
so that we can get connected to the database. After establishing a connection  we can access or retrieve data form MySQL
database. We are going to make a program on connecting to a MySQL database, after going through this program you will be
 able to establish a connection on your own PC.

Description of program:

This program establishes the connection between MySQL database and java files with the help of various types of APIs interfaces
and methods. If connection is established then it shows "Connected to the database" otherwise it will displays a message "Disconnected
from database".

Description of code:

Connection:
This is an interface in  java.sql package that specifies connection with specific database like: MySQL, Ms-Access, Oracle etc and
java files. The SQL statements are executed within the context of the Connection interface.

Class.forName(String driver):
This method is static. It attempts to load the class and returns class instance and takes string type value (driver) after that
 matches class with given string.

DriverManager:
It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be register with this class.

getConnection(String url, String userName, String password):
This method establishes a connection to specified database url. It takes three string types of arguments like:

    url: - Database url where stored or created your database
  userName: - User name of MySQL
  password: -Password of MySQL

con.close():
This method is used for disconnecting the connection. It frees all the resources occupied by the database.

printStackTrace():
The method is used to show error messages. If the connection is not established then exception is thrown and print the message.

import java.sql.*;

public class MysqlConnect{
  public static void main(String[] args) {
  System.out.println("MySQL Connect Example.");
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "jdbctutorial";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "root";
  String password = "root";
  try {
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection(url+dbName,userName,password);
  System.out.println("Connected to the database");
  conn.close();
  System.out.println("Disconnected from database");
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
}

java calculator

 JAVA CALCULATOR

/**
  This is a simple calculator program can any one take and use.

   */
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
//<applet code=Calculator height=300 width=200></applet>
public class Calculator extends JApplet {
   public void init() {
      CalculatorPanel calc=new CalculatorPanel();
      getContentPane().add(calc);
      }
   }

   class CalculatorPanel extends JPanel implements ActionListener {
      JButton
n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
      static JTextField result=new JTextField("0",45);
      static String lastCommand=null;
      JOptionPane p=new JOptionPane();
      double preRes=0,secVal=0,res;

      private static void assign(String no)
        {
         if((result.getText()).equals("0"))
            result.setText(no);
          else if(lastCommand=="=")
           {
            result.setText(no);
            lastCommand=null;
           }
          else
            result.setText(result.getText()+no);
         }

      public CalculatorPanel() {
         setLayout(new BorderLayout());
         result.setEditable(false);
         result.setSize(300,200);
         add(result,BorderLayout.NORTH);
         JPanel panel=new JPanel();
         panel.setLayout(new GridLayout(4,4));

         n7=new JButton("7");
         panel.add(n7);
         n7.addActionListener(this);
         n8=new JButton("8");
         panel.add(n8);
         n8.addActionListener(this);
         n9=new JButton("9");
         panel.add(n9);
         n9.addActionListener(this);
         div=new JButton("/");
         panel.add(div);
         div.addActionListener(this);

         n4=new JButton("4");
         panel.add(n4);
         n4.addActionListener(this);
         n5=new JButton("5");
         panel.add(n5);
         n5.addActionListener(this);
         n6=new JButton("6");
         panel.add(n6);
         n6.addActionListener(this);
         mul=new JButton("*");
         panel.add(mul);
         mul.addActionListener(this);

         n1=new JButton("1");
         panel.add(n1);
         n1.addActionListener(this);
         n2=new JButton("2");
         panel.add(n2);
         n2.addActionListener(this);
         n3=new JButton("3");
         panel.add(n3);
         n3.addActionListener(this);
         minus=new JButton("-");
         panel.add(minus);
         minus.addActionListener(this);

         dot=new JButton(".");
         panel.add(dot);
         dot.addActionListener(this);
         n0=new JButton("0");
         panel.add(n0);
         n0.addActionListener(this);
         
         equal=new JButton("=");
         panel.add(equal);
         equal.addActionListener(this);
         plus=new JButton("+");
         panel.add(plus);
         plus.addActionListener(this);
         add(panel,BorderLayout.CENTER);
      }
      public void actionPerformed(ActionEvent ae)
         {
      if(ae.getSource()==n1) assign("1");
      else if(ae.getSource()==n2) assign("2");
      else if(ae.getSource()==n3) assign("3");
      else if(ae.getSource()==n4) assign("4");
      else if(ae.getSource()==n5) assign("5");
      else if(ae.getSource()==n6) assign("6");
      else if(ae.getSource()==n7) assign("7");
      else if(ae.getSource()==n8) assign("8");
      else if(ae.getSource()==n9) assign("9");
      else if(ae.getSource()==n0) assign("0");
     
      else if(ae.getSource()==dot)
            {
             if(((result.getText()).indexOf("."))==-1)
                result.setText(result.getText()+".");
           }
      else if(ae.getSource()==minus)
             {
             preRes=Double.parseDouble(result.getText());
             lastCommand="-";
             result.setText("0");
             }
      else if(ae.getSource()==div)
             {
             preRes=Double.parseDouble(result.getText());
             lastCommand="/";
             result.setText("0");
             }
      else if(ae.getSource()==equal)
             {
             secVal=Double.parseDouble(result.getText());
             if(lastCommand.equals("/"))
                  res=preRes/secVal;
             else if(lastCommand.equals("*"))
                  res=preRes*secVal;
             else if(lastCommand.equals("-"))
                  res=preRes-secVal;
             else if(lastCommand.equals("+"))
                  res=preRes+secVal;
             result.setText(" "+res);
             lastCommand="=";
             }
      else if(ae.getSource()==mul)
             {
              preRes=Double.parseDouble(result.getText());
              lastCommand="*";
              result.setText("0");
              }
      else if(ae.getSource()==plus)
              {
              preRes=Double.parseDouble(result.getText());
              lastCommand="+";
              result.setText("0");
              }

       }
 }

java chat program

CHAT SIMULATION USING JAVA
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * This applet simulates a network chat, in which the user chats with
 * someone over a network.  Here, there is no network.  The partner is
 * simulated by a thread that emits strings at random.  The point
 * of the simulation is to show how to use a separate thread for receiving
 * information.

 * The applet has an input box where the user enters messages.  When
 * the user presses return, the message is posted to a text area.  In
 * a real chat program, it would be transmitted over the network.
 * When a (simulated) message is received from the other side, it is
 * also posted to this text area. 

 * The partner thread is started the first time the user sends
 * a message.
 */

public class ChatSimulation extends JApplet implements ActionListener, Runnable {

   private static String[] incomingMessages = {  // Simulated messages from chat partner.
      "Say, how about those Mets.",
      "My favorite color is gray.  What's yours?",
      "In a World without Walls, who needs Windows?  "
      + "In a World without Fences, who needs Gates?",
      "An empty vessel makes the most noise.",
      "Can you tell me what a Thread is?",
      "Do you always follow style rules when you program?",
      "Sometimes, I really, really hate computers.",
      "Do you remember the Pythagorean theorem?",
      "Have you tried the GIMP image processing program?",
      "I was thinking, How come wrong numbers are never busy?",
      "Do you know Murphy's Law?  You should.",
      "Are you getting bored yet?",
      "Everything should be made as simple as possible -- but not simpler.",
      "The revolution will not be televised."
   };

   private JTextArea transcript;  // A text area that shows transmitted and
                                  // received messages.

   private JTextField input;  // A text-input box where the use enters
                              // outgoing messages.

   private Thread runner;    // The thread the simulated the incoming messages.

   private boolean running;  // This is set to true when the thread is created.
                             // when it becomes false, the thread should exit.
                             // It is set to false in the applet's stop() method.

   /**
    * Initialize the applet.
    */
   public void init() {
      JPanel content = new JPanel();
      content.setBackground(Color.LIGHT_GRAY);
      content.setLayout(new BorderLayout(3,3));
      content.setBorder(BorderFactory.createLineBorder(Color.GRAY,3));
      transcript = new JTextArea();
      transcript.setEditable(false);
      content.add(new JScrollPane(transcript),BorderLayout.CENTER);
      JPanel bottom = new JPanel();
      bottom.setBackground(Color.LIGHT_GRAY);
      bottom.setLayout(new BorderLayout(3,3));
      content.add(bottom,BorderLayout.SOUTH);
      input = new JTextField();
      input.setBackground(Color.WHITE);
      input.addActionListener(this);
      bottom.add(input,BorderLayout.CENTER);
      JButton send = new JButton("Send");
      send.addActionListener(this);
      bottom.add(send,BorderLayout.EAST);
      bottom.add(new JLabel("Text to send:"),BorderLayout.WEST);
      setContentPane(content);
   }

  
   /**
    *  This will be called when the user clicks the "Send" button or presses
    *  return in the text-input box.  It posts the contents of the input box
    *  to the transcript.  If the thread is not running, it creates and starts
    *  a new thread.
    */
   public void actionPerformed(ActionEvent evt) {
      postMessage("SENT: " + input.getText());
      input.selectAll();
      input.requestFocus();
      if (running == false) {
         runner = new Thread(this);
         running = true;
         runner.start();
      }
   }
  

   /**
    * Add a line of text to the transcript area.
    * @param message text to be added; two line feeds is added at the end.
    */
   private void postMessage(String message) {
      transcript.append(message + "\n\n");
         // The following line is a nasty kludge that was the only way I could find to force
         // the transcript to scroll so that the text that was just added is visible in
         // the window.  Without this, text can be added below the bottom of the visible area
         // of the transcript.
      transcript.setCaretPosition(transcript.getDocument().getLength());
   }


   /**
    * The run method just posts messages to the transcript
    * at random intervals of 2 to 10 seconds.
    */
   public void run() {
      //
      postMessage("RECEIVED: Hey, hello there! Nice to chat with you.");
      while (running) {
         try {
               // Wait a random time from 2000 to 10000 milliseconds.
            Thread.sleep( 2000 + (int)(8000*Math.random()) );
         }
         catch (InterruptedException e) {
         }
         int msgNum = (int)(Math.random() * incomingMessages.length);
         postMessage("RECEIVED: " + incomingMessages[msgNum]);
      }
   }
  

   /**
    * When applet is stopped, make sure that the thread will
    * terminate by setting running to false.
    */
   public void stop() {
      running = false;
      runner = null;
   }


} // end class ChatSimulation

Java Web BROWSER

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.net.URL;
/* <applet code="SimpleWebBrowser.Class" height=400 width=500></applet>  */
/**
 * Defines a simple web browser that can load web pages from
 * URLs specified by the user in a "Location" box.  Almost all
 * the functionality is provided automatically by the JEditorPane
 * class.  The program loads web pages synchronously and can hang
 * indefinitely while trying to load a page.  See
 * SimpleWebBrowserWithThread for an asynchronous version.
 * This class can be run as a standalone application and has
 * a nested class that can be run as an applet.  The applet
 * version can probably only read pages from the server from which
 * it was loaded.
 */
public class SimpleWebBrowser extends JPanel {

   /**
    * The main routine simply opens a window that shows a SimpleWebBrowser panel.
    */
   public static void main(String[] args) {
      JFrame window = new JFrame("SimpleWebBrowser");
      SimpleWebBrowser content = new SimpleWebBrowser();
      window.setContentPane(content);
      window.setSize(600,500);
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      window.setLocation( (screenSize.width - window.getWidth())/2,
            (screenSize.height - window.getHeight())/2 );
      window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      window.setVisible(true);
   }
  
  
   /**
    * The public static class SimpleWebBrowser.Applet represents this program
    * as an applet.  The applet's init() method simply sets the content
    * pane of the applet to be a SimpleWebBrowser.  To use the applet on
    * a web page, use code="SimpleWebBrowser$Applet.class" as the name of
    * the class.
    */
   public static class Applet extends JApplet {
      public void init() {
         SimpleWebBrowser content = new SimpleWebBrowser();
         setContentPane( content );
      }
   }
  
  
   /**
    * The pane in which documents are displayed.
    */
   private JEditorPane editPane;
  
  
   /**
    * An input box where the user enters the URL of a document
    * to be loaded into the edit pane.  A value URL string has
    * to contain the substring "://".  If the string in the box
    * does not contain this substring, then "http://" is
    * prepended to the string.
    */
   private JTextField locationInput;
  
  
   /**
    * Defines a listener that responds when the user clicks on
    * a link in the document.
    */
   private class LinkListener implements HyperlinkListener {
      public void hyperlinkUpdate(HyperlinkEvent evt) {
         if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
            loadURL(evt.getURL());
         }
      }
   }
  
  
   /**
    * Defines a listener that loads a new page when the user
    * clicks the "Go" button or presses return in the location
    * input box.
    */
   private class GoListener implements ActionListener {
      public void actionPerformed(ActionEvent evt) {
         URL url;
         try {
            String location = locationInput.getText().trim();
            if (location.length() == 0)
               throw new Exception();
            if (! location.contains("://"))
               location = "http://" + location;
            url = new URL(location);
         }
         catch (Exception e) {
            JOptionPane.showMessageDialog(SimpleWebBrowser.this,
                  "The Location input box does not\nccontain a legal URL.");
            return;
         }
         loadURL(url);
         locationInput.selectAll();
         locationInput.requestFocus();
      }
   }

  
   /**
    * Construct a panel that contains a JEditorPane in a JScrollPane,
    * with a tool bar that has a Location input box and a Go button.
    */
   public SimpleWebBrowser() {
     
      setBackground(Color.BLACK);
      setLayout(new BorderLayout(1,1));
      setBorder(BorderFactory.createLineBorder(Color.BLACK,1));

      editPane = new JEditorPane();
      editPane.setEditable(false);
      editPane.addHyperlinkListener(new LinkListener());
      add(new JScrollPane(editPane),BorderLayout.CENTER);
     
      JToolBar toolbar = new JToolBar();
      toolbar.setFloatable(false);
      add(toolbar,BorderLayout.NORTH);
      ActionListener goListener = new GoListener();
      locationInput = new JTextField("math.hws.edu/javanotes/index.html", 40);
      locationInput.addActionListener(goListener);
      JButton goButton = new JButton(" Go ");
      goButton.addActionListener(goListener);
      toolbar.add( new JLabel(" Location: "));
      toolbar.add(locationInput);
      toolbar.addSeparator(new Dimension(5,0));
      toolbar.add(goButton);

   }
  
  
   /**
    * Loads the document at the specified URL into the edit pane.
    */
   private void loadURL(URL url) {
      try {
         editPane.setPage(url);
      }
      catch (Exception e) {
         editPane.setContentType("text/plain");
         editPane.setText( "Sorry, the requested document was not found\n"
               +"or cannot be displayed.\n\nError:" + e);
      }
   }
  
}

Sunday, 29 April 2012

RSS feed by XML using CSS

Improving an XML feed display through CSS and XSLT

XML feeds, though useful, are boring to look at in a browser because they are simple XML files. It's possible though to make them easier on the eye, and in this article we'll look at two ways of doing that. First, we'll use simple CSS properties to format each XML node, and then we'll use a little more complex but much more powerful XSL transformation.


Introduction

XML feeds have become a common way for people to keep updated on their favorite websites, no matter what specification they follow (RSS, Atom, etc.). XML files suffer though from poor usability by nature as they are not friendly to look at in the browser. Your feed handler (e.g. FeedDemon, FeedReader, NewsGator, etc.) will, of course, display them in a nicely formatted way, but in this article we'll see two ways to spice up their boring browser display:

    Using CSS definitions on the individual notes
    Applying an XSL Tranformation file

For our example, we'll assume that we are serving feeds in RSS 2.0 format, but the principles discussed should apply for any type of XML feed. You can rest assured that this type of formatting will not change the way your readers use your feeds. I first got this idea after reading a blog entry by Pete Freitag.
First, the original XML feed

So, Let's a take a look at a typical RSS 2.0 feed: an example of a possible "latest articles" feed for this site:
<?xml version="1.0" encoding="iso-8859-1"?>

<?xml-stylesheet type="text/css" href="itemof.css" ?>
     <rss version="2.0">
     <channel xmlns:html="http://www.w3.org/1999/xhtml">
   
      <html:hr/>
   
         <title>rtechinsane.in</title>
        <html:hr/>
         <link>http://www.rtechinsane.in</link>
         <description>The latest articles from rtechinsane.in</description>
         <language>en-us</language>
         <copyright>Copyright 2012 rtechinsane.in</copyright>
         <docs>http://blogs.law.harvard.edu/tech/rss/</docs>
         <lastBuildDate>Mon, 23 April 2012 00:00:00 MST</lastBuildDate>
        
         <item>
             <title>Improving an XML feed display through CSS and XSLT</title>
            <photo>
         <html:img src="img.jpg" width="80" height="80" />Flannel Bush
      </photo>
             <description>XML feeds, though useful, are boring to look at in a browser because they are simple XML files. It's possible though to make them easier on the eye, and in this article we'll look at two ways of doing that. First, we'll use simple CSS properties to format each XML node, and then we'll use a little more complex but much more powerful XSL transformation.</description>
             <pubDate>Sun, 06 Mar 2005 00:00:00 MST</pubDate>
             <link>http://www.rtechinsane.in/articles/show.cfm?id=24</link>
         </item>
        

         <item>
             <title>Identity fields in Oracle and SQL Server</title>
            <photo>
         <html:img src="img.jpg" width="80" height="90" />Flannel Bush
      </photo>
             <description>While it may be relatively easy to create an incrementing and unique identifier inside a table in SQL Server, things get tricky with Oracle. In this article, we'll see the differences between the two databases and offer a way of solving the problem.</description>
             <author>email@yoursite.com </author>
        <pubDate>Mon, 17 Mar 2003 00:00:00 MST</pubDate>
             <link>http://www.rtechinsane.in/articles/show.cfm?id=23</link>
         </item>

        
         <item>
             <title>Exporting Word files to HTML</title>
            <photo>
         <html:img src="img.jpg" width="80" height="80" />Flannel Bush
      </photo>
             <description>In this article we will first discuss the case for and against using Word as your HTML editor. Then we will see how to properly save a Word file to smaller, more compact HTML files. Third and last, we will see how to do this through code, and possibly create a batch process for converting numerous Word files to HTML at once.</description>
             <author>email@yoursite.com </author>
             <pubDate>Wed, 05 Mar 2003 00:00:00 MST</pubDate>
             <link>http://www.rtechinsane.in/articles/show.cfm?id=22</link>
         </item>

        
     </channel>
     </rss>

We are not doing anything new here. We are following the RSS 2.0 specification to create this feed: a channel wrapper with its feed properties, including as many item nodes as we want of the latest posts (with their own properties). Here's what this feed looks like through the browser:

XML Feed with no formatting

Basic yes, friendly to look at no. So, let's see how to improve this display.
Formatting through CSS

The principle here is that since a feed is made up of XML nodes, we can apply CSS formatting on them to change the way they display in the browser. First we need to add the CSS reference inside the XML file. This can be a full URL with the domain, or simply a website relative address:
1     <?xml version="1.0" encoding="ISO-8859-1" ?>
2     <?xml-stylesheet type="text/css" href="/includes/css/rssfeed.css" ?>
3     <rss version="2.0">

Under channel, we have the mandatory title, which is the feed title. To edit the display of this node to a bigger text size we can simply add this to our CSS:
1     channel title {
2         font-size:140%;
3     }


We can follow this principle to format the rest of the notes. One issue that we have to keep in mind is that if there is more than one node named title, then they will all inherit the same properties. In the example shown, the second tag will also display with font size 140%. To fix this, we will need to create a separate CSS property for it and change the size:
1     channel item title {
2         font-size:100%;
3     }

Our feeds most often contain properties that we may not necessarily want to have them display in our improved version. So. we can group all nodes that we want to hide and change their display property to hidden. The order of the nodes in the XML file will be maintained, unless you can figure out a way to change this through CSS.

Here is a complete CSS file as an example:
1     channel link, channel language, channel copyright, channel managingEditor, channel webMaster, channel docs, channel lastBuildDate {
2         display:none;
3     }
4     rss {
5         font-family:Verdana, Arial, Helvetica, sans-serif;
6         font-size:0.7em;
7         line-height:130%;
8         margin:1em;
9     }
10     /* HEADER */
11     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
12     channel title {
13         display:block;
14         padding:0.4em 0.2em;
15         color:#FFF;
16         border-bottom:1px solid black;
17         font-weight:bold;
18         font-size:140%;
19         background-color:#4483C7;
20     }
21     channel description {
22         display:block;
23         float:left;
24         font-size:130%;
25         font-weight:bold;
26         margin:0.5em;
27     }
28     /* CONTENT */
29     /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
30     channel item {
31         background-color:#FFFFEE;
32         border:1px solid #538620;
33         clear:both;
34         display:block;
35         padding:0 0 0.5em;
36         margin:1em;
37     }
38     channel item title {
39         background-color:#538620;
40         border-bottom-width:0;
41         color:#FFF;
42         display:block;
43         font-size:110%;
44         font-weight:bold;
45         margin:0;
46         padding:0.3em 0.5em;
47     }
48     channel item description {
49         display: block;
50         float:none;
51         margin:0;
52         text-align: left;
53         padding:0.2em 0.5em 0.4em;
54         color: black;
55         font-size:100%;
56         font-weight:normal;
57     }
58     channel item link {
59         color:#666;
60         display:block;
61         font-size:86%;
62         padding:0 0.5em;
63     }
64     channel item pubDate {
65         color:#666;
66         display:block;
67         font-size:86%;
68         padding:0 0.5em;
69     }

   

Here's a screenshot of the resulting output:

XML feed with CSS formatting