Search This Blog

Showing posts with label Oracle JDBC. Show all posts
Showing posts with label Oracle JDBC. Show all posts

Wednesday, 7 September 2011

Batch Inserting using Spring JDBC (JdbcTemplate)

In this small example we use the classic JdbcTemplate to complete batch processing with the Oracle JDBC driver. Although we could simply use SimpleJdbcTemplate and write less code this one just seems more natural to me. The code is assuming insertion of new records here.

Table definition
drop table jdbc_batch_table;

create table jdbc_batch_table
(message_id number primary key,
 message_type varchar2(1),
 message varchar2(100))
/

purge recyclebin;

exit;

Spring DAO - JdbcBatchDAOImpl
package pas.au.gemfire.demo.cachewriter.dao.jdbcbatch;

import java.math.BigDecimal;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import java.util.List;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.sql.DataSource;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;

public class JdbcBatchDAOImpl implements JdbcBatchDAO
{
  private Logger logger = Logger.getLogger(this.getClass().getSimpleName());
  
  private JdbcTemplate jdbcTemplate;

  public void setDataSource(DataSource dataSource)
  {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
  }
  
  @Override
  public void storeBatch(final List<JdbcBatch> jdbcBatchEntries)
  {

    int[] updateCounts = 
     jdbcTemplate.batchUpdate
      (Constants.INSERT_SQL,
       new BatchPreparedStatementSetter() 
       {
          public void setValues(PreparedStatement ps, int i) throws SQLException 
          {
              ps.setBigDecimal(1, new BigDecimal(jdbcBatchEntries.get(i).getMessageId().toString()));
              ps.setString(2, jdbcBatchEntries.get(i).getMessageType());
              ps.setString(3, jdbcBatchEntries.get(i).getMessage());
          }
          
          public int getBatchSize() 
          {
            return jdbcBatchEntries.size();                  
          }
        }
      );
    
    logger.log (Level.INFO, 
                String.format("Inserted %s records using spring jdbc batching", updateCounts.length));
  }
}

Constants Interface
package pas.au.gemfire.demo.cachewriter.dao.jdbcbatch;

public interface Constants
{
  public final String INSERT_SQL = "insert into jdbc_batch_table values (:1, :2, :3)";
}  

Output showing the insertion of 100 records at a time

Sep 7, 2011 10:03:43 PM pas.au.gemfire.demo.cachewriter.dao.jdbcbatch.JdbcBatchDAOImpl storeBatch
INFO: Inserted 100 records using spring jdbc batching
Sep 7, 2011 10:03:43 PM pas.au.gemfire.demo.cachewriter.DBGatewayListener processEvents
INFO: Size of DBGatewayListener = 100
Sep 7, 2011 10:03:43 PM pas.au.gemfire.demo.cachewriter.dao.jdbcbatch.JdbcBatchDAOImpl storeBatch
INFO: Inserted 100 records using spring jdbc batching
Sep 7, 2011 10:03:43 PM pas.au.gemfire.demo.cachewriter.DBGatewayListener processEvents
INFO: Size of DBGatewayListener = 100
Sep 7, 2011 10:03:43 PM pas.au.gemfire.demo.cachewriter.dao.jdbcbatch.JdbcBatchDAOImpl storeBatch
INFO: Inserted 100 records using spring jdbc batching
Sep 7, 2011 10:03:43 PM pas.au.gemfire.demo.cachewriter.DBGatewayListener processEvents
INFO: Size of DBGatewayListener = 100
Sep 7, 2011 10:03:44 PM pas.au.gemfire.demo.cachewriter.dao.jdbcbatch.JdbcBatchDAOImpl storeBatch
INFO: Inserted 100 records using spring jdbc batching
Sep 7, 2011 10:03:44 PM pas.au.gemfire.demo.cachewriter.DBGatewayListener processEvents
INFO: Size of DBGatewayListener = 100
Sep 7, 2011 10:03:44 PM pas.au.gemfire.demo.cachewriter.dao.jdbcbatch.JdbcBatchDAOImpl storeBatch
INFO: Inserted 100 records using spring jdbc batching

More info on Spring JDBC can be found here.

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html 

Monday, 15 August 2011

Using Oracle Universal Connection Pool with Spring from JDeveloper 11.1.2

In this example we simply setup Oracle UCP to be used by Spring from JDeveloper 11g 11.1.2. When using read write backing maps with Oracle Coherence that are using a back end database such as RAC it's UCP RAC integration which makes this UCP the ideal choice. In this example we are just using a single instance Oracle database but can easily add the FCF properties required for UCP.

1. Create a spring framework beans.xml file as follows
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="ucpDataSource" class="oracle.ucp.jdbc.PoolDataSourceFactory" factory-method="getPoolDataSource">
      <property name="URL" value="jdbc:oracle:thin:@beast.au.oracle.com:1524/linux11gr2" />
      <property name="user" value="scott" />
      <property name="password" value="tiger" />
      <property name="connectionFactoryClassName" value="oracle.jdbc.pool.OracleDataSource" />
      <property name="connectionPoolName" value="TEST_POOL" />
      <property name="minPoolSize" value="1" />
      <property name="maxPoolSize" value="10" />
      <property name="initialPoolSize" value="1" />
    </bean>
    
  <bean id="ucpJDBCTest" class="pas.au.spring.demo.ucp.test.TestJDBC">
    <property name="dataSource" ref="ucpDataSource"/>
  </bean>
  
</beans> 

2. Add the required libraries to the project


3. Create the TestJDBC class as follows
package pas.au.spring.demo.ucp.test;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

public class TestJDBC
{
  private JdbcTemplate jdbcTemplate;

  public void setDataSource(DataSource dataSource)
  {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
  }
  
  public void insertDept()
  {
    /**
     * Specify the insert values 
     */
    jdbcTemplate.update("insert into dept values (:1, :2, :3)", 
                        new Object[] 
                        { 
                          Integer.valueOf(89),
                          "Pas", 
                          "Spring"
                        });
  }
}

4. Create Main test class as follows.
package pas.au.spring.demo.ucp.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main
{
  public static void main(String[] args)
  {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    TestJDBC testJDBC = (TestJDBC) context.getBean("ucpJDBCTest");
    testJDBC.insertDept();
    System.out.println("all done..");
  }
}

5. Run and verify output as follows

Aug 15, 2011 8:52:42 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@b753f8: startup date [Mon Aug 15 08:52:42 EST 2011]; root of context hierarchy
Aug 15, 2011 8:52:42 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Aug 15, 2011 8:52:43 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3411a: defining beans [ucpDataSource,ucpJDBCTest]; root of factory hierarchy
all done..

6. Verify insertion from SQL*Plus
c:\temp>sqlplus scott/tiger@linux11gr2

SQL*Plus: Release 11.2.0.1.0 Production on Mon Aug 15 08:53:31 2011

Copyright (c) 1982, 2010, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> select * from dept;

    DEPTNO DNAME          LOC
---------- -------------- -------------
        50 MARKETING      MELBOURNE
        10 ACCOUNTING     NEW YORK
        20 RESEARCH       DALLAS
        30 SALES          CHICAGO
        40 OPERATIONS     BOSTON
        89 Pas            Spring

6 rows selected.

Wednesday, 25 May 2011

Intermittent Oracle JDBC Connection Failures to RAC

More often then not I get the following come my way regarding Oracle JDBC connections to a RAC Cluster.

"My JDBC connections to a RAC cluster intermittently fail every now and then, but SQL*Plus works fine?"

Here is a little demo that will enable you to continually get JDBC connections to the RAC cluster , waiting for a connection failure. Nice way to verify if indeed there are intermittent problems from ORACLE JDBC when connecting to the cluster. We use the ScheduledExecutorService to get connections periodically and never terminate until we get a connection request failure. This demo is using an 11g R2 cluster with SCAN.

PeriodicJDBCRacTester.java (Main class to run the test)
package pas.au.jdbc.rac;

import java.io.FileInputStream;

import java.text.DateFormat;

