Solved

How to make this into JSP page?

Posted on 2001-06-23
24
342 Views
Last Modified: 2013-11-23
0
Comment
Question by:Bekkerus
  • 10
  • 6
  • 4
  • +4
24 Comments
 

Author Comment

by:Bekkerus
Comment Utility
Hello all,

 For some reason the question would not post into EE normally so here is the question. How do I make this into a JSP page?

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ErrTrkr extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException
     {
          File rptFolder = new File("c:\\files");
          java.util.ArrayList arr = new java.util.ArrayList();
          LogParser MyReader = new LogParser();
          String x = new String();

          /* Brief desc.
           * 1. Load Array list with rpt files from the directory c:\files
           * 2. With my reader load data into DB.
           * 3. Run FixOob to correct all issues.
           * 4. Select data from tbl_Err & display results to browser.
          */

          if (rptFolder.isDirectory())
          {
               String[] contents = rptFolder.list();
               for (int i = 0; i < contents.length; i++)  
               {
                    arr.add(String.valueOf(i));
                    x = contents[i];
                    String[] newArgs = { x };
                    MyReader.ReadFile(newArgs);
               }
          }

          FixOob ob = new FixOob();
          FixOob.TestOOB();

          response.setContentType("text/html");
          PrintWriter out = response.getWriter();
          out.println("<html>");
          out.println("<body>");
          out.println("<head>");
          out.println("<title>Error Tracker Servlet</title>");
          out.println("</head>");
          out.println("<body>");
          out.println("<h3><Center>Error Tracker: Db updated.</Center></h3>");
          out.println("<table border=1>");
          // Create Header Row
          out.println("<TR>");
          out.println("<TD><B>CnfrNo</B></TD>");
          out.println("<TD><B>AcctNo</B></TD>");
          out.println("<TD><B>AuthNo</B></TD>");
          out.println("<TD><B>Error Message</B></TD>");
          out.println("<TD><B>Entry Date</B></TD>");
          out.println("<TD><B>Modify Date</B></TD>");
          out.println("<TD><B>Error Type</B></TD>");
          out.println("<TD><B>Resolved</B></TD>");
          out.println("</TR>");

          try
          {
               Class.forName("oracle.jdbc.driver.OracleDriver");
               String url = "jdbc:oracle:thin:@mspdev01:1527:dev01";
               Connection con = DriverManager.getConnection(url, "bekkerus", "changeme");
               Statement stmt = con.createStatement();
               ResultSet rs;
               
               rs = stmt.executeQuery("select sysdate from dual");
               if (rs.next())
               {
                    log("Sysdate is : " + rs.getString(1));
               }

               String rVal = new String();
               rs = stmt.executeQuery("Select * From tbl_Err");
               while(rs.next())
               {
                    out.println("<TR>");
                    rVal = rs.getString(1);
                    out.println("     <TD>" + rVal + "</TD>");
                    rVal = rs.getString(2);
                    out.println("     <TD>" + rVal + "</TD>");
                    rVal = rs.getString(3);
                    out.println("     <TD>" + rVal + "</TD>");
                    rVal = rs.getString(9);
                    out.println("     <TD>" + rVal + "</TD>");
                    rVal = rs.getString(10);
                    out.println("     <TD>" + rVal + "</TD>");
                    rVal = rs.getString(11);
                    out.println("     <TD>" + rVal + "</TD>");
                    rVal = rs.getString(12);
                    out.println("     <TD>" + rVal + "</TD>");
                    rVal = rs.getString(13);
                    out.println("     <TD>" + rVal + "</TD>");
                    out.println("</TR>");
                 }
          }
          catch (SQLException e)
          {
                      log("SQl Error in ErrTrkr.java"+e);
               e.printStackTrace();
          }
          catch (Exception e)
          {
                      log("Other Exception"+e);
               e.printStackTrace();
          }    

          out.println("</table>");
          out.println("</body>");
          out.println("</html>");
     }
}
0
 
LVL 12

Expert Comment

by:ahosang
Comment Utility
Simple rules to start and this may be enough for you. I can't look through the code now.
1)Any packages to be imported use syntax like this:
  <%@ page import="java.io.*" %>

2)Any out.println statement simply leave out the java method syntax e.g.
  <html>
  <head><title>Hello World</title>

3)Any other code within the doGet method(apart from the out.println statements) put in angle brackets like:
<%
File rptFolder = new File("c:\\files");
         java.util.ArrayList arr = new java.util.ArrayList();
         LogParser MyReader = new LogParser();
         String x = new String();
