PreparedStatement.Close()

I'm using the same PreparedStatement object for many querys on a method, I think this is ok, isn't it? So... Do I need to call the PreparedStatement.close() method between every query? Can I call the close method many times without calling the executeQuery() method?
Thanks
Eduardo Castor

Do not close the PreparedStatement until your program ends (or until you do not need it any more). You can use it repeatedly without closing it.

Similar Messages

  • PreparedStatement.close() hangs, blocking finalization

    We encountered an incident on a production system with a class that would call PreparedStatement.close() on finalize(), and there was an instance where the jvm finalizer thread stalled on this the PreparedStatement.close() call, blocking garbage collection.
    The last sql statement run with the preparedstatement was most probably a select statement (we cannot determine for sure), and the OCI driver was used.
    While I realize it's not recommended to close PreparedStatements on finalize(), can I ask for some possible reasons why the close() call would stall? Would it be a database issue or a java issue?

    Can you do the close() in a PhantomReference? That might be a good alternative to using finalize(). These refs are rather obscure and most Java authors parrot the usual line about post-mortem cleanup, but if you dig deep enough you can find a few examples of its use (I think that there is Apache group source with an example).
    If you are running in a servlet, move the close() to the servlet destroy() method.
    The best solution is to use 10.2 implicit connection caching and close all your Connections immediatly after use in a finally block. Then close your DataSource in the destroy().

  • Should PreparedStatement close before continue next PreparedStatement ?

    Hi guys,
    For instance, I need to use PreparedStatement for several insert and update like below:
    Connection conn; // got the connection
    PreparedStatement pstmt = conn.prepareStatement("insert ......");
    pstmt.addBatch();
    pstmt.executeBatch();
    *// should I do a pstmt.close() here ?????????*
    pstmt = conn.prepareStatement("update......");
    pstmt.addBatch();
    pstmt.executeBatch();
    Thanks & Regards,
    Mark

    kmthien wrote:
    Yes, I am using apache DBCP and using the example code here :
    http://www.freshblurbs.com/jakarta-commons-dbcp-tutorial#comment-544
    However, In my class, I need to connect to 2 database, 1 is local and another 1 is remote.Location doesn't matter.
    I don't know how to create and initialize 2 connection pooling as when I initialize 2 connection pooling, it jus treated it as 1 only.This is of course completely different from your first question. Did you google?

  • Servlet crashes on preparedStatement.close()

    Hello Everyone ,
    I have a servlet that gives out database information. Depending on the request parameters , some prepared statements that I declare before my try block may or may not be used. All statements and resultSets are initialized to null. If I determine the request is bad my servlet goes to an else block, then the finally block to close statements and stuff. Unfortunately, when it hits a preparedStatement that wasn't used, it outputs a HTTP Status 500 java.lang.NullPointer exception. I have never had this happen before ?
    P.S I output my xml before the try block, so how come I see the error and not my xml, or a combination of both ?

    As mentioned earlier by others, in your servlet code somewhere you are doing some operation on an object which is null. From server error log see the stack trace. Locate the exact place of NullPointerException and fix it.
    I hope you know where log files are generated in server. If you need help fixing the root cause of NullPointerException please post your code snippet here.
    Thanks,
    Mrityunjoy

  • 9.2.0 Thin driver; PreparedStatement.close() gives NullPointerException when close()d

    Here's the error stack:
    --- Nested Exception ---
    java.lang.NullPointerException
    at oracle.jdbc.dbaccess.DBData.clearItem(DBData.java:431)
    at oracle.jdbc.dbaccess.DBDataSetImpl.clearItem(DBDataSetImpl.java:3528)
    at oracle.jdbc.driver.OraclePreparedStatement.clearParameters(OraclePreparedSta
    at com.secretseal.util.sql.PooledPreparedStatement.close(PooledPreparedStatemen
    at com.secretseal.util.sql.LoggableStatement.close(LoggableStatement.java:112)
    Has anybody has this issue? Thank you in advance.

    workaround: use Oracle proprietary batching, setExecuteBatch(). My webapp is facing the exact problem. But I used the Oracle 8i drivers and it worked. Meanwhile, will you please tell me what is the AppServer you are using? Cause this happens in Websphere 4.0.x environment but not in 3.5.x and weblogic.
    Thanks,

  • When to use PreparedStatement.close()

    Hi,
    For a long time I was/am convinced that it is good to use prepared statement eventhough you are not going to use them propertly, cause whenever in the future you are going to modify your code to use your connections wisely along with prepared statements it will save you valuble execution time.
    I have following enviornment....
    Miscrosoft SQL Server 2000 driver for JDBC
    Jakarta-Commons DBCP (have prepared stmt pooling on)
    Tomcat as the web app.
    (I would not like to use Tomcat's internal CPooling cause we may have to migrate to some other app server and then the installation process and everything should have been changed.)
    Now to the actuall question.... in a transacation I have 2 to 3 different sets of queries (some SELECTs, some UPDATEs and some INSERTs)
    say I have QUERY1 , a SELECT query and QUERY2 an UPDATE query in a transaction T1. Will following code utilize features of PreaparedStatement properly??
    String q1 = QUERY1;
    String q2 = QUERY2;
    PreparedStmt pStmt = null;
    pStmt = conn.prepareStatement(q1);
    rs = pStmt.executeQuery();
    Object obj1 = processRS (rs);
    pStmt = conn.prepareStatement(q2);
    myint = pStmt.executeUpdate();
    pStmt.close();Do I need to have "pStmt.close()" btw "Object obj1 = processRS (rs);" and "pStmt = conn.prepareStatement(q2);"?
    Thanks a lot.

    >>
    Do I need to have "pStmt.close()" btw "Object obj1 =
    processRS (rs);" and "pStmt =
    conn.prepareStatement(q2);"?Yes.
    And you need to close the ResultSets as well.
    And you need proper exception handling to handling
    closing all of them if an exception occurs.
    Won't "pStmt.close()" will also close the result set if any?
    And yes I am aware that I need to take care of closing it properly in case of any exception.
    Thanks a lot for your response.

  • Problem in preparedstatements

    hi all,i am using preparedstatements in my program.i use so many of them.i have so many functions and in each function i declare preparedstatements though the preparedstatements are common.but when i use these preparedstatements in the valuechanged() method of JList and actionperformed() method of JButton they work fine for 5 to 6 event changes after which they throw a SQL exception ORA 01000 saying
    "maximum open cursors exceeded".
    is this exception got anything to do with the number of preparedstatements.why does this exception occur and how to rectify it.thanks in advance.bye thiyagu.

    As the error message says you have reached the limit of your available cursors. You can increase the number of cursors by modifying the initialization parameter OPEN_CURSORS in INITSID.ORA. After this you have to restart the database. The cursors that are counted for this are those explicit cursors that you opened and never closed, you have to use preparedStatement.close() in order to close the cursors.

  • Connections not being released from jdbc pool on WLS 5.1 sp8

    I am using WLS 5.1 on RedHat Linux kernel 2.4
    The database is oracle 8.1.6 and I am using the thin jdbc driver as shown in the config below.
    weblogic.jdbc.connectionPool.bobePool=\
    url=jdbc:oracle:thin:@localhost:1521:<sid>,\
    driver=oracle.jdbc.driver.OracleDriver,\
    loginDelaySecs=1,\
    initialCapacity=10,\
    maxCapacity=22,\
    capacityIncrement=5,\
    allowShrinking=true,\
    shrinkPeriodMins=3,\
    testConnsOnReserve=true,\
    testTable=dual,\
    refreshTestMinutes=5,\
    props=user=<username>;password=<password>
    The problem I am facing is that some connections remain active
    after the SQL query has finished. The no. of open connections
    keep on piling up till the limit of 18 connections is reached and
    ultimately at that point weblogic hangs.
    Has someone else faced this problem...and found a solution??
    Regards,
    Anish Srivastava
    System Analyst
    Baazee.com

    Hi Caren,
    Weblogic doesn't close connections on "time-out". There are some reasons
    for this. The most important one is that even if you have such a
    functionality,
    in case of a connection leak all the available connections can be trashed in
    a matter of milliseconds, so it wouldn't help at all. Though, weblogic does
    close leaked connection when they are garbage collected, but it's easy to
    see
    that it doesn't help a lot, too.
    So you need to make sure that all the JDBC objects are closed properly,
    for example like in this code:
    try {
    } finally {
    try {resultSet.close();} catch (SQLException se) {}
    try {preparedStatement.close();} catch (SQLException se) {}
    try {connection.close();} catch (SQLException se) {}
    Also it's possible that you simply don't have enough connection.
    You could try to increase size of the pool.
    Regards,
    Slava Imeshev
    "Karen Law" <[email protected]> wrote in message
    news:[email protected]...
    Closing the DB connections is important. But is there any parameters to be
    set in the WebLogic configuration in order to release the connection whenit
    hasn't been closed for a long time? Say, setting the connection timeout?
    Many thx!
    Karen
    "Deyan D. Bektchiev" <[email protected]> wrote in message
    news:[email protected]...
    Do you close the DB connections in a finally block after you've finished
    using them?
    If not your application is leaking the connections and sometimes GC is
    not able or does not free those in a timely manner.
    --dejan
    Anish Srivastava wrote:
    I am using WLS 5.1 on RedHat Linux kernel 2.4
    The database is oracle 8.1.6 and I am using the thin jdbc driver as
    shown
    in the config below.
    weblogic.jdbc.connectionPool.bobePool=\
    url=jdbc:oracle:thin:@localhost:1521:<sid>,\
    driver=oracle.jdbc.driver.OracleDriver,\
    loginDelaySecs=1,\
    initialCapacity=10,\
    maxCapacity=22,\
    capacityIncrement=5,\
    allowShrinking=true,\
    shrinkPeriodMins=3,\
    testConnsOnReserve=true,\
    testTable=dual,\
    refreshTestMinutes=5,\
    props=user=<username>;password=<password>
    The problem I am facing is that some connections remain active
    after the SQL query has finished. The no. of open connections
    keep on piling up till the limit of 18 connections is reached and
    ultimately at that point weblogic hangs.
    Has someone else faced this problem...and found a solution??
    Regards,
    Anish Srivastava
    System Analyst
    Baazee.com

  • How to use "scope " attrubute in useBean tag

    Can anyone please tell me if I can use the same JavaBean Class to hold information form different pages? well, let me explain exactely what I want to do:
    I have a Java bean Class that holds a property 'Name':
    package ContactManager;
    public class Person {
    private String name="%";
    public String getName () {
    return this.name;
    public void setName (String my_name) {
    name = my_name + "%" ;
    I'm using this class to store temporarly the Criteria of search from a JSP/HTML page to send to a database for search and for UPDATE -> this of course is done in different HTML/JSP pages. The problem I have is that the first time I set the properties (when the user make a search) this value remains unchanged [-> the second time when the user asks for update, I try to use the same bean to keep the value => unfortuntly it returns me the old value]
    My question is: is the use of 'scope' attribute of the "jsp:useBean" tag can solve this problem? if yes how to use it? I've tryed to set the scope of the bean to page but that does not help :-(
    Pleaze help, I'm stuck.... Bellow is the 4 JSP pages for:
    - person_search.jsp / person_result.jsp
    - request_modify.jsp/ DoModify.jsp
    1 -person_search.jsp
    <%@ page import="java.sql.*" %>
    <HTML>
    <HEAD><TITLE>Person Search</TITLE></HEAD>
    <BODY><CENTER>
    <form method="POST" action="person_result.jsp">
    Name <input type="text" name="name" size="47"></p>
    <input type="submit" value="Submit" name="B1">
    <input type="reset" value="Reset" name="B2"></p>
    </form></body>
    </html>
    2- person_result.jsp
    <%@ page import="java.sql.*" %>
    <HTML><BODY>
    <jsp:useBean id="theBean" class="ContactManager.Person"/>
    <jsp:setProperty name="theBean" property="*" />
    Name<BR>
    <%
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("JDBC driver loaded");
    catch (ClassNotFoundException e) {
    System.out.println(e.toString());
    %>
    <%
    try {
    Connection con = DriverManager.getConnection("jdbc:odbc:ContactManager");
    Statement s = con.createStatement();
    String sql = "SELECT Client.ClientID, Client.Name FROM Client where Client.Name like " + "'" + theBean.getName() + "'";
    ResultSet rs = s.executeQuery(sql);
    while (rs.next()) {
    String myId = rs.getString(1);
    %>
    <TR>
    <TD><%= myId %></TD>
    <TD><a href="person_detail.jsp?id=<%= myId %>"><%=rs.getString(2)%></a></TD>
    <TD><a href="delete_person.jsp?id=<%= myId %>">Delete</a></TD><BR>
    </TR>
    <%
    rs.close();
    s.close();
    con.close();
    catch (SQLException e) {
    System.out.println(e.toString());
    catch (Exception e) {
    System.out.println(e.toString());
    %>
    </BODY>
    </HTML>
    3- request_modify.jsp
    <%@ page import="java.sql.*" %>
    <html>
    <head><title>AddressBook: Modifying Person <%= request.getParameter ("id") %></title> </head>
    <body bgcolor="#ffffee">
    <%
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("JDBC driver loaded");
    catch (ClassNotFoundException e) {
    System.out.println(e.toString());
    %>
    <%
    int rowsAffected = 0;
    try {
    Connection con = DriverManager.getConnection("jdbc:odbc:ContactManager");
    Statement s = con.createStatement();
    String sql = "SELECT Client.ClientID, Client.Name FROM Client where ClientID ="+ request.getParameter("id");
    ResultSet rs = s.executeQuery(sql);
    if (rs.next()) {
    %>
    Client Name is <input type=text name=name value=<%= rs.getString(2) %>> <br>
    <TD><a href="person_do_modify.jsp?id=<%= rs.getString(1)%>">Confirm Modify</a></TD>
    <%
    rs.close();
    s.close();
    con.close();
    catch (SQLException e) {
    System.out.println(e.toString());
    catch (Exception e) {
    System.out.println(e.toString());
    %>
    </BODY> </HTML>
    4- do_modify.jsp
    <%@ page import="java.sql.*" %>
    <html>
    <head><title>AddressBook: Modifying Address <%= request.getParameter ("id") %></title></head>
    <body bgcolor="#ffffee">
    <jsp:useBean id="theBean" class="ContactManager.Person" scope="page"/>
    <jsp:setProperty name="theBean" property="name"/>
    <%
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("JDBC driver loaded");
    catch (ClassNotFoundException e) {
    System.out.println(e.toString());
    %>
    <%
    int rowsAffected = 0;
    try {
    Connection con = DriverManager.getConnection("jdbc:odbc:ContactManager");
    PreparedStatement preparedStatement = con.prepareStatement ("UPDATE Client SET Name=? WHERE ClientID =?");
    preparedStatement.setString (1, theBean.getName());
    preparedStatement.setString (2, request.getParameter("id"));
    rowsAffected = preparedStatement.executeUpdate ();
    preparedStatement.close ();
    if (rowsAffected == 1) {
    %>
    done
    <%
    else{
    %>
    Not Modified
    <%
    con.close();
    catch (SQLException e) {
    System.out.println(e.toString());
    catch (Exception e) {
    %>
    </BODY></HTML>
    Thank you for the help.
    Sammy

    While a quick search on the <jsp:useBean> tag and the scope attribute will probably yield more information than I can summarize in a few sentences, I'm pretty sure that using the scope="page" attribute on a bean will cause that bean to be instantiated every time the page is loaded. In order for a bean to persist longer than the existance of that page (whether you're loading a new page, or reloading the same one), you'd need to set the scope to session or application (you'd probably want session).

  • How do get particular date of total time

    this is our java code
        private static PreparedStatement preparedStatement;
        private static ResultSet rs;
        public static void main(String[] args) throws NamingException, SQLException
            int objectId;
            int clientId;
             DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // String gpstime = null;
             PreparedStatement preparedStatement = null;
             Connection conn=null;
             long mill;
             long diffSeconds=0;
             long diffMinutes=0;
             try
              Class.forName("com.mysql.jdbc.Driver");
            Connection conn1=DriverManager.getConnection("jdbc:mysql://108.108.8.4:3306/navl?","root", "ajmani@%");
            preparedStatement = conn1.prepareStatement("select gpstime from xydata a inner join fm4features f on a.ID=f.ID where a.objectId= '18'  AND a.clientId = '1' AND a.gpstime > '2010-05-11 00:00:00'  AND a.gpstime < '2010-05-13 23:59:59' AND f.DataId='1' AND f.value = '1'");
            rs = preparedStatement.executeQuery();
            int a = 0;
            int b=0;
             int b1=0;
             int b2=0;
             int x=0;
             float secs = 0;
            Set<String> dates = new HashSet<String>();
            ArrayList<Integer> l=new ArrayList<Integer>();
              Timestamp t1 = null;
              Timestamp t2 = null;
              int count  = 0;
              while ( rs.next() )
                    String gpstime = rs.getString("GpsTime");
                 if (dates.add(gpstime) )
                     //System.out.println(rs.getTimestamp(1));
                     t2 =   rs.getTimestamp(1);
                     count++;
                   if (t1 == null )
                       int nano = t2.getSeconds();
                         System.out.println(nano);
                       System.out.println(nano);
                       System.out.println(t2);
                       System.out.println(count);
                  else
                        mill= (t1.getTime() - t2.getTime())/-1;
                        //System.out.println(mill);
                        diffSeconds = mill / 1000;
                        diffMinutes = mill / (60 * 1000);
                        long diffHours = mill / (60 * 60 * 1000);
                        long diffDays = mill / (24 * 60 * 60 * 1000);
                        //System.out.println("\nThe Date Different");
                        //System.out.println("Time in milliseconds: " + mill+ " milliseconds.");
                        System.out.println("GPSTime " +gpstime+ " Time in seconds: " + diffSeconds+ " seconds.");
                        //System.out.println("Time in minutes: " + diffMinutes+ " minutes.");
                        //System.out.println("Time in hours: " + diffHours+ " hours.");
                        //System.out.println("Time in days: " + diffDays+ " days.");
                  t1 = t2;
                //System.out.println("Time in minutes: " + diffSeconds+ " seconds.");
                if(diffSeconds < 80)
                  b=(int) diffSeconds;
                  System.out.println(b);
                  l.add(b);
                 else if(diffSeconds > 80)
                    b2=(int)diffSeconds%60;
                    System.out.println(b2);
                    l.add(b2);
                 a++;
              for (int i=0; i<l.size();)
                  secs+=l.get(i);
                  i++;
                 System.out.println(secs);
                 int hours = (int) (secs / 3600),
                 remainder = (int) (secs % 3600),
                 minutes = remainder / 60,
                 seconds = remainder % 60;
                    String disHour = (hours < 10 ? "0" : "") + hours,
                    disMinu = (minutes < 10 ? "0" : "") + minutes ,
                    disSec = (seconds < 10 ? "0" : "") + seconds ;
                    if (count < 2)
                        int se = Integer.parseInt(disSec);
                        String min = (t2.getSeconds() < 10 ? "0" : "") + t2.getSeconds();
                        System.out.println("00" + ":" +  "00" + ":" + min + " hh:mm:ss");
                    System.out.println(disHour +":"+ disMinu+":"+disSec+ " hh:mm:ss");
             }catch(Throwable th)
               Logger.getLogger(testing1.class.getName()).log(Level.SEVERE, null, th);
             }finally
               if(preparedStatement!=null)
                   preparedStatement.close();
               if(conn!=null)
                   conn.close();
    }this is output
    GPSTime 2010-05-13 20:16:13.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:17:10.0 Time in seconds: 57 seconds.
    57
    GPSTime 2010-05-13 20:18:10.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:19:10.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:20:10.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:21:11.0 Time in seconds: 61 seconds.
    61
    GPSTime 2010-05-13 20:22:11.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:23:11.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:24:11.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:25:11.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:26:11.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:27:11.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:28:12.0 Time in seconds: 61 seconds.
    61
    GPSTime 2010-05-13 20:29:12.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:30:12.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:31:12.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:32:12.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:37:46.0 Time in seconds: 334 seconds.
    34
    GPSTime 2010-05-13 20:38:46.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 20:47:22.0 Time in seconds: 516 seconds.
    36
    GPSTime 2010-05-13 21:12:54.0 Time in seconds: 1532 seconds.
    32
    GPSTime 2010-05-13 21:13:54.0 Time in seconds: 60 seconds.
    60
    GPSTime 2010-05-13 21:14:55.0 Time in seconds: 61 seconds.
    61
    GPSTime 2010-05-13 21:37:08.0 Time in seconds: 1333 seconds.
    13
    GPSTime 2010-05-13 21:38:09.0 Time in seconds: 61 seconds.
    61
    31169.0
    08:39:29 hh:mm:ssi am getting the total time for all date
    i need only the particular date of total time
    2010-05-11-->total time
    2010-05-12->Total time
    2010-05-13->total time
    how do i change the given code to get the above output
    please help me anybody having idea

    Bakthavachalam wrote:
    i am getting the total time for all date
    i need only the particular date of total timeIn which case your while(rs.next()) loop needs to process 1 day at a time and print its results when the date changes (assuming your Timestamps come in in date sequence; if not, you'll have to sort them first).
    I suspect you'll also have to decide what you want to do with
    GPSTime 2010-05-13 23:59:59.0
    followed by
    GPSTime 2010-05-14 00:00:01.0
    Do you still need to calculate the difference? And if so, which "date" does it go in, or is it split?
    Your logic seems incredibly convoluted for such a simple task. What exactly are you trying to do?
    Winston
    BTW: TimeStamp.getSeconds() is deprecated, which means you use it at your peril.

  • Need help w corba/jdbc class

    hi
    i'm trying to get this class to work right, i don't think i'm coding it the right way, especially the getAllAccounts() and selectAccounts() methods. this code compiles cleanly, but i get runtime exceptions when i try to run my app. my runtime exceptions look like
    ############################ StackTrace ############################
    java.lang.NullPointerException
    at com.kafein.accountServices.AccountServiceImpl.getAllAccounts(AccountS
    erviceImpl.java:218)
    at com.kafein.idl.accountServices.AccountServicePOA._invoke(AccountServi
    cePOA.java:74)
    at org.jacorb.poa.RequestProcessor.invokeOperation(RequestProcessor.java
    :247)
    at org.jacorb.poa.RequestProcessor.process(RequestProcessor.java:477)
    at org.jacorb.poa.RequestProcessor.run(RequestProcessor.java:604)
    and
    Creating 100 Accounts
    org.omg.CORBA.UNKNOWN: This exception was reported by the server, it is only re-
    thrown here. vmcid: 0x0 minor code: 0 completed: No
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Sou
    rce)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.jacorb.orb.SystemExceptionHelper.read(SystemExceptionHelper.java:
    157)
    at org.jacorb.orb.connection.ReplyInputStream.checkExceptions(ReplyInput
    Stream.java:117)
    at org.jacorb.orb.Delegate.invoke(Delegate.java:942)
    at org.omg.CORBA.portable.ObjectImpl._invoke(Unknown Source)
    at com.kafein.idl.accountServices._AccountServiceStub.getAllAccounts(_Ac
    countServiceStub.java:134)
    at com.kafein.client.AccountClient.main(AccountClient.java:111)
    org.omg.CORBA.UNKNOWN: This exception was reported by the server, it is only re-
    thrown here. vmcid: 0x0 minor code: 0 completed: No
    ORB shutting down...
    code for this class is below...
    // AccountServiceImpl.java: The AccountService Implementation
    package com.kafein.accountServices;
    import java.util.Hashtable;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import junit.framework.TestCase;
    import junit.framework.Test;
    import junit.framework.TestSuite;
    import org.omg.PortableServer.*;
    import com.kafein.idl.accountServices.AccountServicePOA;
    import com.kafein.idl.accountServices.AccountEntryStruct;
    import com.kafein.idl.accountServices.AccountStruct;
    import com.kafein.idl.utilities.DateTimeStruct;
    import com.kafein.idl.exceptions.NotFoundException;
    import com.kafein.idl.exceptions.DataValidationException;
    import com.kafein.idl.errorCodes.DataValidationErrorCodes;
    import com.kafein.utils.ServiceHandler;
    import com.kafein.utils.Log;
    import java.net.URL;
    import java.sql.*;
    import java.util.*;
    * AccountServiceImpl is an implementation of the
    * idl.accountServices.AccountService interface.
    public class AccountServiceImpl extends AccountServicePOA {
      POA poa;
      private Hashtable accounts = new Hashtable(); // collection of Accounts
      private static int nextAccountID = 1; // global account ID
      Connection connection;
      Vector connections;
      Statement statement;
      PreparedStatement preparedStatement;
       * Construct an instance.
      public AccountServiceImpl(POA aPOA, String driver, String url, String user, String password) {
        super();
        poa = aPOA;
        driver = driver;
        url = url;
        user = user;
        password = password;
        connections = new Vector();
        // Connect to Database
        try {
            connect(driver,url,user,password);
        catch(Exception e) {
               e.printStackTrace();       
        // Simple Database Select
        try {
            testSimpleSelect();
        catch(Exception e) {
               e.printStackTrace();       
        // Database Select
        try {
            testSelect();
        catch(Exception e) {
               e.printStackTrace();       
       * Overloaded constructor for unit tests.
      protected AccountServiceImpl() {
        poa = null;
       * createAccount is used by administrator to add a new Account
       * in the system.
       * @param newAccount AccountEntryStruct containing data for new account
       * @return int the new unique Account ID
       * @exception com.kafein.idl.exceptions.DataValidationException
      public int createAccount(AccountEntryStruct newAccount) throws
        DataValidationException {
        validateData (newAccount); // throws DataValidationException;
        int accountID = getNextID();     
        // Create new Account.
        Account anAccount = new Account(accountID,
                            newAccount.userName,
                            newAccount.userEmail,
                            newAccount.creditCardType,
                            newAccount.creditCardNumber,
                            newAccount.creditCardExpirationDate.year,
                            newAccount.creditCardExpirationDate.month,
                            newAccount.userPassword,
                            newAccount.initialBalance);
    // Insert here / call method insertAccount() pass it in an account object
    // or call manager object - accountmanager.put()
        // Insert Account into Database
        try {
            insertAccount(anAccount);
        catch(Exception e) {
               e.printStackTrace();       
        accounts.put(accountID,anAccount);
        return accountID;
       * isAccountValid is used to validate a user logon.
       * @param accountID AccountID
       * @param userPassword String
       * @return boolean true to indicate an existing Account
      public boolean isValidAccount (int accountID, String userPassword) {
        // Get account with key equal to accountID.
        AccountStruct anAccount;
        try {
          anAccount = (AccountStruct) getAccount (accountID);
        catch (NotFoundException e) {
          return false;
        // Verify password.
        return (anAccount.userPassword.equals(userPassword) ? true : false);
       * getAccount is used to retrieve an existing Account in the system
       * @param int AccountID
       * @return AccountStruct containing data for the existing Account
       * @exception com.kafein.idl.exceptions.NotFoundException
      public AccountStruct getAccount(int accountID)throws
        NotFoundException {
        // Verify that accountID is within an appropriate interval.
        if (accountID < 1 || accountID > accounts.size()) {
          throw new NotFoundException(DataValidationErrorCodes.INVALID_ACCOUNT_ID,
                          "Account ID not found");
        // Get Account and convert to AccountStruct (which is returned).
        Account anAccount = (Account) accounts.get(accountID);
        return anAccount.getAccountStruct();
       * getAllAccounts is used to retrieve all existing Accounts in the system
       * @return AccountStruct[] containing all existing Accounts.
       * @fyi returns an empty sequence if no Accounts exist
      // GetAllAcounts method v. 2 - rather than enumerating through the vector
      // call a method that returns a collection of objs in that method where
      // you do select stmts
      public AccountStruct[] getAllAccounts() {
        // Allocate the array of AccountStructs.
        Vector results = new Vector();
        try {
                results = selectAccounts();
        catch(Exception e) {
               e.printStackTrace();       
        //Vector results = selectAccounts();
        int lastKey = results.size();
        //int lastKey = accounts.size();
        AccountStruct[] accountSequence = new AccountStruct[lastKey];
        if (lastKey==0) {
          return accountSequence;
        // Create AccountStructs from Accounts.
        for (int i = 1; i <= lastKey; i++) {
          Account anAccount = (Account) accounts.get(i);
          accountSequence[i-1] = anAccount.getAccountStruct();
        return accountSequence;
       * validateData is used to check new account data.
       * @param newAccount AccountEntryStruct containing data for new account
       * @exception com.kafein.idl.exceptions.DataValidationException
      protected void validateData(AccountEntryStruct newAccount) throws
        DataValidationException {
        // Check all of the member data in newAccount.
        if (newAccount.userName.equals("")) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_USER_NAME,
              "User Name must not be empty");
        if (newAccount.userEmail.equals("")) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_USER_EMAIL,
              "User Email must not be empty");
        if (newAccount.creditCardType.equals("")) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_CREDIT_CARD_TYPE,
              "Credit card type must not be empty");
        if (newAccount.creditCardNumber.equals("")) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_CREDIT_CARD_NUMBER,
              "Credit card number must not be empty");
        // Compare creditCardExpirationDate to current date
        // (we only consider year and month).
        GregorianCalendar now = new GregorianCalendar();
        DateTimeStruct proposed = newAccount.creditCardExpirationDate;
        if (proposed.year < now.get (Calendar.YEAR) ||
         (proposed.year == now.get (Calendar.YEAR) &&
          proposed.month < now.get (Calendar.MONTH) + 1)) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_CREDIT_CARD_EXPIRATION_DATE,
              "Credit card has expired");
        if (newAccount.userPassword.equals("")) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_USER_PASSWORD,
              "Password must not be empty");
        else if (!newAccount.userPassword.equals(newAccount.userPasswordVerification)) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_USER_PASSWORD,
              "Password verification failure");
        if (newAccount.initialBalance < 0.0F) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_BALANCE,
              "Account Balance cannot have a negative balance");
       * getNextID is used to generate a unique ID.
       * Needs a much better implementation that generates a globally unique ID!
       * @return int an Account ID
      protected synchronized int getNextID() {
        nextAccountID++;
        return nextAccountID - 1;
       * override _default_POA to return this servant's POA, not Root POA
      public POA _default_POA() {
        return poa;
       * jdbc related methods
      public void connect(String driver, String url, String user, String password)
                    throws Exception {
            try {
                // Load JDBC driver
                Class.forName(driver);
                System.out.println("Connecting to " + url);
                connection = DriverManager.getConnection(url, user, password);
                connections.add(connection);
                connection.setAutoCommit(false);
            } catch(Exception e) {
                System.err.println("System Exception in connect");
                System.err.println(e);
                throw e;
      public void closeConnection() throws Exception {
            try {
                Enumeration myEnum = connections.elements();
                while ( myEnum.hasMoreElements() ) {
                    System.out.println("Closing connection");
                    ((Connection) myEnum.nextElement()).close();
            } catch (Exception e) {
                System.err.println("System Exception in closeConnection");
                System.err.println(e);
                throw e;
      private void testSimpleSelect() throws Exception {
            try {
                Statement statement = connection.createStatement();
                ResultSet rs = statement.executeQuery("Select 1 from ACCOUNT");
                if (rs != null && rs.next()) {
                   int value = rs.getInt(1);
                   System.out.println("Fetched value " + value);
                connection.commit();
                statement.close();
            } catch(Exception e) {
                System.err.println("System Exception in testSimpleSelect");
                System.err.println(e);
                throw e;
      private void testSelect() throws Exception {
            try {
                Statement statement = connection.createStatement();
                ResultSet rs = statement.executeQuery(
                    "Select ACCT_ID, ACCT_USERNAME, ACCT_USEREMAIL, ACCT_CC_TYPE, ACCT_CC_NUMBER, ACCT_CC_EXPYR, ACCT_CC_EXPMO, ACCT_USERPASSWORD, ACCT_USERBALANCE from ACCOUNT LIMIT 1");
                System.out.println("Account ID   User Name     User Email     CC Type     CC Number     CC Expyr CC Expmo User Password     User Balance");
                while (rs != null && rs.next()) {
                    int acct_id = rs.getInt(1);
                    String acct_username = rs.getString(2);
                    String acct_useremail = rs.getString(3);
                    String acct_cc_type = rs.getString(4);
                    String acct_cc_number = rs.getString(5);
                    int acct_cc_expyr = rs.getInt(6);
                    int acct_cc_expmo = rs.getInt(7);
                    String acct_userpassword = rs.getString(8);
                    float acct_userbalance = rs.getFloat(9);
                    System.out.println(acct_id + "         " +
                                       acct_username + "   " +
                                       acct_useremail + "   " +
                                       acct_cc_type + "   " +
                                       acct_cc_number + "   " +
                                       acct_cc_expyr + "   " +
                                       acct_cc_expmo + "   " +
                                       acct_userpassword + "   " +
                                       acct_userbalance);
                connection.commit();
                statement.close();
            } catch(Exception e) {
                System.err.println("System Exception in testSelect");
                System.err.println(e);
                throw e;
      private void testLoadData() throws Exception {
            int numberOfAccounts = 5;
            String  acct_username    = "<--20 BYTE STRING-->";
            String  acct_useremail = "<--20 BYTE STRING-->";
         String  acct_cc_type = "TEST ";
            String  acct_cc_number = "<--20 BYTE STRING-->";
            int  acct_cc_expyr = 2000;
            int  acct_cc_expmo = 1;
            String  acct_userpassword = "<--20 BYTE STRING-->";
            float     acct_userbalance = 0.0F;
            int     acct_id = 0;
         try {
                System.out.println("Inserting data...");
                connection.setAutoCommit(false);
                // Calculate Start time
                System.out.println("Starting data insertion (" + numberOfAccounts +
                    " rows) into ACCOUNT table..");
                long startTime = System.currentTimeMillis();
                preparedStatement = connection.prepareStatement(
                    "INSERT INTO ACCOUNT (ACCT_ID, ACCT_USERNAME, ACCT_USEREMAIL, ACCT_CC_TYPE, ACCT_CC_NUMBER, " +
                    "ACCT_CC_EXPYR, ACCT_CC_EXPMO, ACCT_USERPASSWORD, ACCT_USERBALANCE) VALUES ( ?, ?, ?, ?, ?, ? , ?, ?, ?)");
                // Insert accounts in ACCOUNT table
                for (int i = 1; i <= numberOfAccounts; i++) {
                    acct_id  = i * 1000;
                    preparedStatement.setInt(1, acct_id);
                    preparedStatement.setString(2, acct_username);
                    preparedStatement.setString(3, acct_useremail);
                    preparedStatement.setString(4, acct_cc_type);
                    preparedStatement.setString(5, acct_cc_number);
                    preparedStatement.setInt(6, acct_cc_expyr);
                    preparedStatement.setInt(7, acct_cc_expmo);
                    preparedStatement.setString(8, acct_userpassword);
                    preparedStatement.setFloat(9, acct_userbalance);
              preparedStatement.executeUpdate();
                    connection.commit();
                System.out.println(numberOfAccounts + " accounts created.");
                preparedStatement.close();
                long stopTime = System.currentTimeMillis();
                System.out.println("Account table load complete.");
                System.out.println("Load time = " +
                                   ((stopTime - startTime)/(1000f)) + " seconds");
                System.out.println("Data insertion complete");
            } catch(Exception e) {
                System.err.println("System Exception in loadData");
                System.err.println(e);
                throw e;
       * insertAccount is used to insert a new Account in the Database
       * @param int AccountID
       * @return AccountStruct containing data for the existing Account
      private void insertAccount(Account anAccount) throws Exception {
              AccountStruct anAccountStruct = anAccount.getAccountStruct();  
         int numberOfAccounts = 1;
         String  acct_username    = anAccountStruct.userName;
            String  acct_useremail = anAccountStruct.userEmail;
         String  acct_cc_type = anAccountStruct.creditCardType;
            String  acct_cc_number = anAccountStruct.creditCardNumber;
         int acct_cc_expyr = anAccountStruct.creditCardExpirationDate.year;
            int acct_cc_expmo = anAccountStruct.creditCardExpirationDate.month;
            String  acct_userpassword = anAccountStruct.userPassword;
            float     acct_userbalance = anAccountStruct.accountBalance;
            int     acct_id = anAccountStruct.accountID;
         try {
                System.out.println("Inserting data...");
                connection.setAutoCommit(false);
    //instead of system.out just log
                // Calculate Start time
                System.out.println("Starting data insertion ( 1" +
                    " row) into ACCOUNT table..");
                long startTime = System.currentTimeMillis();
                preparedStatement = connection.prepareStatement(
                    "INSERT INTO ACCOUNT (ACCT_ID, ACCT_USERNAME, ACCT_USEREMAIL, ACCT_CC_TYPE, ACCT_CC_NUMBER, " +
                    "ACCT_CC_EXPYR, ACCT_CC_EXPMO, ACCT_USERPASSWORD, ACCT_USERBALANCE) VALUES ( ?, ?, ?, ?, ?, ? , ?, ?, ?)");
                    acct_id  = 1000;
                    preparedStatement.setInt(1, acct_id);
                    preparedStatement.setString(2, acct_username);
                    preparedStatement.setString(3, acct_useremail);
                    preparedStatement.setString(4, acct_cc_type);
                    preparedStatement.setString(5, acct_cc_number);
                    preparedStatement.setInt(6, acct_cc_expyr);
                    preparedStatement.setInt(7, acct_cc_expmo);
                    preparedStatement.setString(8, acct_userpassword);
                    preparedStatement.setFloat(9, acct_userbalance);
              preparedStatement.executeUpdate();
                    connection.commit();
                System.out.println("1 account created.");
                preparedStatement.close();
                long stopTime = System.currentTimeMillis();
                System.out.println("Account table load complete.");
                System.out.println("Load time = " +
                                   ((stopTime - startTime)/(1000f)) + " seconds");
                System.out.println("Data insertion complete");
            } catch(Exception e) {
                System.err.println("System Exception in loadData");
                System.err.println(e);
                throw e;
      private Vector selectAccounts() throws Exception {
            try {
                // Create Vector to hold individual Account values
             Vector mainvector = new Vector();
             Vector values = new Vector();
             Statement statement = connection.createStatement();
                ResultSet rs = statement.executeQuery(
                    "Select ACCT_ID, ACCT_USERNAME, ACCT_USEREMAIL, ACCT_CC_TYPE, ACCT_CC_NUMBER, ACCT_CC_EXPYR, ACCT_CC_EXPMO, ACCT_USERPASSWORD, ACCT_USERBALANCE from ACCOUNT");
                System.out.println("Account ID   User Name     User Email     CC Type     CC Number     CC Expyr CC Expmo User Password     User Balance");
             // Iterate through result set
             while (rs != null && rs.next()) {
              // Make sure values is empty
              values.clear();
              int acct_id = rs.getInt(1);
                    String acct_username = rs.getString(2);
                    String acct_useremail = rs.getString(3);
                    String acct_cc_type = rs.getString(4);
                    String acct_cc_number = rs.getString(5);
                    int acct_cc_expyr = rs.getInt(6);
                    int acct_cc_expmo = rs.getInt(7);
                    String acct_userpassword = rs.getString(8);
                    float acct_userbalance = rs.getFloat(9);
              // Populate Vector values
              values.addElement(rs.getObject(1));
              values.addElement(rs.getObject(2));
              values.addElement(rs.getObject(3));
              values.addElement(rs.getObject(4));
              values.addElement(rs.getObject(5));
              values.addElement(rs.getObject(6));
              values.addElement(rs.getObject(7));
              values.addElement(rs.getObject(8));
              values.addElement(rs.getObject(9));
              mainvector.addElement(values);
                    System.out.println(acct_id + "         " +
                                       acct_username + "   " +
                                       acct_useremail + "   " +
                                       acct_cc_type + "   " +
                                       acct_cc_number + "   " +
                                       acct_cc_expyr + "   " +
                                       acct_cc_expmo + "   " +
                                       acct_userpassword + "   " +
                                       acct_userbalance);
                connection.commit();
                statement.close();
             return mainvector;
            } catch(Exception e) {
                System.err.println("System Exception in selectAccounts");
                System.err.println(e);
                throw e;
        }

    line 217 and 218 is
    Account anAccount = (Account) accounts.get(i);
    accountSequence[i-1] = anAccount.getAccountStruct();
    i realized that
    Account anAccount = (Account) accounts.get(i);
    was a typo. what it should have been was
    Account anAccount = (Account) results.get(i);
    so my getAllAccounts() method now looks like
       * getAllAccounts is used to retrieve all existing Accounts in the system
       * @return AccountStruct[] containing all existing Accounts.
       * @fyi returns an empty sequence if no Accounts exist
      // GetAllAcounts method v. 2 - rather than enumerating through the vector
      // call a method that returns a collection of objs in that method where
      // you do select stmts
      public AccountStruct[] getAllAccounts() {
        // Allocate the array of AccountStructs.
        Vector results = new Vector();
        try {
                results = selectAccounts();
        catch(Exception e) {
               e.printStackTrace();       
        //Vector results = selectAccounts();
        int lastKey = results.size();
        //int lastKey = accounts.size();
        AccountStruct[] accountSequence = new AccountStruct[lastKey];
        if (lastKey==0) {
          return accountSequence;
        // Create AccountStructs from Accounts.
        for (int i = 1; i <= lastKey; i++) {
          Account anAccount = (Account) results.get(i);
          accountSequence[i-1] = anAccount.however, i still get the same runtime errors.
    is my selectAccounts() method returning a null?

  • Null Pointer Execption error when running application

    Hi there...
    I am trying to display content from a table in a database. I am using datasource to do this. When I run the application I am getting the following error:
    HTTP Status 500 -
    type Exception report
    message
    descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: java.lang.NullPointerException
    root cause
    java.lang.NullPointerException
    The 3 files involed are as follows:
    us_states.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
    <%@page import="java.util.ArrayList"%>
    <%@page import="net.ensode.glassfishbook.jdbcselect.UsStateBean"%>
    <%
              ArrayList<UsStateBean> stateList = (ArrayList<UsStateBean>) request
              .getAttribute("stateList");
    %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>US States</title>
    </head>
    <body>
    <table border="1" cellpadding="0" cellspacing="0" align="center">
         <caption><b>US State List</b></caption>
         <tr>
              <td><b>Name</b></td>
              <td><b>Abbreviation</b></td>
         </tr>
         <%
               for (UsStateBean state : stateList)
         %>
         <tr>
              <td><%=state.getStateName()%></td>
              <td><%=state.getStateCode()%></td>
         </tr>
         <%
         %>
    </table>
    </body>
    </html>
    JDBCSelectServlet.java:
    package net.ensode.glassfishbook.jdbcselect;
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.sql.DataSource;
    public class JDBCSelectServlet extends HttpServlet
      @Override
      protected void doGet(HttpServletRequest request,
                           HttpServletResponse response) throws
                           ServletException, IOException
        String sql = "select us_state_nm, " +
            "us_state_cd from us_states order by us_state_nm";
        ArrayList<UsStateBean> stateList =
            new ArrayList<UsStateBean>();
        try
          InitialContext initialContext = new InitialContext();
          DataSource dataSource = (DataSource) initialContext
              .lookup("jdbc/__CustomerDB1Pool");
          Connection connection = dataSource.getConnection();
          PreparedStatement preparedStatement =
              connection.prepareStatement(sql);
          ResultSet resultSet = preparedStatement.executeQuery();
          while (resultSet.next())
            stateList.add(new
                UsStateBean(resultSet.getString("us_state_nm"),
                resultSet.getString("us_state_cd")));
          resultSet.close();
          preparedStatement.close();
          connection.close();
          request.setAttribute("stateList", stateList);
          request.getRequestDispatcher("us_states.jsp").
              forward(request, response);
        catch (NamingException namingException)
          namingException.printStackTrace();
        catch (SQLException sqlException)
          sqlException.printStackTrace();
    UsStateBean.java:
    package net.ensode.glassfishbook.jdbcselect;
    public class UsStateBean
    public UsStateBean()
    public UsStateBean(String stateName, String stateCode)
    this.stateName = stateName;
    this.stateCode = stateCode;
    private String stateName;
    private String stateCode;
    public String getStateCode()
    return stateCode;
    public void setStateCode(String stateCode)
    this.stateCode = stateCode;
    public String getStateName()
    return stateName;
      public void setStateName(String stateName)
    this.stateName = stateName;
    }I am not sure what is wrong. Can anyone point out the problem to me? Thanks.

    Hi..
    The stack trace is as follows:
    StandardWrapperValve[jsp]: PWC1406: Servlet.service() for servlet jsp threw exception
    java.lang.NullPointerException
            at org.apache.jsp.us_005fstates_jsp._jspService(us_005fstates_jsp.java from :75)
            at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:109)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
            at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:389)
            at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:486)
            at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:380)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
            at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:427)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:315)
            at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:287)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:218)
            at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
            at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
            at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:94)
            at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:98)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:222)
            at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
            at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
            at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587)
            at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:166)
            at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
            at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
            at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587)
            at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096)
            at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:288)
            at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:647)
            at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:579)
            at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:831)
            at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341)
            at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:263)
            at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:214)
            at com.sun.enterprise.web.portunif.PortUnificationPipeline$PUTask.doTask(PortUnificationPipeline.java:380)
            at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265)
            at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106)

  • Insert CLOB values problem with 9.2 drivers and not with 10

    Hi
    We are using Oracle 9.2.0.5. We need to insert values bigger than 4000bytes using thin connection, so we've decided to use CLOB fields. With the 9.2.0.5 driver we can't do it, obtaining the classical exception explaining the data is bigger than the supported size but with the 10g driver (and, of course, same java code) it worked. The problem is that we want to mantain the equivalence between the database and driver not using the 10g driver with the 9.2.0.5 version of the db.
    Here it's the test code we've used:
    Data generation:     
              String data = "";
              Random rnd = new Random();
              long cont = 10000;
              while (cont > 0){               
                   int result = rnd.nextInt(255);
                   data = data + result;
                   cont--;
              Integer id = new Integer(2);
    Data insertion:
                   String queryString="INSERT INTO TMP_BUG_ORACLE (ID, VALOR) VALUES (?,?)";
                   preparedStatement = connection.prepareStatement(queryString);
                   preparedStatement.setInt(1,1);
                   preparedStatement.setString(2,this.datos);
                   int numero = preparedStatement.executeUpdate();               
                   System.out.println("Items inserted: " + numero);
                   preparedStatement.close();
                   connection.close();
    Table structure
         Name:          Type:
         ID           NUMBER
         VALOR      CLOB
    Response (only with 9.2.0.5 driver):
    java.sql.SQLException: El tamaño de los datos es mayor que el tamaño máximo para este tipo: 25708 (Data size is bigger than the maximum for this type: 25708)
    Thank you very much for all

    Hi,
    I had exactly the same problem. on Oracle 9.2 I wanted to insert a template file bigger than 4K. with the ojdbc14.jar from Oracle 9.2 it was not possible.
    What I did was this:
    I have used a JDBCwrapper to fix this issue. I can send it to you, if you send me your email.
    When I use the ojdbc14.jar from Oracle 10, I cannot insert a bigger file.
    How did you code your programm to insert big size data into a CLOB field with ojdbc14.jar driver from 10?
    thank you for your response

  • C$sync_history table not getting updated

    I am doing file based sync using the oracle APIs. While syncing there is no entry in the table showing Sync happened. but C$SYNC_LOG table is getting updated.
    Can anybody tell whats the issue.
    Thanks and Regards
    Lijo Lawrance

    Something additionaly. If the removeSession throws exception, or does not work as expected, the only way to continue is to extend the HeliosSession Class, and add to history by yourself.
    The code for extending the HeliosSession is listed above.
    The only thing you need is to call
    ((HeliosSessionExtended)localHeliosSession).addToSyncHistory(this); //this is the FDSession, or the new one used in constrctor of HeliosSession, or in the createSession Method from syncService)
    afert startSession completes successfully.
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import java.sql.Timestamp;
    import java.util.Iterator;
    import java.util.LinkedList;
    import oracle.lite.sync.HeliosSession;
    import oracle.lite.sync.HeliosTransport;
    import oracle.lite.sync.SiteDef;
    import oracle.lite.sync.Subscription;
    import oracle.lite.sync.SyncPubItemStatus;
    public class HeliosSessionExtended extends HeliosSession {
    public HeliosSessionExtended(HeliosTransport paramHeliosTransport) throws Throwable {
    super(paramHeliosTransport);
    //override the addToSyncHistory method
    void addToSyncHistory(Connection paramConnection) {
    //what I said about Sync_history
    if (!SiteDef.SYNC_HISTORY) {
    return;
    Long SessionId = this.getSessionId();
    Long DeviceSessionId = this.getDeviceSessionId();
    String clientId = this.getClientId();
    String memberId = this.getMemberId();
    String devicePlatform = this.getDevicePlatform();
    int result = this.getResult();
    String localHeliosMessage = this.getMessage();
    long startTime = this.getStartTimeMs();
    long finishTime = this.getFinishTimeMs();
    long uploadStartTime = this.getUploadStartTimeMs();
    long uploadFinishTime = this.getUploadFinishTimeMs();
    int recordCount = this.getUploadRecordCount();
    long uploadedByteCount = this.getUploadByteCount();
    long compressedByteCount = this.getUploadCompressedByteCount();
    LinkedList uploadedPubItems = this.getUploadPubItems();
    int uploadPubItemsSize = 0;
    if (uploadedPubItems != null) {
    uploadPubItemsSize = uploadedPubItems.size();
    long downloadStartTime = this.getDownloadStartTimeMs();
    long downloadFinishTime = this.getDownloadFinishTimeMs();
    int downloadRecordTime = this.getDownloadRecordCount();
    long downloadedByteCount = this.getDownloadByteCount();
    long downloadedCompressedByteCount = this.getDownloadCompressedByteCount();
    LinkedList downloadedPublicationItems = this.getDownloadPubItems();
    int downloadPubItemsSize = 0;
    if (downloadedPublicationItems != null) {
    downloadPubItemsSize = downloadedPublicationItems.size();
    int completeRefItemsCount = this.getCompleteRefreshItemCount();
    PreparedStatement preparedStatement = null;
    try {
    String insertString = "INSERT INTO C$SYNC_HISTORY (SESSION_ID,CLIENT_ID,DEVICE_PLATFORM,RESULT,START_TIME,FINISH_TIME,UPLOAD_START_TIME,UPLOAD_FINISH_TIME,UPLOAD_RECORD_COUNT,UPLOAD_BYTE_COUNT,UPLOAD_COMPRESSED_BYTE_COUNT,DOWNLOAD_START_TIME,DOWNLOAD_FINISH_TIME,DOWNLOAD_RECORD_COUNT,DOWNLOAD_BYTE_COUNT,DOWNLOAD_COMPRESSED_BYTE_COUNT,COMPLETE_REFRESH_ITEM_COUNT,DEVICE_SESSION_ID,UPLOAD_PUB_ITEM_COUNT,DOWNLOAD_PUB_ITEM_COUNT,MEMBER_CLIENT_ID) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    preparedStatement = paramConnection.prepareStatement(insertString);
    preparedStatement.setLong(1, SessionId.longValue());
    if ((clientId != null) && (clientId.length() > 0)) {
    SetStringParameter(preparedStatement, 2, clientId);
    } else {
    SetStringParameter(preparedStatement, 2, " ");
    if ((devicePlatform != null) && (devicePlatform.length() > 0)) {
    SetStringParameter(preparedStatement, 3, devicePlatform);
    } else {
    SetStringParameter(preparedStatement, 3, " ");
    if (result == 0) {
    preparedStatement.setString(4, "SUCCESS");
    } else if (result == 1) {
    preparedStatement.setString(4, "FAILURE");
    } else if (result == -1) {
    preparedStatement.setString(4, "UNKNOWN");
    } else {
    preparedStatement.setNull(4, 12);
    SetTimeParameter(preparedStatement, 5, startTime);
    SetTimeParameter(preparedStatement, 6, finishTime);
    SetTimeParameter(preparedStatement, 7, uploadStartTime);
    SetTimeParameter(preparedStatement, 8, uploadFinishTime);
    preparedStatement.setInt(9, recordCount);
    preparedStatement.setLong(10, uploadedByteCount);
    preparedStatement.setLong(11, compressedByteCount);
    SetTimeParameter(preparedStatement, 12, downloadStartTime);
    SetTimeParameter(preparedStatement, 13, downloadFinishTime);
    preparedStatement.setInt(14, downloadRecordTime);
    preparedStatement.setLong(15, downloadedByteCount);
    preparedStatement.setLong(16, downloadedCompressedByteCount);
    preparedStatement.setInt(17, completeRefItemsCount);
    if (DeviceSessionId != null) {
    preparedStatement.setLong(18, DeviceSessionId.longValue());
    } else {
    preparedStatement.setNull(18, 2);
    preparedStatement.setInt(19, uploadPubItemsSize);
    preparedStatement.setInt(20, downloadPubItemsSize);
    if (memberId != null) {
    preparedStatement.setString(21, memberId);
    } else {
    preparedStatement.setNull(21, 12);
    preparedStatement.executeUpdate();
    preparedStatement.close();
    preparedStatement = null;
    Object localObjcClob;
    if (localHeliosMessage != null) {
    localObjcClob = new Long[]{SessionId};
    Subscription.setCLOB(paramConnection, "C$SYNC_HISTORY", "MESSAGE", localHeliosMessage, "SESSION_ID=? ", (Object[]) localObjcClob);
    if (((uploadedPubItems != null) && (uploadedPubItems.size() > 0)) || ((downloadedPublicationItems != null) && (downloadedPublicationItems.size() > 0))) {
    insertString = "INSERT INTO C$SYNC_HIS_PUB_ITEMS (SESSION_ID,PHASE,PUBLICATION,PUB_ITEM,DEVICE_TABLE,START_TIME,FINISH_TIME,IS_COMPLETE_REFRESH,RECORD_COUNT,BYTE_COUNT,COMPRESSED_BYTE_COUNT,MESSAGE) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
    preparedStatement = paramConnection.prepareStatement(insertString);
    preparedStatement.setLong(1, SessionId.longValue());
    SyncPubItemStatus localSyncPubItemStatus;
    if ((uploadedPubItems != null) && (uploadedPubItems.size() > 0)) {
    preparedStatement.setString(2, "UPLOAD");
    localObjcClob = uploadedPubItems.iterator();
    while (((Iterator) localObjcClob).hasNext()) {
    localSyncPubItemStatus = (SyncPubItemStatus) ((Iterator) localObjcClob).next();
    SetStringParameter(preparedStatement, 3, localSyncPubItemStatus.publication);
    SetStringParameter(preparedStatement, 4, localSyncPubItemStatus.pubItem);
    SetStringParameter(preparedStatement, 5, localSyncPubItemStatus.deviceTable);
    SetTimeParameter(preparedStatement, 6, localSyncPubItemStatus.startTimeMs);
    SetTimeParameter(preparedStatement, 7, localSyncPubItemStatus.finishTimeMs);
    if (localSyncPubItemStatus.isCompleteRefresh) {
    preparedStatement.setString(8, "YES");
    } else {
    preparedStatement.setString(8, "NO");
    preparedStatement.setInt(9, localSyncPubItemStatus.recordCount);
    preparedStatement.setLong(10, localSyncPubItemStatus.byteCount);
    preparedStatement.setLong(11, localSyncPubItemStatus.compressedByteCount);
    SetStringParameter(preparedStatement, 12, localSyncPubItemStatus.message);
    preparedStatement.executeUpdate();
    if ((downloadedPublicationItems != null) && (downloadedPublicationItems.size() > 0)) {
    preparedStatement.setString(2, "DOWNLOAD");
    localObjcClob = downloadedPublicationItems.iterator();
    while (((Iterator) localObjcClob).hasNext()) {
    localSyncPubItemStatus = (SyncPubItemStatus) ((Iterator) localObjcClob).next();
    SetStringParameter(preparedStatement, 3, localSyncPubItemStatus.publication);
    SetStringParameter(preparedStatement, 4, localSyncPubItemStatus.pubItem);
    SetStringParameter(preparedStatement, 5, localSyncPubItemStatus.deviceTable);
    SetTimeParameter(preparedStatement, 6, localSyncPubItemStatus.startTimeMs);
    SetTimeParameter(preparedStatement, 7, localSyncPubItemStatus.finishTimeMs);
    if (localSyncPubItemStatus.isCompleteRefresh) {
    preparedStatement.setString(8, "YES");
    } else {
    preparedStatement.setString(8, "NO");
    preparedStatement.setInt(9, localSyncPubItemStatus.recordCount);
    preparedStatement.setLong(10, localSyncPubItemStatus.byteCount);
    preparedStatement.setLong(11, localSyncPubItemStatus.compressedByteCount);
    SetStringParameter(preparedStatement, 12, localSyncPubItemStatus.message);
    preparedStatement.executeUpdate();
    if (preparedStatement != null) {
    preparedStatement.close();
    preparedStatement = null;
    } catch (Throwable localThrowable) {
    //some error logging
    } finally {
    try {
    if (preparedStatement != null) {
    preparedStatement.close();
    preparedStatement = null;
    } catch (SQLException localSQLException2) {
    //some sqlexception logging
    void SetStringParameter(PreparedStatement paramPreparedStatement, int paramInt, String paramString)
    throws SQLException {
    if (paramString != null) {
    paramPreparedStatement.setString(paramInt, paramString);
    } else {
    paramPreparedStatement.setNull(paramInt, 12);
    void SetTimeParameter(PreparedStatement paramPreparedStatement, int paramInt, long paramLong)
    throws SQLException {
    if (paramLong > 0L) {
    paramPreparedStatement.setTimestamp(paramInt, new Timestamp(paramLong));
    } else {
    paramPreparedStatement.setNull(paramInt, 93);
    Edited by: FlorinA on Jul 6, 2010 12:37 AM
    Edited by: FlorinA on Jul 6, 2010 12:45 AM

  • Servlet not forwarding a control to the jsp with req dspher

    hi ppl,my servlet code is supposed to forward a control to a jsp page so as to display the value in the jsp.but the request dispatcher's forward is not forwarding the control to the jsp page.....here is my servlet code----
    // Decompiled by DJ v3.4.4.74 Copyright 2003 Atanas Neshkov  Date: 7/4/2003 12:37:00 PM
    // Home Page : http://members.fortunecity.com/neshkov/dj.html  - Check often for new version!
    // Decompiler options: packimports(3)
    // Source File Name:   BdgtMaster.java
    package publicity;
    import java.io.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class BdgtMaster extends HttpServlet
        public synchronized void service(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)
            throws ServletException, IOException
            Object obj = null;
            String s3 = "";
            String s4 = "";
            out = httpservletresponse.getOutputStream();
            String s = "";
            String s1 = "";
            String s2 = httpservletrequest.getParameter("option");
            s3 = httpservletrequest.getParameter("branch");
            s4 = httpservletrequest.getParameter("publicity_code");
            String s5 = httpservletrequest.getParameter("budget");
            try
                String s6 = "0";
                String s7 = "0";
                String s8 = "INSERT INTO Budget_Master(Branch,Publicity_Code,Budget_Alloted,Work_In_Progress,Amount_Paid) VALUES (?,?,?,?,?)";
                String s9 = "update budget_master set old_budget = budget_alloted where branch='" + s3 + "' and publicity_code=" + s4;
                String s10 = "UPDATE Budget_Master set budget_alloted=" + s5 + " where Branch='" + s3 + "' and publicity_code=" + s4;
                datasource = "jdbc:odbc:budget";
                con = DriverManager.getConnection(datasource);
                int i = con.getTransactionIsolation();
                con.setTransactionIsolation(2);
                con.setAutoCommit(false);
                if("new".equalsIgnoreCase(s2))
                    PreparedStatement preparedstatement = con.prepareStatement(s8);
                    preparedstatement.setString(1, s3);
                    preparedstatement.setString(2, s4);
                    preparedstatement.setString(3, s5);
                    preparedstatement.setString(4, s7);
                    preparedstatement.setString(5, s6);
                    preparedstatement.executeUpdate();
                    con.commit();
                    preparedstatement.close();
                if("update".equalsIgnoreCase(s2))
                    Statement statement = con.createStatement();
                    statement.executeUpdate(s9);
                    statement.executeUpdate(s10);
                    con.commit();
                con.setTransactionIsolation(0);
                /*htmlStart(out, "BUDGET MASTER");
                out.println("<p> </p><div align=\"left\">");
                out.println("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"50%\">");
                out.print("<tr>");
                out.println("<td width=\"50%\"><strong><small><font face=\"Tahoma\">Branch </font></small></strong></td>");
                out.println("<td width=\"50%\"><small><font color=\"#004080\" face=\"Tahoma\">" + s3 + "</font></small></td></tr><tr>");
                out.println("<td width=\"50%\"><strong><small><font face=\"Tahoma\">Budget Alloted </font></small></strong></td>");
                out.println("<td width=\"50%\"><small><font color=\"#004080\" face=\"Tahoma\">" + s5 + "</font></small></td></tr><tr>");
                out.println("<td width=\"50%\"><small><strong><font face=\"Tahoma\">Publicity Code</font></strong></small></td>");
                out.println("<td width=\"50%\"><small><font color=\"#004080\" face=\"Tahoma\">" + s4 + "</font></small></td></tr></table></div>");
                htmlEnd(out);
              con.close();
                httpservletrequest.getRequestDispatcher("/pages/serview/BdgM.jsp").forward(httpservletrequest,httpservletresponse);        
            catch(SQLException sqlexception)
                cleanUp();
                printSQLException(sqlexception, out);
            out.flush();
        public void init(ServletConfig servletconfig)
            throws ServletException
            super.init(servletconfig);
            try
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                return;
            catch(ClassNotFoundException classnotfoundexception)
                log("Couldn't load class sun.jdbc.odbc.JdbcOdbcDriver");
                throw new ServletException(classnotfoundexception.getMessage());
        static void printSQLException(SQLException sqlexception, ServletOutputStream servletoutputstream)
            throws IOException
            servletoutputstream.print("<b>SQLException</b>\n<p>\n\n");
            for(; sqlexception != null; sqlexception = sqlexception.getNextException())
                servletoutputstream.print("<b>SQLState:</b> " + sqlexception.getSQLState() + "<br>\n");
                servletoutputstream.print("<b>Message:</b> " + sqlexception.getMessage() + "<br>\n");
                servletoutputstream.print("<b>Vendor:</b> " + sqlexception.getErrorCode() + "<br>\n");
        private static boolean checkForWarning(SQLWarning sqlwarning)
            throws SQLException
            boolean flag = false;
            if(sqlwarning != null)
                System.out.println("\n *** Warning ***\n");
                flag = true;
                for(; sqlwarning != null; sqlwarning = sqlwarning.getNextWarning())
                    System.out.println("SQLState: " + sqlwarning.getSQLState());
                    System.out.println("Message:  " + sqlwarning.getMessage());
                    System.out.println("Vendor:   " + sqlwarning.getErrorCode());
                    System.out.println("");
            return flag;
        /*void htmlStart(ServletOutputStream servletoutputstream, String s)
            throws IOException
            servletoutputstream.println("<html><head><title>" + s + "</title></head>");
            servletoutputstream.println("<body topmargin=\"0\" leftmargin=\"0\" bgproperties=\"fixed\">");
            servletoutputstream.println("<div align=\"left\"><table border=\"0\" width=\"100%\">");
            servletoutputstream.println("<tr><td width=\"100%\" bgcolor=\"#DFDFFF\">");
            servletoutputstream.println("<font face=\"Tahoma\" color=\"#000000\"><strong>B u d g e t   M a s t e r - D e t a i l s   E n t e r e d</strong></font></td>");
            servletoutputstream.println("</tr></table>");
        void htmlEnd(ServletOutputStream servletoutputstream)
            throws IOException
            servletoutputstream.print("<hr>");
            servletoutputstream.print("</body></html>\n");
        String link(String s, String s1)
            return "<a href=\"" + s + "\">" + s1 + "</a>";
        public String getServletInfo()
            return "Display and SQL manipulate JDBC databases on the server.";
        public void cleanUp()
            throws IOException
            if(con != null)
                try
                    out.print("Closing database connection");
                    con.setTransactionIsolation(0);
                    con.close();
                    return;
                catch(SQLException _ex)
                    return;
            else
                return;
        public BdgtMaster()
        private Connection con;
        private String datasource;
        private String user;
        private String password;
        private String base;
        private ServletOutputStream out;
    plz tell me where im wrong...
    regards....a_joseph

    Hi,
    Sorry to say this but it'd be lot simple if we can avoid cross posting similar Queries.
    I'd appriciate if you can continue using with your post
    http://forum.java.sun.com/thread.jspa?threadID=5208928
    Hope there are no hard issues on this.
    REGARDS,
    RaHuL

Maybe you are looking for

  • Error Parsing Structure File

    When I try to access a project that is in RoboSource Control, I keep getting this error "Error Parsing Structure File". Does anyone know what this means and how to fix it? Thanks.

  • How to assign ALV for parent node and child node that uses supply method.?

    HI Dear friends,     I need to display header details ( VBAK ) and Item details ( VBAP ). I have created two node like HEADER_NODE inside this i have created ITEM_NODE for this item node i use supply function 'GET_ITEMS'  any way it is working only w

  • Using Java swing layout

    I'm rather new at this and i'm having trouble creating my desired layout, actually i'm having trouble picking my desired layout. this is how i'd want my program to look... name place time address mary Hos. 12:00 70 sine st. JButton Kay Sch. 1:00 13 c

  • How to set acknowledgement flag in asynchronous message

    Hello, I just read in the documenation that it is possible to request acknowlegment messages by setting an "acknowledgement tag" in the request message. My question now is how to set this acknowledgement tag and which rules I have to follow? Do you h

  • Permission denied :Oracle 10g on RHEL4

    I am using ubuntu 10.10 and Virtualbox installed on it.I have installed red hat (RHEL4) on virtualbox.When i try to run the oracle installer from the cdrom i get the following error "permission denied".I am have tried to edit fstab entry in /etc but