import java.util.Date;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class PeriodicJDBCRacTester
{
  private static final DateFormat DATEFORMAT = DateFormat.getInstance();
  private String periodString = "30";
  private String url = null;
  private String user = null;
  private String passwd = null;
  private static Properties myProperties = new Properties();
  
  public PeriodicJDBCRacTester()
  {
    try
    {
      myProperties.load(new FileInputStream("jdbcractest.properties"));
      processProps(myProperties);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
  
  public void run()
  {
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    try 
    {

      LoadBalanceTest loadBalanceTest = 
         new LoadBalanceTest(url, user, passwd);

      String periodString = "30";
      int prd = Integer.parseInt(periodString);
      long period = (long) prd;
      
      System.out.println("\nPeriodic JDBC Load Balance Test ");
      System.out.println("Period to report results in seconds is : " + period + "\n");
     
      System.out.printf("** Started [%s] with %s(sec) interval between runs **\n", 
                        DATEFORMAT.format(new Date()),
                        periodString);
      
      final ScheduledFuture jdbcRacMonitor = 
          scheduler.scheduleAtFixedRate(loadBalanceTest, 0, 30, 
                                        TimeUnit.SECONDS);
                                       
              
    } 
    catch (Exception ex) 
    {
      ex.printStackTrace();
    } 
  }

  private void processProps(Properties inProps)
  {
    periodString = inProps.getProperty("period");
    url = inProps.getProperty("url");
    user = inProps.getProperty("user");
    passwd = inProps.getProperty("passwd");
  }
  
  public static void main(String[] args)
  {
    PeriodicJDBCRacTester test = new PeriodicJDBCRacTester();
    test.run();
  }
}  

LoadBalanceTest.java (Test class which is called periodically which obtains connections)
package pas.au.jdbc.rac;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.text.DateFormat;

import java.util.Date;

import oracle.jdbc.pool.OracleDataSource;

public class LoadBalanceTest implements Runnable
{
  private static final DateFormat DATEFORMAT = DateFormat.getInstance();
  
  private OracleDataSource ods = null;
  public final String userId = "scott";
  public final String password = "tiger";

  private String url = null;
  
  public LoadBalanceTest(String url, String user, String password) throws SQLException
  {
    ods = new OracleDataSource();
    ods.setUser(user);
    ods.setPassword(password);
    ods.setURL(url);  
    
    this.url = url;
    
  }

  public Connection getConnection() throws SQLException
  {
    return ods.getConnection();
  }
  
  public void run ()
  {
    Connection[] connArray = new Connection[5];
    System.out.println("\nCurrent run started at " + new Date());
    System.out.println("Obtaining 5 connections");
    try
    {
      for (int i = 0; i < connArray.length; i++)
      {
        connArray[i] = getConnection();
      }

      for (int j = 0; j < connArray.length; j++)
      {
        if (j == 0)
        {
          DatabaseMetaData meta = connArray[j].getMetaData();
          System.out.println("using URL : " + url + "\n");
          // gets driver info:

          System.out.println("=============\nDatabase Product Name is ... " +
                             meta.getDatabaseProductName());
          System.out.println("Database Product Version is  " +
                             meta.getDatabaseProductVersion());
          System.out.println("=============\nJDBC Driver Name is ........ " +
                             meta.getDriverName());
          System.out.println("JDBC Driver Version is ..... " +
                             meta.getDriverVersion());
          System.out.println("JDBC Driver Major Version is " +
                             meta.getDriverMajorVersion());
          System.out.println("JDBC Driver Minor Version is " +
                             meta.getDriverMinorVersion());
          System.out.println("=============");
        }

        getInstanceDetails(connArray[j], j);
      }

      System.out.println("Closing Connections\n");
      for (int y = 0; y < connArray.length; y++)
      {
        connArray[y].close();
      }
    }
    catch (SQLException sqle)
    {
      // TODO: Add catch code
      sqle.printStackTrace();
    }
  }

  public void getInstanceDetails (Connection conn, int i) throws SQLException
  {
    String sql = 
      "select sys_context('userenv', 'instance_name'), " + 
      "sys_context('userenv', 'server_host'), " + 
      "sys_context('userenv', 'service_name') " + 
      "from dual";
    
    Statement stmt = conn.createStatement();
    ResultSet rset = stmt.executeQuery(sql);
    while (rset.next())
    {
      System.out.println
        ("Connection #" + i + " : instance[" + rset.getString(1) + "], host[" + 
         rset.getString(2) + "], service[" + rset.getString(3) + "]");
    }
   
    stmt.close();
    rset.close();
  }
}
jdbcractest.properties (Properties file used to connect to the cluster and define the period in seconds for when the test will run)

period=30
url=jdbc:oracle:thin:@apctcsol1.au.oracle.com:1521/pas_srv
user=scott
passwd=tiger

If you want to run this with ANT you can use a build.xml as follows.
<?xml version="1.0" encoding="windows-1252" ?>

<project default="run" name="JDBCRACTester" basedir=".">

  <property file="build.properties"/>
   
  <path id="j2ee.classpath">
    <pathelement path="./lib/ojdbc6.jar"/>
    <pathelement path="./lib/JDBCRACTester.jar"/>
  </path>

  <property name="src.dir" value="src"/>
  <property name="classes.dir" value="classes"/>
  <property name="lib.dir" value="lib"/>
  <property name="class.name" value="pas.au.jdbc.rac.PeriodicJDBCRacTester"/>
  
  <target name="init">
    <tstamp/>
    <mkdir dir="${lib.dir}"/>
    <mkdir dir="${classes.dir}"/>
  </target>
  
  <target name="clean" description="Clean lib, classes directories">
    <delete dir="${classes.dir}"/>
  </target>
  
  <target name="compile" description="Compiles classes into ${classes.dir}" depends="init">
    <javac includeantruntime="false" srcdir="${src.dir}" debug="true" destdir="${classes.dir}" 
           includes="**/*.java" >
      <classpath refid="j2ee.classpath"/>
    </javac>
  </target>

  <target name="package" depends="compile" description="Package application into ${ant.project.name}.jar">
    <jar basedir="${classes.dir}" destfile="${lib.dir}/${ant.project.name}.jar">
      <include name="**/*.class"/>
    </jar>
  </target>
  
  <target name="run" depends="package" description="Run the JDBC RAC Tester application">
    <echo message="Running the JDBC RAC Tester application"/>
    <java classname="${class.name}" fork="true">
      <classpath>
        <path refid="j2ee.classpath"/>
        <path path="${lib.dir}/${ant.project.name}.jar"/>
      </classpath>
    </java>
  </target>

</project>

Output (Run using ANT) 

  run:
     [echo] Running the JDBC RAC Tester application
     [java]
     [java] Periodic JDBC Load Balance Test
     [java] Period to report results in seconds is : 30
     [java]
     [java] ** Started [5/25/11 9:38 AM] with 30(sec) interval between runs **
     [java]
     [java] Current run started at Wed May 25 09:38:59 EST 2011
     [java] Obtaining 5 connections
     [java] using URL : jdbc:oracle:thin:@apctcsol1.au.oracle.com:1521/pas_srv
     [java]
     [java] =============
     [java] Database Product Name is ... Oracle
     [java] Database Product Version is  Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - Production
     [java] With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
     [java] Data Mining and Real Application Testing options
     [java] =============
     [java] JDBC Driver Name is ........ Oracle JDBC driver
     [java] JDBC Driver Version is ..... 11.2.0.2.0
     [java] JDBC Driver Major Version is 11
     [java] JDBC Driver Minor Version is 2
     [java] =============
     [java] Connection #0 : instance[A12], host[auw2k4], service[pas_srv]
     [java] Connection #1 : instance[A11], host[auw2k3], service[pas_srv]
     [java] Connection #2 : instance[A12], host[auw2k4], service[pas_srv]
     [java] Connection #3 : instance[A11], host[auw2k3], service[pas_srv]
     [java] Connection #4 : instance[A12], host[auw2k4], service[pas_srv]
     [java] Closing Connections
     [java]
     [java]
     [java] Current run started at Wed May 25 09:39:29 EST 2011
     [java] Obtaining 5 connections
     [java] using URL : jdbc:oracle:thin:@apctcsol1.au.oracle.com:1521/pas_srv
     [java]
     [java] =============
     [java] Database Product Name is ... Oracle
     [java] Database Product Version is  Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - Production
     [java] With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
     [java] Data Mining and Real Application Testing options
     [java] =============
     [java] JDBC Driver Name is ........ Oracle JDBC driver
     [java] JDBC Driver Version is ..... 11.2.0.2.0
     [java] JDBC Driver Major Version is 11
     [java] JDBC Driver Minor Version is 2
     [java] =============
     [java] Connection #0 : instance[A12], host[auw2k4], service[pas_srv]
     [java] Connection #1 : instance[A11], host[auw2k3], service[pas_srv]
     [java] Connection #2 : instance[A12], host[auw2k4], service[pas_srv]
     [java] Connection #3 : instance[A11], host[auw2k3], service[pas_srv]
     [java] Connection #4 : instance[A11], host[auw2k3], service[pas_srv]
     [java] Closing Connections
     [java]

Friday, 29 April 2011

RESTful SQL Query Service using XML SQL Utility (XSU) API

A little demo showing how easily we can create a SQL query utility using Oracle's XML SQL Utility (XSU) within a JAX-RS Web Service. Although basic you can easily create more query parameters to take full advantage of the XML SQL Utility (XSU) API.

1. Create a JAX-RS Web Service as follows.
package pas.au.xmlsql.services;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import javax.sql.DataSource;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import oracle.xml.parser.v2.XMLDocument;
import oracle.xml.sql.query.OracleXMLQuery;

@Path ("/queryservice") 
public class QueryService
{
  private DataSource ds = null;
  private final String dataSourceLocation = "jdbc/scottDS";
  
  public QueryService()
  {
    Context context;  
    try  
    {  
      context = getInitialContext();  
      // lookup data source at this point
      ds = (DataSource) context.lookup (dataSourceLocation);
    }  
    catch (NamingException e)  
    {  
      throw new RuntimeException (e.getMessage());  
    } 
  }

  private Connection getConnection () throws SQLException
  {
    return ds.getConnection();  
  }
  
  private static Context getInitialContext() throws NamingException  
  {  
    return new InitialContext();  
  }

  @GET
  @Path("/query")
  @Produces(MediaType.APPLICATION_XML)
  public XMLDocument runQuery (@QueryParam("sql")String querySql)
  {
    Connection conn = null;
    OracleXMLQuery qry = null;
    XMLDocument domDoc = null;
    
    try
    {
      conn = getConnection();
      System.out.println("Query is -> " + querySql);
      qry = new OracleXMLQuery(conn, querySql);
      domDoc = (XMLDocument)qry.getXMLDOM();
      return domDoc;
    }
    catch (Exception e)
    {
      throw new RuntimeException
        (String.format("Error running query [%s]", querySql), e);
    }
    finally
    {
      /* 
       * if exception occurs here no real need to log it just catch it and continue
       */

      if (qry != null)
      {
        qry.close();
      }
      
      if (conn != null)
      {
        try
        {
          conn.close();
        }
        catch (SQLException s)
        {}
      }
    }
    
    
  }
}  

Note: From the code above we lookup a data source using the JNDI name "jdbc/scottDS" which exists for the Integrated Server. You will need to create that for this demo to work.

2. Ensure you add the required libraries within JDeveloper. Apart from the Jersey libraries for JAX-RS you will need the 3 extra libraries as shown below.


3. Run Query Service and eventually it should show it's ready as follows.

[01:28:26 PM] ----  Deployment finished.  ----
Run startup time: 4461 ms.
[Application XMLSQLUtility deployed to Server Instance IntegratedWebLogicServer]

Target Application WADL -- http://localhost:7101/xmlsql-service/jersey/application.wadl

Target URL -- http://localhost:7101/xmlsql-service/jersey/queryservice/query?sql=string

4. Now using "curl" run some queries as shown below. Of course it only accepts SQL queries but still useful enough.

Query: select user from dual

[oracle@beast pas]$ curl http://paslap-au.au.oracle.com:7101/xmlsql-service/jersey/queryservice/query?sql="select user from dual"

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ROWSET>
  <ROW num="1"><USER>SCOTT</USER></ROW>
</ROWSET>

Query: select * from dept

[oracle@beast pas]$ curl http://paslap-au.au.oracle.com:7101/xmlsql-service/jersey/queryservice/query?sql="select * from dept"

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ROWSET>
<ROW num="1"><DEPTNO>10</DEPTNO><DNAME>ACCOUNTING</DNAME><LOC>NEW YORK</LOC</ROW>
<ROW num="2"><DEPTNO>20</DEPTNO><DNAME>RESEARCH</DNAME><LOC>DALLAS</LOC></ROW>
<ROW num="3"><DEPTNO>30</DEPTNO><DNAME>SALES</DNAME><LOC>CHICAGO</LOC></ROW>
<ROW num="4"><DEPTNO>40</DEPTNO><DNAME>OPERATIONS</DNAME><LOC>BOSTON</LOC></ROW></ROWSET>

Tuesday, 26 April 2011

Display DATE columns from Oracle JDBC

If we display a DATE column from a Oracle JDBC program we may not get the desired output. This basic demo shows how to format the display to meet your own needs using the toText method from a oracle.sql.DATE object.

Code
package pas.au.jdbc.dates;

import java.sql.Connection;
import java.sql.SQLException;

import java.util.Date;

import oracle.jdbc.OracleResultSet;
import oracle.jdbc.OracleStatement;
import oracle.jdbc.pool.OracleDataSource;

import oracle.sql.DATE;


public class FormatDateJDBC
{
  private OracleDataSource ods = null;
  private final String userId = "scott";
  private final String password = "tiger";
  private final String url = 
    "jdbc:oracle:thin:@beast.au.oracle.com:1524/linux11gr2";
  
  public FormatDateJDBC() throws SQLException
  {
    ods = new OracleDataSource();
    ods.setUser(userId);
    ods.setPassword(password);
    ods.setURL(url);
  }

  public Connection getConnection() throws SQLException
  {
    return ods.getConnection();
  }

  public void run()
  {
    Connection conn = null;
    OracleStatement stmt = null;
    OracleResultSet rset = null;
    
    try
    {
      conn = getConnection();
      System.out.println(conn);
      stmt = (OracleStatement)conn.createStatement();
      rset = (OracleResultSet) stmt.executeQuery("select SYSDATE from dual");
      rset.next();
      if (rset != null)
      { 
        DATE todaysDate = rset.getDATE(1);
        System.out.println
          (String.format("Todays date is %s", 
                         todaysDate.toText("DD/MM/YY HH:MM:SS", null)));
      }
    }
    catch (SQLException se)
    {
      se.printStackTrace();
    }
    finally
    {
      /* 
       * if exception occurs here no real need to log it just catch it and continue
       */
      if (rset != null)
      {
        try
        {
          rset.close();
        }
        catch (SQLException s)
        {}
      }
      
      if (stmt != null)
      {
        try
        {
          stmt.close();
        }
        catch (SQLException s)
        {}
      }     

      if (conn != null)
      {
        try
        {
          conn.close();
        }
        catch (SQLException s)
        {}
      }
    }
  }
  
  public static void main(String[] args)
  {
    FormatDateJDBC demo = null;
    try
    {
      System.out.println("Started JDBC display date at " + new Date());
      demo = new FormatDateJDBC();
      demo.run();
      System.out.println("Completed JDBC display date at " + new Date());
    }
    catch (SQLException e)
    {
      e.printStackTrace();
      System.exit(-1);
    }
  }
}

Output

Started JDBC display date at Tue Apr 26 11:07:59 EST 2011
oracle.jdbc.driver.T4CConnection@c24c0
Todays date is 26/04/11 10:04:38
Completed JDBC display date at Tue Apr 26 11:08:00 EST 2011

Wednesday, 9 March 2011

How-To: Use Oracle WebLogic Server with a JDBC GridLink Data Source

This recently created how-to I created show's how to configure and test your new Oracle WebLogic 10.3.4 JDBC GridLink Data Source. The demo here is using an 11g R2 RAC cluster with SCAN. The link is as follows which includes a web test client.

http://www.oracle.com/technetwork/middleware/weblogic/wls-jdbc-gridlink-howto-333331.html

Thursday, 17 February 2011

JRuby Script to Monitor a Oracle WebLogic GridLink Data Source Remotely

In WebLogic 10.3.4 release, a single data source implementation has been introduced to support Oracle RAC cluster. To simplify and consolidate its support for Oracle RAC, WebLogic Server has provided a single data source that is enhanced to support the capabilities of Oracle RAC.  It provides a single connection pool/data source within Oracle WebLogic Server that supports the consumption of database services in an unrestricted manner. For more information on this see the URL below.

http://download.oracle.com/docs/cd/E17904_01/web.1111/e13737/gridlink_datasources.htm

In the example below we show how we can monitor this new Active GridLink Data Source from a JRuby script to get runtime information as the Data Source is in use from the MBean. In this example we are assuming our Data Source has a name "jdbc/gridlinkDS" which was created in the console of WebLogic itself.

1. Determine the remote connection URL to connect to WebLogic 10.3.4. The URL will be something as follows which shows are are connecting to the runtime MBean server of the managed server itself. In short this will be where you have targeted your GridLink Data Source to, it's not the ADMIN SERVER it's the managed server itself.

Format:

service:jmx:iiop://{hostname}:{managed-server-port}/jndi/weblogic.management.mbeanservers.runtime

Example:

service:jmx:iiop://wayne-p2.au.oracle.com:7003/jndi/weblogic.management.mbeanservers.runtime

2. At this point it's worth connecting using JConsole remotely to the WebLogic server using the URL above as this will help you see how the MBeans are structured and what you then need to alter the JRuby script with. Start jconsole ensuring your using wlfullclient.jar in the classpath from $WLS_HOME/server/lib directory.

Windows Example: (Connecting to a remote linux x86 server)

> jconsole -J-Djava.class.path=C:\jdev\weblogic-client\1034\wlfullclient.jar;C:\jdev\jdk\jdk1.6.0_21\lib\jconsole.jar -J-Djmx.remote.protocol.provider.pkgs=weblogic.management.remote

3. Connect using the service url from #1 above and with your username/password for the managed server where the GridLink Data Source is targeted for.



4. Click on the "MBeans" tab

5. At this point we want to determine what the MBean for the GridLink Data Source is but also what the MBean names are for the instances within the RAC cluster. To do that click on "com.bea" using the + symbol to expand the tree.

6. Scroll down and locate your GridLink Data Source in this case it's "jdbc/gridlinkDS" , use the + symbol to expand the tree

7. Click on the + symbol next to "JDBCOracleDataSourceRuntime"

8. Now actually click on "JDBCOracleDataSourceRuntime" to reveal the MBean name for the actual GidLink Data Source. Make a note of it which is displayed in the field "Object Name" in the right hand side of the dialog.

com.bea:ServerRuntime=apple,Name=jdbc/gridlinkDS,Type=JDBCOracleDataSourceRuntime

9. Select the "Attributes" node in the tree to view the GridLink Data Source runtime attributes.

10. Double click on the "Instances" Value field to reveal the MBean names for the individual instances within your cluster. Make a note of them as we will need them shortly. For my example there as follows.

com.bea:ServerRuntime=apple,Name=A11,Type=JDBCOracleDataSourceInstanceRuntime,JDBCOracleDataSourceRuntime=jdbc/gridlinkDS
com.bea:ServerRuntime=apple,Name=A12,Type=JDBCOracleDataSourceInstanceRuntime,JDBCOracleDataSourceRuntime=jdbc/gridlinkDS

11. Create a test client as follows
require 'java'
require 'rubygems'
require 'jmx4r'
require 'C:/jdev/weblogic-client/1034/wlfullclient.jar'

java_import 'javax.management.ObjectName'
java_import java.lang.System

class MonitorGridLinkDataSource
  def initialize(user, passwd, url)
    System.setProperty("jmx.remote.protocol.provider.pkgs", "weblogic.management.remote")
    @user, @passwd, @url = user, passwd, url
       
    @conn = JMX::MBean.establish_connection :url => @url, :username => @user, :password => @passwd 
  end

  # add getters and setters for all attrributes we wish to expose    
  attr_reader :user, :passwd, :url, :conn
  
  def display_array (value)
    data = "" 
    value.each do |x|
      data += "\n\t" + x.to_s
    end
    return data
  end

  def display_attribute_data(conn, object_name, attribute)  
    s = conn.get_attribute object_name, attribute
    search_str = s.to_s
    if (/^\[Ljava.lang.String/.match(search_str)) or 
       (/^\[I/.match(search_str)) or
       (/^\[Ljavax.management.ObjectName/.match(search_str))
      # we have a array with data
      return display_array s
    else
      return search_str
    end 
  end
  
  def to_s    
    "MonitorGridLinkDataSource [user=#{@user}, passwd=#{@passwd}, " +    
    "url=#{@url}]"    
  end  
  
  def run(parent_ds_runtime_mbean_name, child_ds_instances)

    mbean = JMX::MBean.find_by_name parent_ds_runtime_mbean_name
    object_name = ObjectName.new parent_ds_runtime_mbean_name

    #
    # Display main JDBC grindlink Data Source MBean info
    # 
    printf "\n** JDBC GridLink Data Source mbean \"jdbc/gridlinkDS\" ** \n\n"

    # display attributes key/values
    mbean.attributes.each do |key, value|  
     puts "Name: #{value}, Value: #{display_attribute_data conn, object_name, value}\n"
    end

    #
    # Now display info about each RAC instances within the gridlink DS
    #
    # Note: there will be as many instances as your RAC cluster contains here, in my case 
    # just a 2 node RAC cluster here

    child_ds_instances.each {|mbean_name| 
      ds1_mbean = JMX::MBean.find_by_name mbean_name
      object_name1 = ObjectName.new mbean_name
      
      printf "\n** Instance MBean \n\t[#{mbean_name}] \n\n"
      ds1_mbean.attributes.each do |key, value|  
       puts "Name: #{value}, Value: #{display_attribute_data conn, object_name1, value}\n"
      end
    }
    
  end

end

print "Run at ", Time.now , "\n"

#Connection details to MBeanServer within Weblogic 10.3.4 
url = "service:jmx:iiop://wayne-p2.au.oracle.com:7003/jndi/weblogic.management.mbeanservers.runtime"
username = "weblogic"
password = "welcome1"

# parent GridLink Data Source MBean name
parent_ds_runtime_mbean_name = 
      "com.bea:ServerRuntime=apple,Name=jdbc/gridlinkDS,Type=JDBCOracleDataSourceRuntime"
      
# child instance MBean array, add for each instance in the RAC cluster
child_ds_instances = 
  ["com.bea:ServerRuntime=apple,Name=A11,Type=JDBCOracleDataSourceInstanceRuntime,JDBCOracleDataSourceRuntime=jdbc/gridlinkDS", 
   "com.bea:ServerRuntime=apple,Name=A12,Type=JDBCOracleDataSourceInstanceRuntime,JDBCOracleDataSourceRuntime=jdbc/gridlinkDS"]

begin
  mon_grid_link_ds = MonitorGridLinkDataSource.new username, password, url
  puts mon_grid_link_ds
  while (true)
    mon_grid_link_ds.run parent_ds_runtime_mbean_name, child_ds_instances
    # sleep for 20 seconds
    puts "\nSleeping for 20 seconds....\n"   
    sleep 20
  end
rescue 
  print "\n** Error occured **\n"
 print "Failed executing GridLink Data Source Monitoring from JRuby ", $!, "\n"  
end

print "\nEnded at ", Time.now , "\n" 

12. Edit the following lines as per the information we collected above.

require 'C:/jdev/weblogic-client/1034/wlfullclient.jar'
...

#Connection details to MBeanServer within Weblogic 10.3.4 
url = "service:jmx:iiop://wayne-p2.au.oracle.com:7003/jndi/weblogic.management.mbeanservers.runtime"
username = "weblogic"
password = "welcome1"

# parent GridLink Data Source MBean name
parent_ds_runtime_mbean_name = 
      "com.bea:ServerRuntime=apple,Name=jdbc/gridlinkDS,Type=JDBCOracleDataSourceRuntime"
      
# child instance MBean array, add for each instance in the RAC cluster
child_ds_instances = 
["com.bea:ServerRuntime=apple,Name=A11,Type=JDBCOracleDataSourceInstanceRuntime,JDBCOracleDataSourceRuntime=jdbc/gridlinkDS", 
 "com.bea:ServerRuntime=apple,Name=A12,Type=JDBCOracleDataSourceInstanceRuntime,JDBCOracleDataSourceRuntime=jdbc/gridlinkDS"]

...



Note: We previously installed "jmx4r" ruby gem to allow us to use JMX API to communicate with the WebLogic server as follows


> jruby -S gem install jmx4r

13. Run the JRuby script as follows it will continually run sleeping every 20 seconds to display runtime information regarding your GridLink Data Source. To end it simply use CNRL-C to stop it running.

> jruby gridlink-monitor.rb

Output

Run at Thu Feb 17 21:55:32 +1100 2011
MonitorGridLinkDataSource [user=weblogic, passwd=welcome1, url=service:jmx:iiop://wayne-p2.au.oracle.com:7003/jndi/weblogic.management.mbean
servers.runtime]


** JDBC GridLink Data Source mbean "jdbc/gridlinkDS" **


Name: ActiveConnectionsCurrentCount, Value: 0
Name: WaitingForConnectionFailureTotal, Value: 0
Name: Instances, Value:
        com.bea:ServerRuntime=apple,Name=A11,Type=JDBCOracleDataSourceInstanceRuntime,JDBCOracleDataSourceRuntime=jdbc/gridlinkDS
        com.bea:ServerRuntime=apple,Name=A12,Type=JDBCOracleDataSourceInstanceRuntime,JDBCOracleDataSourceRuntime=jdbc/gridlinkDS
Name: FailedRCLBBasedBorrowCount, Value: 0
Name: WaitingForConnectionTotal, Value: 0
Name: ConnectionsTotalCount, Value: 28
Name: SuccessfulRCLBBasedBorrowCount, Value: 0
Name: DriverVersion, Value: 11.2.0.2.0
Name: WaitingForConnectionCurrentCount, Value: 0
Name: LeakedConnectionCount, Value: 0
Name: HighestNumUnavailable, Value: 20
Name: PrepStmtCacheAccessCount, Value: 0
Name: LastTask, Value:
Name: Parent, Value: com.bea:Name=apple,Type=ServerRuntime
Name: WaitSecondsHighCount, Value: 0
Name: ActiveConnectionsHighCount, Value: 20
Name: FailedAffinityBasedBorrowCount, Value: 0
Name: PrepStmtCacheHitCount, Value: 0
Name: ActiveConnectionsAverageCount, Value: 0
Name: VersionJDBCDriver, Value: oracle.jdbc.OracleDriver
Name: DatabaseProductVersion, Value: Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
Data Mining and Real Application Testing options
Name: SuccessfulAffinityBasedBorrowCount, Value: 0
Name: PrepStmtCacheDeleteCount, Value: 0
Name: ReserveRequestCount, Value: 36
Name: FailuresToReconnectCount, Value: 0
Name: WaitingForConnectionHighCount, Value: 0
Name: PrepStmtCacheMissCount, Value: 0
Name: Enabled, Value: true
Name: FailedReserveRequestCount, Value: 0
Name: Type, Value: JDBCOracleDataSourceRuntime
Name: HighestNumAvailable, Value: 20
Name: WorkManagerRuntimes, Value:
Name: DatabaseProductName, Value: Oracle
Name: ONSClientRuntime, Value: com.bea:ServerRuntime=apple,Name=jdbc/gridlinkDS,Type=ONSClientRuntime,JDBCOracleDataSourceRuntime=jdbc/gridl
inkDS
Name: Properties, Value: {user=scott}
Name: CurrCapacityHighCount, Value: 20
Name: PrepStmtCacheCurrentSize, Value: 0
Name: ServiceName, Value:
Name: JDBCDriverRuntime, Value:
Name: WaitingForConnectionSuccessTotal, Value: 0
Name: NumUnavailable, Value: 0
Name: PrepStmtCacheAddCount, Value: 0
Name: DriverName, Value: Oracle JDBC driver
Name: NumAvailable, Value: 20
Name: ModuleId, Value: jdbc/gridlinkDS
Name: Name, Value: jdbc/gridlinkDS
Name: State, Value: Running
Name: ConnectionDelayTime, Value: 133
Name: DeploymentState, Value: 2
Name: CurrCapacity, Value: 20


** Instance MBean
        [com.bea:ServerRuntime=apple,Name=A11,Type=JDBCOracleDataSourceInstanceRuntime,JDBCOracleDataSourceRuntime=jdbc/gridlinkDS]


Name: Parent, Value: com.bea:ServerRuntime=apple,Name=jdbc/gridlinkDS,Type=JDBCOracleDataSourceRuntime
Name: Enabled, Value: true
Name: ActiveConnectionsCurrentCount, Value: 0
Name: Type, Value: JDBCOracleDataSourceInstanceRuntime
Name: NumAvailable, Value: 10
Name: Signature, Value: instance=A11,service=pas_srv,database=A1,host=auw2k3
Name: CurrentWeight, Value: 1
Name: Name, Value: A11
Name: ConnectionsTotalCount, Value: 14
Name: ReserveRequestCount, Value: 19
Name: State, Value: Enabled
Name: NumUnavailable, Value: 0
Name: CurrCapacity, Value: 10
Name: InstanceName, Value: A11


** Instance MBean
        [com.bea:ServerRuntime=apple,Name=A12,Type=JDBCOracleDataSourceInstanceRuntime,JDBCOracleDataSourceRuntime=jdbc/gridlinkDS]


Name: Parent, Value: com.bea:ServerRuntime=apple,Name=jdbc/gridlinkDS,Type=JDBCOracleDataSourceRuntime
Name: Enabled, Value: true
Name: ActiveConnectionsCurrentCount, Value: 0
Name: Type, Value: JDBCOracleDataSourceInstanceRuntime
Name: NumAvailable, Value: 10
Name: Signature, Value: instance=A12,service=pas_srv,database=A1,host=auw2k4
Name: CurrentWeight, Value: 1
Name: Name, Value: A12
Name: ConnectionsTotalCount, Value: 14
Name: ReserveRequestCount, Value: 17
Name: State, Value: Enabled
Name: NumUnavailable, Value: 0
Name: CurrCapacity, Value: 10
Name: InstanceName, Value: A12


Sleeping for 20 seconds....

Friday, 4 February 2011

JRuby Script to Verify Your 11g R2 RAC Setup using SCAN

The following demo can be used to verify failover using an 11g R2 (11.2.0.2) RAC cluster from a JRuby script. For this example we are using an Oracle UCP Pool setup to use FCF to receive FAN events / notifications.

1. Download ucp.jar and ojdbc6.jar from the links below.

ojdbc6.jar (11.2.0.2)
ucp.jar (11.2.0.1)

2. In a "lib" sub directory create a JRuby script called "ucppool-singleton.rb" with content as follows
require 'java'
require 'C:/jdev/jdcbdrivers/11.2/11202/ojdbc6.jar'
require 'C:/jdev/jdcbdrivers/11.2/11202/ons.jar'
require 'C:/jdev/jdcbdrivers/11.2/ucp/ucp.jar'

java_import 'oracle.ucp.jdbc.PoolDataSource'
java_import 'oracle.ucp.jdbc.PoolDataSourceFactory'

API_VERSION = 1.0

class MyOracleUcpPool
   
   def load_properties(properties_filename)
    properties = {}
    File.open(properties_filename, 'r') do |properties_file|
      properties_file.read.each_line do |line|
        line.strip!
        if (line[0] != ?# and line[0] != ?=)
          i = line.index('=')
          if (i)
            properties[line[0..i - 1].strip] = line[i + 1..-1].strip
          else
            properties[line] = ''
          end
        end
      end      
    end
    return properties
  end
  
  def initialize()
    props = load_properties(File.dirname(__FILE__) + "/ucp.properties")

    @user = props["user"]
    @passwd = props["password"]
    @url = props["url"]
    @minsize = props["minpoolsize"].to_i
    @maxsize = props["maxpoolsize"].to_i
    @initialsize = props["initialpoolsize"].to_i
    @factoryclassname = props["connectionfactory"]
    @onsconfig = props["onsconfig"]
    
    #create pool for use here
    @pds = PoolDataSourceFactory.getPoolDataSource
    @pds.set_user user
    @pds.set_password passwd
    @pds.set_url url
    @pds.set_connection_factory_class_name factoryclassname
    @pds.set_connection_pool_name "ruby-fcfucppool"
    @pds.set_initial_pool_size initialsize
    @pds.set_min_pool_size minsize
    @pds.set_max_pool_size maxsize
    @pds.setONSConfiguration(onsconfig)
    @pds.set_fast_connection_failover_enabled true
    
  end

  #add getters and setters for all attrributes
  attr_reader :user, :passwd, :url, :minsize, :maxsize, :initialsize, :factoryclassname, :onsconfig
  
  @@instance = MyOracleUcpPool.new
  @pds = nil
  
  def self.instance()
    return @@instance
  end
  
  def get_connection()
    return @pds.get_connection
  end
  
  def return_connection(conn)
    conn.close
  end

  def to_s
    "MyOracleUcpPool [user=#{@user}, passwd=#{@passwd}, " +
    "url=#{@url}, minsize=#{@minsize}, maxsize=#{@maxsize}, " +
    "initialsize=#{@initialsize}], factoryclassname=#{factoryclassname}"
  end
  alias_method :to_string, :to_s
    
  def display_pool_details()
    return "\n** FCF Enabled UCP Pool Details **\n" + 
            "NumberOfAvailableConnections: #{@pds.getAvailableConnectionsCount()}\n" +
            "BorrowedConnectionsCount: #{@pds.getBorrowedConnectionsCount()}\n";
  end
  
  private_class_method :new

 end    

3. In the same "lib" directory create a properties file called "ucp.properties" with content as follows. Ensure you set the correct details for your 11g RAC Cluster.


user=scott
password=tiger
url=jdbc:oracle:thin:@apctcsol1.au.oracle.com:1521/pas_srv
connectionfactory=oracle.jdbc.pool.OracleDataSource
initialpoolsize=5
minpoolsize=5
maxpoolsize=20
onsconfig=nodes=auw2k3.au.oracle.com:6200,auw2k4.au.oracle.com:6200

4. Edit the 3 lines below in the file "lib/ucppool-singleton.rb" to indicate the PATH to the 2 JAR files downloaded at step #1. For ons.jar you would obtain that from your CRS_HOME or RAC node at "$ORACLE_HOME/opmn/lib/ons.jar".

require 'C:/jdev/jdcbdrivers/11.2/11202/ojdbc6.jar'
require 'C:/jdev/jdcbdrivers/11.2/11202/ons.jar'
require 'C:/jdev/jdcbdrivers/11.2/ucp/ucp.jar'

5. Create a JRuby script called "ucp_fcf_test.rb" with content as follows.
require 'lib/ucppool-singleton'

INSTANCE_SQL = <<EOF  
select sys_context('userenv', 'instance_name'),  
sys_context('userenv', 'server_host'),   
sys_context('userenv', 'service_name')  
from dual  
EOF

def get_instance_details (conn, index)
  stmt = nil
  rset = nil
  
  begin
    stmt = conn.create_statement  
    rset = stmt.execute_query INSTANCE_SQL  
    rset.next  
    result = "\n--> Connection #{index} : instance [#{rset.get_string 1}], " +   
         "host[#{rset.get_string 2}], service[#{rset.get_string 3}]"  
    
    rset.close
    stmt.close
    
    return result
  rescue
    if (!rset.nil?)
      rset.close
    end
    if (!stmt.nil?)
      stmt.close
    end
    raise
  end
end

print "Run at ", Time.now , "\n"

conn = nil
ucppool = nil
i = 0

begin

  #use as a singleton class enusuring only one instance can exist
  ucppool = MyOracleUcpPool.instance()
  print ucppool , "\n"
  
  while (true)
    #get 5 connections from pool and insert into ruby hash
    conn = []
    for y in 0..4
      conn[y] = ucppool.get_connection
    end
    
    #  print instance details for each connection
    x = 0
    conn.each {|connection| print get_instance_details connection, x += 1}
    
    #print pool details
    puts
    print ucppool.display_pool_details

    #return connections
    conn.each {|connection| ucppool.return_connection connection}
    
    # sleep for 20 seconds
    puts "\nSleeping for 20 seconds....\n"
    sleep 20
  end
  
rescue 
  print "\n** Error occured **\n"
 print "Failed executing FCF UCP Pool demo from JRuby ", $!, "\n"
  
end

print "\nEnded at ", Time.now , "\n"
6. Connect to one of your RAC node instances in preparation to perform a ungraceful instance crash.
[oradb1@auw2k3 ~]$ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.2.0 Production on Thu Feb 3 21:27:13 2011

Copyright (c) 1982, 2010, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
Data Mining and Real Application Testing options

SQL>

7.  Run the JRuby script "ucp_fcf_test.rb" as shown below.

This script will create a UCP Pool setup for use with FCF,  obtain 5 connections and then sleep for 20 seconds and continue the process of obtaining another 5 connections and so on until the program is ended using CNTRL-C.

> jruby ucp_fcf_test.rb
Run at Thu Feb 03 21:30:58 +1100 2011
MyOracleUcpPool [user=scott, passwd=tiger, url=jdbc:oracle:thin:@apctcsol1.au.oracle.com:1521/pas_srv, minsize=5, maxsize=20, initialsize=5]
, factoryclassname=oracle.jdbc.pool.OracleDataSource

--> Connection 1 : instance [A11], host[auw2k3], service[pas_srv]
--> Connection 2 : instance [A11], host[auw2k3], service[pas_srv]
--> Connection 3 : instance [A12], host[auw2k4], service[pas_srv]
--> Connection 4 : instance [A12], host[auw2k4], service[pas_srv]
--> Connection 5 : instance [A11], host[auw2k3], service[pas_srv]

** FCF Enabled UCP Pool Details **
NumberOfAvailableConnections: 0
BorrowedConnectionsCount: 5

Sleeping for 20 seconds....

8. Now once the program output shows it has obtained 5 connections and is currently sleeping return to your SQL*Plus session at step #6 and perform an ungraceful shutdown using "shutdown abort" as shown below.
SQL> shutdown abort;
ORACLE instance shut down. 

9. Return to the JRuby script and wait for it to wake up and verify that the node which has crashed is no longer in the list of connected instances.

Run at Thu Feb 03 21:30:58 +1100 2011
MyOracleUcpPool [user=scott, passwd=tiger, url=jdbc:oracle:thin:@apctcsol1.au.oracle.com:1521/pas_srv, minsize=5, maxsize=20, initialsize=5]
, factoryclassname=oracle.jdbc.pool.OracleDataSource

--> Connection 1 : instance [A11], host[auw2k3], service[pas_srv]
--> Connection 2 : instance [A11], host[auw2k3], service[pas_srv]
--> Connection 3 : instance [A12], host[auw2k4], service[pas_srv]
--> Connection 4 : instance [A12], host[auw2k4], service[pas_srv]
--> Connection 5 : instance [A11], host[auw2k3], service[pas_srv]

** FCF Enabled UCP Pool Details **
NumberOfAvailableConnections: 0
BorrowedConnectionsCount: 5

Sleeping for 20 seconds....

*** RAC instance on auw2k3 shutdown at this point **

--> Connection 1 : instance [A12], host[auw2k4], service[pas_srv]
--> Connection 2 : instance [A12], host[auw2k4], service[pas_srv]
--> Connection 3 : instance [A12], host[auw2k4], service[pas_srv]
--> Connection 4 : instance [A12], host[auw2k4], service[pas_srv]
--> Connection 5 : instance [A12], host[auw2k4], service[pas_srv]

** FCF Enabled UCP Pool Details **
NumberOfAvailableConnections: 0
BorrowedConnectionsCount: 5

Sleeping for 20 seconds....

10. Return to your SQL*Plus session at step #6 and start the instance back up using "startup".
SQL> startup;
ORACLE instance started.

Total System Global Area  790941696 bytes
Fixed Size                  1347084 bytes
Variable Size             587203060 bytes
Database Buffers          197132288 bytes
Redo Buffers                5259264 bytes
Database mounted.
Database opened. 
11. Verify from the running JRuby script that connections from the recently returned instance are coming up in the list as shown below.

.....


Sleeping for 20 seconds....

*** RAC instance on auw2k3 started at this point **

--> Connection 1 : instance [A12], host[auw2k4], service[pas_srv]
--> Connection 2 : instance [A11], host[auw2k3], service[pas_srv]
--> Connection 3 : instance [A11], host[auw2k3], service[pas_srv]
--> Connection 4 : instance [A11], host[auw2k3], service[pas_srv]
--> Connection 5 : instance [A12], host[auw2k4], service[pas_srv]

** FCF Enabled UCP Pool Details **
NumberOfAvailableConnections: 5
BorrowedConnectionsCount: 5

Sleeping for 20 seconds....

For more information on using SCAN with 11g R2 RAC see the white paper below.

http://www.oracle.com/technetwork/database/clustering/overview/scan-129069.pdf

Monday, 31 January 2011

JRuby Oracle RAC 11g R2 SCAN Client Demo

Previously I created a JDBC client against an 11g R2 RAC client using SCAN as shown here. That example simply ensures we are load balancing between the RAC nodes in the cluster because from the JDBC URL we would not even know we are connecting to a RAC cluster.

jdbc:oracle:thin:@apctcsol1.au.oracle.com:1521/pas_srv

In the example below we use some JRuby code to do the exact same thing. We are using the 11.2.0.2 Oracle JDBC Driver and an 11.2.0.2 RAC cluster as well.

JRuby Code
require 'java'  
require 'C:/jdev/jdcbdrivers/11.2/11202/ojdbc6.jar'  
  
java_import java.sql.Statement
java_import java.sql.Connection
java_import java.sql.SQLException
java_import java.sql.DatabaseMetaData

java_import 'oracle.jdbc.OracleDriver'
java_import 'oracle.jdbc.pool.OracleDataSource'

INSTANCE_SQL = <<EOF
select sys_context('userenv', 'instance_name'),
sys_context('userenv', 'server_host'), 
sys_context('userenv', 'service_name')
from dual
EOF

class MyOracleDataSource   
  def initialize(user, passwd, url)  
    @user, @passwd, @url = user, passwd, url
      
    @ods = OracleDataSource.new
    @ods.set_user user
    @ods.set_password passwd
    @ods.set_url url
  end  
   
  # add getters and setters for all attrributes we wish to expose  
  attr_reader :user, :passwd, :url

  def get_connection()
    @ods.get_connection
  end
  
  def create_statement()
    @connection.create_statement
  end
  
  def to_s  
    "OracleDataSource  [user=#{@user}, passwd=#{@passwd}, " +  
    "url=#{@url}]"  
  end  

  def self.create(user, passwd, url)
    ods = new(user, passwd, url)
  rescue
    puts "\n** Error occured **\n"  
    puts "Failed executing SCAN Load Blance test from JRuby ", $!, "\n"
  end
end


user = "scott"
passwd = "tiger"
url = "jdbc:oracle:thin:@apctcsol1.au.oracle.com:1521/pas_srv"

print "Run at #{Time.now} using JRuby #{RUBY_VERSION}\n\n"  

mods = MyOracleDataSource.create(user, passwd, url)

# empty array
conns = []

# obtain 5 connections
for i in 1..5 
  conns[i] = mods.get_connection
end

# determine instance details
for i in 1..5
  if (i == 1)
    meta = conns[i].get_meta_data
    puts "=============\nDatabase Product Name is ... #{meta.getDatabaseProductName()}"  
    puts "Database Product Version is  #{meta.getDatabaseProductVersion()}"  
    puts "=============\nJDBC Driver Name is ........ #{meta.getDriverName()}" 
    puts "JDBC Driver Version is ..... #{meta.getDriverVersion()}"
    puts "JDBC Driver Major Version is #{meta.getDriverMajorVersion()}"  
    puts "JDBC Driver Minor Version is #{meta.getDriverMinorVersion()}" 
    puts "============="    
  end
  
  stmt = conns[i].create_statement
  rset = stmt.execute_query INSTANCE_SQL
  rset.next
  puts "Connection #{i} : instance [#{rset.get_string 1}], " + 
       "host[#{rset.get_string 2}], service[#{rset.get_string 3}] "
  
  rset.close
  stmt.close
end

#close the 5 connections
for i in 1..5
  conns[i].close
end

print "\nEnded at #{Time.now}"

Output

C:\jdev\scripting\demos\jruby\jdbc\scan-load-balance-test>jruby scan-lbt.rb
Run at Mon Jan 31 14:28:11 +1100 2011 using JRuby 1.8.7


=============
Database Product Name is ... Oracle
Database Product Version is  Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
Data Mining and Real Application Testing options
=============
JDBC Driver Name is ........ Oracle JDBC driver
JDBC Driver Version is ..... 11.2.0.2.0
JDBC Driver Major Version is 11
JDBC Driver Minor Version is 2
=============
Connection 1 : instance [A12], host[auw2k4], service[pas_srv]
Connection 2 : instance [A11], host[auw2k3], service[pas_srv]
Connection 3 : instance [A12], host[auw2k4], service[pas_srv]
Connection 4 : instance [A11], host[auw2k3], service[pas_srv]
Connection 5 : instance [A12], host[auw2k4], service[pas_srv]


Ended at Mon Jan 31 14:28:12 +1100 2011

Thursday, 13 January 2011

Retrieving DBMS_OUTPUT from PLSQL in a JRuby script

This demo shows how to get DBMS OUTPUT form PLSQL blocks and PLSQL program units using JRuby. In this example we obtain a JDBC connection which we then use to invoke a PLSQL block and get the DBMS OUTPUT back to the JRuby script.

1. Download ojdbc6.jar from the links below.

ojdbc6.jar (11.2.0.2)

2. Create a JRuby script for the JDBC connection named "jdbc_connection.rb" as follows
require 'java'
require 'C:/jdev/jdcbdrivers/11.2/ojdbc6.jar'

import 'oracle.jdbc.OracleDriver'
import 'java.sql.DriverManager'

class OracleConnection 

  @conn = nil
  
  def initialize (user, passwd, url)
    @user = user
    @passwd = passwd
    @url = url
    
    # load driver class
    oradriver = OracleDriver.new
    
    DriverManager.registerDriver(oradriver)
    @conn = DriverManager.getConnection(url,user,passwd);
    @conn.setAutoCommit(false);
    
  end
 
  #add getters and setters for all attrributes we wish to expose
  attr_reader :user, :passwd, :url
 
  def getConnection()
    return @conn
  end

  def closeConnection()
    @conn.close()
  end

  def to_s
    "OracleConnection [user=#{@user}, passwd=#{@passwd}, " +
    "url=#{@url}]"
  end
  alias_method :to_string, :to_s
  
end


- Edit the line below to indicate the PATH to the Oracle JDBC driver downloaded at step #1

require 'C:/jdev/jdcbdrivers/11.2/ojdbc6.jar'


3. Create a JRuby script for the DBMS OUTPUT class named "dbms_output.rb" as follows.
require 'java'

require 'C:/jdev/jdcbdrivers/11.2/ojdbc6.jar'

import 'java.sql.CallableStatement'
import 'java.sql.Connection'
import 'java.sql.SQLException'
import 'java.sql.Types'

class DbmsOutput

  def initialize (conn)
    @enable_stmt  = conn.getConnection.prepareCall( "begin dbms_output.enable(:1); end;" );
    @disable_stmt = conn.getConnection.prepareCall( "begin dbms_output.disable; end;" );
    
    @show_stmt = conn.getConnection.prepareCall( 
          "declare " +
          "    l_line varchar2(255); " +
          "    l_done number; " +
          "    l_buffer long; " +
          "begin " +
          "  loop " +
          "    exit when length(l_buffer)+255 > :maxbytes OR l_done = 1; " +
          "    dbms_output.get_line( l_line, l_done ); " +
          "    l_buffer := l_buffer || l_line || chr(10); " +
          "  end loop; " +
          " :done := l_done; " +
          " :buffer := l_buffer; " +
          "end;" );
  end
  
  def enable (size)
    @enable_stmt.setInt( 1, size );
    @enable_stmt.executeUpdate();
  end
  
  def disable
    @disable_stmt.executeUpdate();
  end
  
  def show
      output = ""
      done = 0;
  
      @show_stmt.registerOutParameter( 2, 4);
      @show_stmt.registerOutParameter( 3, 12 );
  
      while (done == 0)   
          @show_stmt.setInt( 1, 32000 );
          @show_stmt.executeUpdate();
          output = output , "" , @show_stmt.getString(3), "\n"
          if ( (done = @show_stmt.getInt(2)).to_i == 1 ) 
            break
          end
      end
      
      return output
  end
  
  def closeAll
    @enable_stmt.close();
    @disable_stmt.close();
    @show_stmt.close();
  end
  
end 

- Edit the line below to indicate the PATH to the Oracle JDBC driver downloaded at step #1

require 'C:/jdev/jdcbdrivers/11.2/ojdbc6.jar'


4. Create a JRuby test script named "test_dbms_output.rb" as follows
# test DBMS_OUTPUT from JRuby
#

require 'lib/jdbc_connection'
require 'lib/dbms_output'

print "Run at ", Time.now , " using JRuby ", RUBY_VERSION, "\n"
puts 

conn = nil

begin

  conn = OracleConnection.new("scott", "tiger", "jdbc:oracle:thin:@beast.au.oracle.com:1524/linux11gr2")
  puts conn
  dbms_output = DbmsOutput.new(conn)
  dbms_output.enable( 1000000 );
  
  plsql_block = 
    "begin " + 
    " for i in 1..10 loop " +
    "  dbms_output.put_line('Hello JRuby at position '||i); " + 
    " end loop; " +
    "end;"
 
  stmt = conn.getConnection.createStatement();
  stmt.execute(plsql_block);   
  
  print "** Output from PLSQL Block as follows **"
  puts dbms_output.show()
  dbms_output.closeAll()
  
rescue 
  print "\n** Error occured **\n"
 print "Failed executing Oracle JDBC DBMS_OUTPUT demo from JRuby ", $!, "\n"
  if (!conn.nil?)
    conn.closeConnection()
  end
  
end

print "\nEnded at ", Time.now , "\n"

- Edit the 2 lines above to refer to the files created at step #2 and step #3. In this example they exist of a lib directory from the current directory.

require 'lib/jdbc_connection'
require 'lib/dbms_output'

Note: Ensure you specify a connection to your database as follows

conn = OracleConnection.new("scott", "tiger", "jdbc:oracle:thin:@beast.au.oracle.com:1524/linux11gr2")

5. Run test_dbms_output.rb

Run at Thu Jan 13 07:45:21 +1100 2011 using JRuby 1.8.7

OracleConnection [user=scott, passwd=tiger, url=jdbc:oracle:thin:@beast.au.oracle.com:1524/linux11gr2]
** Output from PLSQL Block as follows **


Hello JRuby at position 1
Hello JRuby at position 2
Hello JRuby at position 3
Hello JRuby at position 4
Hello JRuby at position 5
Hello JRuby at position 6
Hello JRuby at position 7
Hello JRuby at position 8
Hello JRuby at position 9
Hello JRuby at position 10


Ended at Thu Jan 13 07:45:21 +1100 2011

Friday, 7 January 2011

JRuby example using Oracle UCP (Universal Connection Pool)

The Oracle Universal Connection Pool (UCP) for JDBC is a full-featured connection pool for managing database connections not only for Oracle but also for other non Oracle databases. The advantage with using UCP with Oracle is that UCP JDBC connection pools provide a tight integration with various Oracle Real Application Clusters (RAC) Database features . The features include Fast Connection Failover (FCF), Run-Time Connection Load Balancing, and Connection Affinity.

In this example below we show how to use UCP with an Oracle Database from a JRuby client BUT just a single instance database rather then RAC back end.

Note: We are using the HR schema for this demo

1. Download ucp.jar and ojdbc6.jar from the links below.

ojdbc6.jar (11.2.0.2)
ucp.jar (11.2.0.1)

2. Create a pool class as follows in a JRuby script called "ucppool.rb" in a directory called "lib". Client would then create an instance of this pool class and use it to retrieve / return connections from it.

require 'java'
require 'C:/jdev/jdcbdrivers/11.2/ojdbc6.jar'
require 'C:/jdev/jdcbdrivers/11.2/ucp/ucp.jar'

import 'oracle.ucp.jdbc.PoolDataSource'
import 'oracle.ucp.jdbc.PoolDataSourceFactory'

API_VERSION = 1.0

class MyOracleUcpPool

  #pool data source object
  @pds
  
  def initialize(user, passwd, url, minsize=0, maxsize=10, initialsize=2)
    @user = user
    @passwd = passwd
    @url = url
    @minsize = minsize
    @maxsize = maxsize
    @initialsize = initialsize
    
    #create pool for use here
    @pds = PoolDataSourceFactory.getPoolDataSource()
    @pds.setUser(user)
    @pds.setPassword(passwd)
    @pds.setURL(url)
    @pds.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource")
    @pds.setConnectionPoolName("ruby-ucppool")
    @pds.setInitialPoolSize(initialsize)
    @pds.setMinPoolSize(minsize)
    @pds.setMaxPoolSize(maxsize)
    
  end
  
  #add getters and setters for all attrributes
  attr_reader :user, :passwd, :url, :minsize, :maxsize, :initialsize
  
  def getConnection()
    return @pds.getConnection()
  end
  
  def returnConnection(conn)
    conn.close()
  end
  
  def displayPoolDetails()
    return "\n** UCP Pool Details **\n" + 
            "NumberOfAvailableConnections: ", @pds.getAvailableConnectionsCount(), "\n" +
            "BorrowedConnectionsCount: ", @pds.getBorrowedConnectionsCount(), " \n";
  end
  
  def to_s
    "MyOracleUcpPool [user=#{@user}, passwd=#{@passwd}, " +
    "url=#{@url}, minsize=#{@minsize}, maxsize=#{@maxsize}, " +
    "initialsize=#{@initialsize}]"
  end
  alias_method :to_string, :to_s
  
 end

- Edit the 2 lines below to indicate the PATH to the 2 JAR files downloaded at step #1


require 'C:/jdev/jdcbdrivers/11.2/ojdbc6.jar'
require 'C:/jdev/jdcbdrivers/11.2/ucp/ucp.jar'


3. In your current directory create a test client to verify the UCP called "testucp.rb" as follows to test your UCP Pool.

require 'lib/ucppool'

print "Run at ", Time.now , "\n"

conn = nil
ucppool = nil

begin

  ucppool = MyOracleUcpPool.new("hr", "hr", "jdbc:oracle:thin:@beast.au.oracle.com:1524/linux11gr2", 0, 5, 2)
  print ucppool , "\n"

  #get connection from pool
  conn = ucppool.getConnection()

  #print pool details
  print ucppool.displayPoolDetails()
  puts

  #execute query
  stmt = conn.createStatement()
  rset = stmt.executeQuery("select * from departments")
  while rset.next()
    print "DepartmentId=", rset.getInt(1), 
          ", DepartmentName=" + rset.getString(2), "\n"
  end

  rset.close()
  stmt.close()

  #return connection
  ucppool.returnConnection(conn)
  print "\nConnection returned to pool\n"

  #print pool details
  print ucppool.displayPoolDetails()

rescue 
  print "\n** Error occured **\n"
 print "Failed executing UCP Pool demo from JRuby ", $!, "\n"
  if (!conn.nil?)
    if (!ucppool.nil?)
      ucppool.returnConnection(conn)  
      print "\nConnection returned to pool\n"
    end
  end
  
end

print "\nEnded at ", Time.now , "\n"

4. Your file system would look as follows
C:\jdev\scripting\demos\jruby\jdbc\ucp>dir
 Volume in drive C is OS
 Volume Serial Number is 7C37-0C64

 Directory of C:\jdev\scripting\demos\jruby\jdbc\ucp

06/01/2011  10:21 PM    <DIR>          .
06/01/2011  10:21 PM    <DIR>          ..
06/01/2011  10:30 PM    <DIR>          lib
07/01/2011  08:47 AM             1,112 testucp.rb
               1 File(s)          1,112 bytes
               3 Dir(s)  248,428,380,160 bytes free

5. Edit the following line of code to ensure you provide the correct connect details for your database.

ucppool = MyOracleUcpPool.new("hr", "hr", "jdbc:oracle:thin:@beast.au.oracle.com:1524/linux11gr2", 0, 5, 2)

6. Run the test client using jruby testucp.rb. In this example we do the following.

  • create a UCP Pool
  • obtain a JDBC Connection from the Pool
  • Query a table
  • Return the JDBC connection to the pool


OUTPUT

Run at Fri Jan 07 09:25:16 +1100 2011
MyOracleUcpPool [user=hr, passwd=hr, url=jdbc:oracle:thin:@beast.au.oracle.com:1524/linux11gr2, minsize=0, maxsize=5, initialsize=2]


** UCP Pool Details **
NumberOfAvailableConnections: 1
BorrowedConnectionsCount: 1


DepartmentId=10, DepartmentName=Administration
DepartmentId=20, DepartmentName=Marketing
DepartmentId=30, DepartmentName=Purchasing
DepartmentId=40, DepartmentName=Human Resources
DepartmentId=50, DepartmentName=Shipping
DepartmentId=60, DepartmentName=IT
DepartmentId=70, DepartmentName=Public Relations
DepartmentId=80, DepartmentName=Sales
DepartmentId=90, DepartmentName=Executive
DepartmentId=100, DepartmentName=Finance
DepartmentId=110, DepartmentName=Accounting
DepartmentId=120, DepartmentName=Treasury
DepartmentId=130, DepartmentName=Corporate Tax
DepartmentId=140, DepartmentName=Control And Credit
DepartmentId=150, DepartmentName=Shareholder Services
DepartmentId=160, DepartmentName=Benefits
DepartmentId=170, DepartmentName=Manufacturing
DepartmentId=180, DepartmentName=Construction
DepartmentId=190, DepartmentName=Contracting
DepartmentId=200, DepartmentName=Operations
DepartmentId=210, DepartmentName=IT Support
DepartmentId=220, DepartmentName=NOC
DepartmentId=230, DepartmentName=IT Helpdesk
DepartmentId=240, DepartmentName=Government Sales
DepartmentId=250, DepartmentName=Retail Sales
DepartmentId=260, DepartmentName=Recruiting
DepartmentId=270, DepartmentName=Payroll


Connection returned to pool


** UCP Pool Details **
NumberOfAvailableConnections: 2
BorrowedConnectionsCount: 0


Ended at Fri Jan 07 09:25:16 +1100 2011


More Information

Oracle Universal Connection Pool for JDBC Developer's Guide
11g Release 2 (11.2)
http://download.oracle.com/docs/cd/E11882_01/java.112/e12265/toc.htm

Tuesday, 20 July 2010

How to Set v$session.program From a Universal Connection Pool (UCP)

The follow shows how you can ensure connections created from your Oracle Universal Connection Pool (UCP) clients can be uniquely identified using the Oracle JDBC driver property v$session.program. The property is an Oracle JDBC driver property so what we do here is the following.

1. Set the factory class to "oracle.jdbc.OracleDriver" using the method PoolDataSource.setConnectionFactoryClassName()
2. Use the PoolDataSource.setConnectionFactoryProperties() method to specify the driver properties that each Connection will use.

So here is a basic class showing how to set v$session.program and verify it did this correctly from SQL*Plus.


TestUCPJDBCProps.java

package demo;

import java.io.IOException;

import java.sql.Connection;
import java.sql.SQLException;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import oracle.ucp.UniversalConnectionPoolAdapter;
import oracle.ucp.UniversalConnectionPoolException;
import oracle.ucp.admin.UniversalConnectionPoolManager;
import oracle.ucp.admin.UniversalConnectionPoolManagerImpl;
import oracle.ucp.jdbc.PoolDataSource;
import oracle.ucp.jdbc.PoolDataSourceFactory;


public class TestUCPJDBCProps
{
  private PoolDataSource pds = null;
  private Properties props = new Properties();
  private UniversalConnectionPoolManager mgr = null;
  private String poolName = "PasUCPTest";
  
  public TestUCPJDBCProps() throws SQLException, UniversalConnectionPoolException
  {  
    mgr = UniversalConnectionPoolManagerImpl.getUniversalConnectionPoolManager();
    
   // Create pool-enabled data source instance.
    pds = PoolDataSourceFactory.getPoolDataSource();
    // PoolDataSource and UCP configuration
    
    //set the connection properties on the data source and pool properties
    pds.setUser("scott");
    pds.setPassword("tiger");
    pds.setURL("jdbc:oracle:thin:@//beast.au.oracle.com:1523/linux11gr2");
    pds.setConnectionFactoryClassName("oracle.jdbc.OracleDriver");
    pds.setInitialPoolSize(2);
    pds.setMinPoolSize(2);
    pds.setMaxPoolSize(20);
    pds.setConnectionPoolName(poolName);
    props.put("v$session.program", "scott-ucp-j2seclient");
    pds.setConnectionFactoryProperties(props);
    
    mgr.createConnectionPool((UniversalConnectionPoolAdapter)pds);
    
    mgr.startConnectionPool(poolName);

  }

  public void run () throws SQLException, IOException
  {
    List connList = new ArrayList();
    
    for (int i = 0; i < 5 ;i++ ) 
    {
      //Get a database connection from the datasource. 
      Connection conn = pds.getConnection();
      System.out.println("Retrieved a connection from pool");
      connList.add(conn);
    }

    System.out.println("Press Enter to finish the demo -> ");
    System.in.read();
      
    // close all connections
    for (int j = 0; j < connList.size() ; j++) 
    {
      ((Connection)connList.get(j)).close();
    }
    
  }
  
  public void stopPool () throws UniversalConnectionPoolException
  {
    mgr.stopConnectionPool(poolName);  
  }
  
  public static void main(String[] args) throws IOException
  {
    System.out.println("Started UCP JDBC Property Test at " + new Date());
    TestUCPJDBCProps test;

    try
    {
      test = new TestUCPJDBCProps();
      test.run();
      test.stopPool();
    }
    catch (Exception e)
    {
      e.printStackTrace();
      System.exit(-1);
    }
    
    System.out.println("Ended UCP JDBC Property Test at " + new Date());
  }
} 

SQL*PLus Output

SCOTT@linux11gr2> @query-scott.sql

SCOTT sessions

USERNAME PROGRAM                   STATUS
-------- ------------------------- --------
SCOTT    sqlplus.exe               ACTIVE
SCOTT    scott-ucp-j2seclient      INACTIVE
SCOTT    scott-ucp-j2seclient      INACTIVE
SCOTT    scott-ucp-j2seclient      INACTIVE
SCOTT    scott-ucp-j2seclient      INACTIVE
SCOTT    scott-ucp-j2seclient      INACTIVE

6 rows selected.

SCOTT@linux11gr2>

The SQL for the query above was as follows.

set head on feedback on

set pages 999
set linesize 120

prompt
prompt SCOTT sessions

col machine format a25
col username format a15
col username format a8
col program format a25

select
username,
program,
status,
last_call_et seconds_since_active,
to_char(logon_time, 'dd-MON-yyyy HH24:MI:SS') "Logon"
from v$session
where username = 'SCOTT'
/