%>

4)Any other java code(statements or methods) within the servlet which is not in the doGet method put in brackets like this:
<%!
public void myMethod(String myString) {
  ....
}
%>

5)name your file with a '.jsp' extension
0
 
LVL 12

Expert Comment

by:ahosang
Comment Utility
Couple of things:
1) No need to import javax.servlet.* or javax.servlet.http.*
2) Don't define PrintWriter out=response.getWriter since jsp has built in jsp_Writer
3) Don't actually define the doGet method. Just follow the other rules and you should be fine.
4) If you need to output some HTML which is not a hardcoded item but is the value of a Java variable then use this expression syntax:
<%= javavariable %>

Example mypage.jsp:

<%@ page import="java.io.*" %>
<%
File rptFolder = new File("c:\\files");
        java.util.ArrayList arr = new java.util.ArrayList();
        LogParser MyReader = new LogParser();
        String x = new String();
%>

<html>
<head><title>...
  ....
<body>
 ....

<% rVal = rs.getString(1); %>
<TD><%= rVal %></TD>

 ....
<%!
public String myMethod() {
 ...
}
%>

</body>
</html>
0
 

Author Comment

by:Bekkerus
Comment Utility
What about database connections and recordset? And about calling other Java classes... Do they have to be in the same folder ie can you have private, package, protected, public. will it use my classpath? Or do JSP only use jsp pages?
0
 
LVL 12

Expert Comment

by:ahosang
Comment Utility
What actually happens when a jsp is first called is the engine translates it into a kind of servlet. The only thing is you can't do is put a jsp into a package so to import custom classes, put the class files where you would normally put them for your servlet use(in MOST servers) and import like:
<%@ page import="myPackage" %> OR
<%@ page import="myPackage.myClass %>
<%@ page import="java.sql.*" %>
Every thing should be fine
0
 

Author Comment

by:Bekkerus
Comment Utility
Will the connection part work the same as this then?

<%
Class.forName("oracle.jdbc.driver.OracleDriver");
              String url = "jdbc:oracle:thin:@mspdev01:1527:dev01";
Connection con = DriverManager.getConnection(url, "bekkerus", "changeme");
Statement stmt = con.createStatement();
ResultSet rs;
%>

<% rVal = rs.getString(1); %>
<TD><%= rVal %></TD>
0
 
LVL 12

Expert Comment

by:ahosang
Comment Utility
I've never put DB connection code in a JSP myself or I can't remember, but it should be OK - try it all out and if any problems, let me know
0
 
LVL 6

Expert Comment

by:dorothy2
Comment Utility
I haven't written jsps in a few months and I can't remember whether the scriptlet with the database info will print out if someone gets the source for a page appearing in a browser, but I think you might have a potential security problem if it does. You don't want your database URL, user name and password so accessible by the outside world. Why don't you write a DataAccess class which you call in your jsp? You could use it for every jsp where you need data access, so you don't have to keep cutting and pasting this code, and the details of your connection remain hidden from users. You can configure the DataAccess class with a properties file, or you can hardcode the database URL.

Dorothy
0
 

Author Comment

by:Bekkerus
Comment Utility
dorothy2,

 Good point. I would make a java class for that and use some kind of include into the jsp page? Would the Java class be a servlet then? Could I use something like:

import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ConnectDB extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException
     {
          //Set up DB connection
          try
          {
               Class.forName("oracle.jdbc.driver.OracleDriver");
               String url = "jdbc:oracle:thin:@mspdev01:1527:dev01";
               Connection con = DriverManager.getConnection(url, "user", "password");
               Statement stmt1 = con.createStatement();
               Statement stmt2 = con.createStatement();
               Statement stmt3 = con.createStatement();
               ResultSet rs1;    
               ResultSet rs2;
               ResultSet rs3;
          }
          catch (SQLException e)
          {
               e.printStackTrace();
          }
          catch (Exception e)
          {
               e.printStackTrace();
          }    
     }
}

How could the JSP page then use these connections? Or I am doing this all wrong?
0
 

Author Comment

by:Bekkerus
Comment Utility
How does something like this look? I will try something like this Monday morning.

<%
@ page import="ConnectDB" // the Connection class.
@ page import="LogParser" // another class I want to use.
@ page import="java.sql.*"
@ page import="java.io.*"

     File rptFolder = new File("c:\\files");
     java.util.ArrayList arr = new java.util.ArrayList();
     LogParser MyReader = new LogParser();
     String x = new String();

     Class.forName("oracle.jdbc.driver.OracleDriver");
     String url = "jdbc:oracle:thin:@mspd1:1521:de01";
     Connection con = DriverManager.getConnection(url, "user", "changeme");
     Statement stmt = con.createStatement();
     ResultSet rs;

     rs = stmt.executeQuery("select sysdate from dual");
     if (rs.next())
     {
          log("Sysdate is : " + rs.getString(1));
     }
%>
     <% rVal = rs.getString(1); %>
     <TD><%= rVal %></TD>
<%
     String rVal = new String();
     rs = stmt.executeQuery("Select * From tbl_something");
%>
     <% rVal = rs.getString(1); %>
     <P><%= rVal %></P>

<html>
<head><title>Test Page<title>
</head>
<body>

     <% rVal = rs.getString(1); %>
     <P><%= rVal %></P>

</body>
</html>
0
 
LVL 2

Expert Comment

by:bagi112599
Comment Utility
Bekkerus,
I will strongly suggest to take into account
dorothy2's advice about having DataAccess class.
Nobody (more or less professional) does explicit database
connection on Jsp or asp.
0
 

Author Comment

by:Bekkerus
Comment Utility
Yes. I forgot to remove that... How do I include an Class that would allow a login? Does any of my code look sort of correct?
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 1

Expert Comment

by:viswa081400
Comment Utility
Hi,
Create a DataAccess class that has methods to create connections, create staement's and other stuff that you require.

For example you can replace your code for database stuff with something like this:

//Incase you want your DB url, user & password to read from a properties file instead of heard coding.

DataAccess myDB = new DataAccess( fileName );

// You do all your connection stuff and etc in DataAccess class. And for futher use you just get the statement object to work.
// So have a method in DataAccess which creates a statement object for you.

Statement stmt = myDB.getStatement();
rs = ...
...
stmt.close();

// And if you define your connection objects as static, you can re-use your connection objects too!!

Hope this helps!!

-viswa

0
 
LVL 12

Expert Comment

by:ahosang
Comment Utility
After you create the DBAccess class, you can just drop it in as viswa said. Put the HTML output in the proper place though, like this:
<html>
<head><title>Test Page<title>
</head>
<body>
<table>
<tr>

<%
DBAcess myDB=new DBAccess(filename);
Statement stmt = myDB.getStatement();
...
rVal = rs.getString(1);
%>

<TD><%= rVal %></TD>
</tr>
</table>
<%
    String rVal = new String();
    rs = stmt.executeQuery("Select * From tbl_something");
%>
    <% rVal = rs.getString(1); %>
    <P><%= rVal %></P>
</body></html>

How is the JSP going?
0
 

Author Comment

by:Bekkerus
Comment Utility
-viswa

  OK I will make a connecion class and try this properties file idea. If I store it in something like c:\login\connect.txt the data within the file I would have 4 rows, something like:
username
password
database
portnumber

ahosang,

 I have not gotten too far but the experts advice here has been helpful. I am going to try and work on this again today.
0
 
LVL 1

Expert Comment

by:viswa081400
Comment Utility
good luck!!
0
 

Author Comment

by:Bekkerus
Comment Utility
OK I have worked on this pretty hard. I made this to work within a Java test class... now I have tried to make it work within my jsp page, and it does not.

Here is the .JSP:

<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<html>
<head><title>Test Page<title>
</head>
<body>
<%
     ConnectionPool myDB = new ConnectionPool();
     myDB.initialize("ConnPool.cfg");
     Connection connection = myDB.getConnection();
     Statement stmt = connection.createStatement();
     ResultSet rs;
     rs = stmt.executeQuery("Select * From bekker.tbl_x");
     String rVal = null;
%>
<table>
<tr>
<%
     while(rs.next())
     {
          rVal = rs.getString(1);
%>
          <TD><%= rVal %></TD>    
<%
     }
%>
</tr>
</table>
</body>
</html>

Here are the errors I get:
[27/Jun/2001:17:16:59] info (18710): JSP: JSP1x compiler threw exception org.apache.jasper.JasperException: Unable to compile class for JSP/usr/netscape/server4/https-devdocs/config/../ClassCache/_jsps/_support/_java/_JSPtest_jsp.java:71: Class _jsps._support._java.ConnectionPool not found.
                ConnectionPool myDB = new ConnectionPool();
                ^
/usr/netscape/server4/https-devdocs/config/../ClassCache/_jsps/_support/_java/_JSPtest_jsp.java:71: Class _jsps._support._java.ConnectionPool not found.
                ConnectionPool myDB = new ConnectionPool();
                                          ^
2 errors

        at org.apache.jasper.compiler.Compiler.compile(Compiler.java, Compiled Code)
        at com.netscape.server.http.servlet.NSServletEntity.load(NSServletEntity.java, Compiled Code)
        at com.netscape.server.http.servlet.NSServletEntity.update(NSServletEntity.java, Compiled Code)
@      
0
 
LVL 1

Expert Comment

by:viswa081400
Comment Utility
The error is because your JSP is not able to find ConnectionPool.class.

Where does your connectionPool class reside?? Is the path to this file added to your class path of your JSP engine??

A simple and quick solution is copy ConnectionPool.class into the directory where your JSP resides ( Assuming ConnectionPool class is not under any package).

-viswa
0
 
LVL 12

Expert Comment

by:ahosang
Comment Utility
ConnectionPool is obviously a class you compiled. Is that class located in the proper place in the server directories? Then remember this example line I gave in a previous comment:

<%@ page import="myPackage.myClass %>

So, something like:
<%@ page import="myPackage.ConnectionPool %>

0
 

Author Comment

by:Bekkerus
Comment Utility
It is not in a package so it is just:
<%@ page import="ConnectionPool"%>

I asked for the weblogic admin to add that to the classpath. I get this error when I try and execute:

[28/Jun/2001:08:20:18] failure (18710):
Internal error: exception thrown from the servlet
service function (uri=/support/java/JSPtest.jsp): javax.servlet.ServletException:
invalid arguments in call, Stack: javax.servlet.ServletException: invalid arguments in call
at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java, Compiled Code)
at _jsps._support._java._JSPtest_jsp._jspService(_JSPtest_jsp.java, Compiled Code)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java, Compiled Code)
at javax.servlet.http.HttpServlet.service(HttpServlet.java, Compiled Code)
at com.netscape.server.http.servlet.NSServletRunner.Service(NSServletRunner.java, Compiled Code)

What do you think? Is it still likely due to a mis-configured classpath? I might try and run this within Iplanet I have that on my machine...
0
 
LVL 1

Expert Comment

by:viswa081400
Comment Utility
Can you include the ConnectionPool Class code??
0
 

Author Comment

by:Bekkerus
Comment Utility
OK sure... it is kind of big:

import java.sql.*;


/**
 * <p>This class serves as a JDBC connection repository. Since
 * creating database connections is one of the most time
 * intensive aspects of JDBC, we'll create a pool of connections.
 * Each connection can be used and then replaced back into the
 * pool.
 *
 * <p>A properties file 'ConnPool.cfg' will be used to
 * specify the types of JDBC connections to create, as well as
 * the minimum and maximum size of the pool. The format of
 * the configuration file is:
 *
 *   #(comment)
 *   JDBCDriver=<JDBC driver name>
 *   JDBCConnectionURL=<JDBC Connection URL>
 *   ConnectionPoolSize=<minimum size of the pool>
 *   ConnectionPoolMax=<maximum size of the pool, or -1 for none>
 *   ConnectionUseCount=<maximum usage count for one connection>
 *   ConnectionTimeout=<maximum idle lifetime (in minutes) of
 *        a connection>
 *   <other property for JDBC connection>=<value>
 *
 * <p>Any number of additional properties may be given (such
 * as username and password) as required by the JDBC driver.
 *
 */

public class ConnectionPool implements TimerListener
{
  // JDBC Driver name
  String m_JDBCDriver;

  // JDBC Connection URL
  String m_JDBCConnectionURL;

  // Minimum size of the pool
  int m_ConnectionPoolSize;

  // Maximum size of the pool
  int m_ConnectionPoolMax;

  // Maximum number of uses for a single connection, or -1 for none
  int m_ConnectionUseCount;

  // Maximum connection idle time (in minutes)
  int m_ConnectionTimeout;

  // Additional JDBC properties
  java.util.Properties m_JDBCProperties;

  // The Connection pool. This is a vector of ConnectionObject objects
  java.util.Vector m_pool;

  // The maximum number of simultaneous connections as reported by the JDBC driver
  int m_MaxConnections = -1;

  // Our Timer object
  Timer m_timer;
 
  /**
    * <p>Initializes the ConnectionPool object using
    * 'ConnPool.cfg' as the configuration file
    *
    * @return true if the ConnectionPool was initialized
    * properly
    */
  public boolean initialize() throws Exception
    {
      return initialize("ConnPool.cfg");
    }

  /**
    * <p>Initializes the ConnectionPool object with the specified
    * configuration file
    *
    * @param config Configuration file name
    * @return true if the ConnectionPool was initialized
    * properly
    */
  public boolean initialize(String config) throws Exception
    {
      // Load the configuration parameters. Any leftover parameters
      // from the configuration file will be considered JDBC
      // connection attributes to be used to establish the
      // JDBC connections
      boolean rc = loadConfig(config);

      if (rc) {
        // Properties were loaded; attempt to create our pool
        // of connections
        createPool();

        // Start our timer so we can timeout connections. The
        // clock cycle will be 20 seconds
        m_timer = new Timer(this, 20);
        m_timer.start();
      }
      return rc;
    }

  /**
    * <p>Destroys the pool and it's contents. Closes any open
    * JDBC connections and frees all resources
    */
  public void destroy()
    {
      try {

        // Stop our timer thread
        if (m_timer != null) {
          m_timer.stop();
          m_timer = null;
        }

        // Clear our pool
        if (m_pool != null) {

          // Loop throught the pool and close each connection
          for (int i = 0; i < m_pool.size(); i++) {
            close((ConnectionObject) m_pool.elementAt(i));
          }
        }
        m_pool = null;
      }
      catch (Exception ex) {
        ex.printStackTrace();
      }
    }

  /**
    * <p>Gets an available JDBC Connection. Connections will be
    * created if necessary, up to the maximum number of connections
    * as specified in the configuration file.
    *
    * @return JDBC Connection, or null if the maximum
    * number of connections has been exceeded
    */
  public synchronized java.sql.Connection getConnection()
    {
      // If there is no pool it must have been destroyed
      if (m_pool == null) {
        return null;
      }

      java.sql.Connection con = null;
      ConnectionObject connectionObject = null;
      int poolSize = m_pool.size();

      // Get the next available connection
      for (int i = 0; i < poolSize; i++) {

        // Get the ConnectionObject from the pool
        ConnectionObject co = (ConnectionObject)
          m_pool.elementAt(i);

        // If this is a valid connection and it is not in use,
        // grab it
        if (co.isAvailable()) {
          connectionObject = co;
          break;
        }
      }

      // No more available connections. If we aren't at the
      // maximum number of connections, create a new entry
      // in the pool
      if (connectionObject == null) {
        if ((m_ConnectionPoolMax < 0) ||
            ((m_ConnectionPoolMax > 0) &&
             (poolSize < m_ConnectionPoolMax))) {
         
          // Add a new connection.
          int i = addConnection();
         
          // If a new connection was created, use it
          if (i >= 0) {
            connectionObject = (ConnectionObject)
              m_pool.elementAt(i);
          }
        }
        else {
          trace("Maximum number of connections exceeded");
        }
      }

      // If we have a connection, set the last time accessed,
      // the use count, and the in use flag
      if (connectionObject != null) {
        connectionObject.inUse = true;
        connectionObject.useCount++;
        touch(connectionObject);
        con = connectionObject.con;
      }
     
      return con;
    }

  /**
    * <p>Places the connection back into the connection pool,
    * or closes the connection if the maximum use count has
    * been reached
    *
    * @param Connection object to close
    */
  public synchronized void close(java.sql.Connection con)
    {
      // Find the connection in the pool
      int index = find(con);
     
      if (index != -1) {
        ConnectionObject co = (ConnectionObject)
          m_pool.elementAt(index);
       
        // If the use count exceeds the max, remove it from
        // the pool.
        if ((m_ConnectionUseCount > 0) &&
            (co.useCount >= m_ConnectionUseCount)) {
          trace("Connection use count exceeded");
          removeFromPool(index);
        }
        else {
          // Clear the use count and reset the time last used
          touch(co);
          co.inUse = false;
        }
      }
    }
 
  /**
    * <p>Prints the contents of the connection pool to the
    * standard output device
    */
  public void printPool()
    {
      System.out.println("--ConnectionPool--");
      if (m_pool != null) {
        for (int i = 0; i < m_pool.size(); i++) {
          ConnectionObject co = (ConnectionObject)
            m_pool.elementAt(i);
          System.out.println("" + i + "=" + co);
        }
      }
    }
 
  /**
    * <p>Removes the ConnectionObject from the pool at the
    * given index
    *
    * @param index Index into the pool vector
    */
  private synchronized void removeFromPool(int index)
    {
      // Make sure the pool and index are valid
      if (m_pool != null) {

        if (index < m_pool.size()) {

          // Get the ConnectionObject and close the connection
          ConnectionObject co = (ConnectionObject)
            m_pool.elementAt(index);
          close(co);

          // Remove the element from the pool
          m_pool.removeElementAt(index);
        }
      }
    }
 
  /**
    * <p>Closes the connection in the given ConnectionObject
    *
    * @param connectObject ConnectionObject
    */
  private void close(ConnectionObject connectionObject)
    {
      if (connectionObject != null) {
        if (connectionObject.con != null) {
          try {
           
            // Close the connection
            connectionObject.con.close();
          }
          catch (Exception ex) {
            // Ignore any exceptions during close
          }

          // Clear the connection object reference
          connectionObject.con = null;
        }
      }
    }
 
  /**
    * <p>Loads the given configuration file.  All global
    * properties (such as JDBCDriver) will be
    * read and removed from the properties list. Any leftover
    * properties will be returned. Returns null if the
    * properties could not be loaded
    *
    * @param name Configuration file name
    * @return true if the configuration file was loaded
    */
  private boolean loadConfig(String name)
    throws Exception
    {
      boolean rc = false;

      // Get our class loader
      ClassLoader cl = getClass().getClassLoader();

      // Attempt to open an input stream to the configuration file.
      // The configuration file is considered to be a system
      // resource.
      java.io.InputStream in;
     
      if (cl != null) {
        in = cl.getResourceAsStream(name);
      }
      else {
        in = ClassLoader.getSystemResourceAsStream(name);
      }

      // If the input stream is null, then the configuration file
      // was not found
      if (in == null) {
        throw new Exception("ConnectionPool configuration file '" +
                           name + "' not found");
      }
      else {
        try {
          m_JDBCProperties = new java.util.Properties();
         
          // Load the configuration file into the properties table
          m_JDBCProperties.load(in);

          // Got the properties. Pull out the properties that we
          // are interested in
          m_JDBCDriver = consume(m_JDBCProperties, "JDBCDriver");
          m_JDBCConnectionURL = consume(m_JDBCProperties,
                                        "JDBCConnectionURL");
          m_ConnectionPoolSize = consumeInt(m_JDBCProperties,
                                            "ConnectionPoolSize");
          m_ConnectionPoolMax = consumeInt(m_JDBCProperties,
                                           "ConnectionPoolMax");
          m_ConnectionTimeout = consumeInt(m_JDBCProperties,
                                           "ConnectionTimeout");
          m_ConnectionUseCount = consumeInt(m_JDBCProperties,
                                            "ConnectionUseCount");
          rc = true;
        }
        finally {
          // Always close the input stream
          if (in != null) {
            try {
              in.close();
            }
            catch (Exception ex) {
            }
          }
        }
      }
      return rc;
    }

  /**
    * <p>Consumes the given property and returns the value.
    *
    * @param properties Properties table
    * @param key Key of the property to retrieve and remove from
    * the properties table
    * @return Value of the property, or null if not found
    */
  private String consume(java.util.Properties p, String key)
    {
      String s = null;

      if ((p != null) &&
          (key != null)) {

        // Get the value of the key
        s = p.getProperty(key);
       
        // If found, remove it from the properties table
        if (s != null) {
          p.remove(key);
        }
      }
      return s;
    }

  /**
    * <p>Consumes the given property and returns the integer
    * value.
    *
    * @param properties Properties table
    * @param key Key of the property to retrieve and remove from
    * the properties table
    * @return Value of the property, or -1 if not found
    */
  private int consumeInt(java.util.Properties p, String key)
    {
      int n = -1;

      // Get the String value
      String value = consume(p, key);

      // Got a value; convert to an integer
      if (value != null) {
        try {
          n = Integer.parseInt(value);
        }
        catch (Exception ex) {
        }
      }
      return n;
    }

  /**
    * <p>Creates the initial connection pool. A timer thread
    * is also created so that connection timeouts can be
    * handled.
    *
    * @return true if the pool was created
    */
  private void createPool() throws Exception
    {
      // Sanity check our properties
      if (m_JDBCDriver == null) {
        throw new Exception("JDBCDriver property not found");
      }
      if (m_JDBCConnectionURL == null) {
        throw new Exception("JDBCConnectionURL property not found");
      }
      if (m_ConnectionPoolSize < 0) {
        throw new Exception("ConnectionPoolSize property not found");
      }
      if (m_ConnectionPoolSize == 0) {
        throw new Exception("ConnectionPoolSize invalid");
      }
      if (m_ConnectionPoolMax < m_ConnectionPoolSize) {
        trace("WARNING - ConnectionPoolMax is invalid and will " +
              "be ignored");
        m_ConnectionPoolMax = -1;
      }
      if (m_ConnectionTimeout < 0) {
        // Set the default to 30 minutes
        m_ConnectionTimeout = 30;
      }

      // Dump the parameters we are going to use for the pool.
      // We don't know what type of servlet environment we will
      // be running in - this may go to the console or it
      // may be redirected to a log file
      trace("JDBCDriver = " + m_JDBCDriver);
      trace("JDBCConnectionURL = " + m_JDBCConnectionURL);
      trace("ConnectionPoolSize = " + m_ConnectionPoolSize);
      trace("ConnectionPoolMax = " + m_ConnectionPoolMax);
      trace("ConnectionUseCount = " + m_ConnectionUseCount);
      trace("ConnectionTimeout = " + m_ConnectionTimeout +
            " seconds");

      // Also dump any additional JDBC properties
      java.util.Enumeration enum = m_JDBCProperties.keys();
      while (enum.hasMoreElements()) {
        String key = (String) enum.nextElement();
        String value = m_JDBCProperties.getProperty(key);
        trace("(JDBC Property) " + key + " = " + value);
      }

      // Attempt to create a new instance of the specified
      // JDBC driver. Well behaved drivers will register
      // themselves with the JDBC DriverManager when they
      // are instantiated
      trace("Registering " + m_JDBCDriver);
      java.sql.Driver d = (java.sql.Driver)
        Class.forName(m_JDBCDriver).newInstance();
     
      // Create the vector for the pool
      m_pool = new java.util.Vector();

      // Bring the pool to the minimum size
      fillPool(m_ConnectionPoolSize);
    }

  /**
    * <p>Adds a new connection to the pool
    *
    * @return Index of the new pool entry, or -1 if an
    * error has occurred
    */
  private int addConnection()
    {
      int index = -1;

      try {
        // Calculate the new size of the pool
        int size = m_pool.size() + 1;

        // Create a new entry
        fillPool(size);

        // Set the index pointer to the new connection if one
        // was created
        if (size == m_pool.size()) {
          index = size - 1;
        }
      }
      catch (Exception ex) {
        ex.printStackTrace();
      }
      return index;
    }
 
  /**
    * <p>Brings the pool to the given size
    */
  private synchronized void fillPool(int size) throws Exception
    {
      boolean useProperties = true;
      String userID = null;
      String password = null;
     
      // If the only properties present are the user id and
      // password, get the connection using them instead of
      // the properties object
      if (m_JDBCProperties != null) {
         
        // Make sure there are only 2 properties, and they are
        // the user id and password
        if (m_JDBCProperties.size() == 2) {
          userID =
            getPropertyIgnoreCase(m_JDBCProperties, "user");
          password =
            getPropertyIgnoreCase(m_JDBCProperties, "password");

          // If all we've got is a user id and password then
          // don't use the properties
          if ((userID != null) && (password != null)) {
            useProperties = false;
          }
        }
       
      }
       
      // Loop while we need to create more connections
      while (m_pool.size() < size) {
       
        ConnectionObject co = new ConnectionObject();

        // Create the connection
        if (useProperties) {
          co.con = DriverManager.getConnection(m_JDBCConnectionURL,
                                              m_JDBCProperties);
        }
        else {
          co.con = DriverManager.getConnection(m_JDBCConnectionURL,
                                               userID, password);
        }
       
        // Do some sanity checking on the first connection in
        // the pool
        if (m_pool.size() == 0) {

          // Get the maximum number of simultaneous connections
          // as reported by the JDBC driver
          java.sql.DatabaseMetaData md = co.con.getMetaData();
          m_MaxConnections = md.getMaxConnections();
        }

        // Give a warning if the size of the pool will exceed
        // the maximum number of connections allowed by the
        // JDBC driver
        if ((m_MaxConnections > 0) &&
            (size > m_MaxConnections)) {
          trace("WARNING: Size of pool will exceed safe maximum of " +
                m_MaxConnections);
        }

        // Clear the in use flag
        co.inUse = false;
       
        // Set the last access time
        touch(co);
       
        m_pool.addElement(co);
      }
    }

  /**
   * Gets a the named propery, ignoring case. Returns null if
   * not found
   * @param p The property set
   * @param name The property name
   * @return The value of the propery, or null if not found
   */
  private String getPropertyIgnoreCase(java.util.Properties p,
                                       String name)
    {
      if ((p == null) || (name == null)) return null;
     
      String value = null;
     
      // Get an enumeration of the property names
      java.util.Enumeration enum = p.propertyNames();
     
      // Loop through the enum, looking for the given property name
      while (enum.hasMoreElements()) {
        String pName = (String) enum.nextElement();
        if (pName.equalsIgnoreCase(name)) {
          value = p.getProperty(pName);
          break;
        }
      }
     
      return value;
    }
 
  /**
    * <p>Find the given connection in the pool
    *
    * @return Index into the pool, or -1 if not found
    */
  private int find(java.sql.Connection con)
    {
      int index = -1;

      // Find the matching Connection in the pool
      if ((con != null) &&
          (m_pool != null)) {
        for (int i = 0; i < m_pool.size(); i++) {
          ConnectionObject co = (ConnectionObject)
            m_pool.elementAt(i);
          if (co.con == con) {
            index = i;
            break;
          }
        }
      }
      return index;
    }
 
  /**
    * <p>Called by the timer each time a clock cycle expires.
    * This gives us the opportunity to timeout connections
    */
  public synchronized void TimerEvent(Object object)
    {
      // No pool means no work
      if (m_pool == null) {
        return;
      }

      // Get the current time in milliseconds
      long now = System.currentTimeMillis();
     
      // Check for any expired connections and remove them
      for (int i = m_pool.size() - 1; i >= 0; i--) {
        ConnectionObject co = (ConnectionObject)
          m_pool.elementAt(i);

        // If the connection is not in use and it has not been
        // used recently, remove it
        if (!co.inUse) {
          if ((m_ConnectionTimeout > 0) &&
              (co.lastAccess +
               (m_ConnectionTimeout * 1000) < now)) {
            removeFromPool(i);
          }
        }
      }

      // Remove any connections that are no longer open
      for (int i = m_pool.size() - 1; i >= 0; i--) {
        ConnectionObject co = (ConnectionObject)
          m_pool.elementAt(i);
        try {
          // If the connection is closed, remove it from the pool
          if (co.con.isClosed()) {
            trace("Connection closed unexpectedly");
            removeFromPool(i);
          }
        }
        catch (Exception ex) {
        }
      }

      // Now ensure that the pool is still at it's minimum size
      try {
        if (m_pool != null) {
          if (m_pool.size() < m_ConnectionPoolSize) {
            fillPool(m_ConnectionPoolSize);
          }
        }
      }
      catch (Exception ex) {
        ex.printStackTrace();
      }
    }
 
  /**
    * <p>Sets the last access time for the given ConnectionObject
    */
  private void touch(ConnectionObject co)
    {
      if (co != null) {
        co.lastAccess = System.currentTimeMillis();
      }
    }
 
  /**
    * <p>Trace the given string
    */
  private void trace(String s)
    {
      System.out.println("ConnectionPool: " + s);
    }
}

// This package-private class is used to represent a single
// connection object
class ConnectionObject
{
  // The JDBC Connection
  public java.sql.Connection con;

  // true if this connection is currently in use
  public boolean inUse;

  // The last time (in milliseconds) that this connection was used
  public long lastAccess;

  // The number of times this connection has been used
  public int useCount;

  /**
    * <p>Determine if the connection is available
    *
    * @return true if the connection can be used
    */
  public boolean isAvailable()
    {
      boolean available = false;

      try {

        // To be available, the connection cannot be in use
        // and must be open
        if (con != null) {
          if (!inUse &&
              !con.isClosed()) {
            available = true;
          }
        }
      }
      catch (Exception ex) {
      }
     
      return available;
    }
 
  /**
    * <p>Convert the object contents to a String
    */
  public String toString()
    {
      return "Connection=" + con + ",inUse=" + inUse +
        ",lastAccess=" + lastAccess + ",useCount=" + useCount;
    }
}
0
 
LVL 5

Expert Comment

by:vemul
Comment Utility
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:
- To be PAQ'ed and points refunded
Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

vemul
Cleanup Volunteer
0
 

Accepted Solution

by:
modulo earned 0 total points
Comment Utility
Finalized as proposed

modulo

Community Support Moderator
Experts Exchange
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Fibonacci challenge 11 81
count7 challenge 12 66
countHi challenge 25 84
wordappend challenge 8 82
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now