示例#1
0
    protected void generateDelegateCode(
        Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {

      String mname = method.getName();
      if (jdbc4WrapperMethod(mname)) {
        generateWrapperDelegateCode(intfcl, genclass, method, iw);
        return;
      }

      Class retType = method.getReturnType();

      iw.println("if (proxyConn != null) proxyConn.maybeDirtyTransaction();");
      iw.println();

      if (mname.equals("close")) {
        iw.println("if (! this.isDetached())");
        iw.println("{");
        iw.upIndent();

        iw.println("if (creator instanceof Statement)");
        iw.upIndent();
        iw.println(
            "parentPooledConnection.markInactiveResultSetForStatement( (Statement) creator, inner );");
        iw.downIndent();
        iw.println("else if (creator instanceof DatabaseMetaData)");
        iw.upIndent();
        iw.println("parentPooledConnection.markInactiveMetaDataResultSet( inner );");
        iw.downIndent();
        iw.println("else if (creator instanceof Connection)");
        iw.upIndent();
        iw.println("parentPooledConnection.markInactiveRawConnectionResultSet( inner );");
        iw.downIndent();
        iw.println(
            "else throw new InternalError(\042Must be Statement or DatabaseMetaData -- Bad Creator: \042 + creator);");

        iw.println(
            "if (creatorProxy instanceof ProxyResultSetDetachable) ((ProxyResultSetDetachable) creatorProxy).detachProxyResultSet( this );");

        iw.println("this.detach();");
        iw.println("inner.close();");
        iw.println("this.inner = null;");

        iw.downIndent();
        iw.println("}");
      } else if (mname.equals("getStatement")) {
        iw.println("if (creator instanceof Statement)");
        iw.upIndent();
        iw.println("return (Statement) creatorProxy;");
        iw.downIndent();
        iw.println("else if (creator instanceof DatabaseMetaData)");
        iw.upIndent();
        iw.println("return null;");
        iw.downIndent();
        iw.println(
            "else throw new InternalError(\042Must be Statement or DatabaseMetaData -- Bad Creator: \042 + creator);");
      } else if (mname.equals("isClosed")) {
        iw.println("return this.isDetached();");
      } else super.generateDelegateCode(intfcl, genclass, method, iw);
    }
示例#2
0
文件: DBManager.java 项目: kone/kin
 public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
   try {
     String method = m.getName();
     if ("prepareStatement".equals(method) || "createStatement".equals(method))
       log.info("[SQL] >>> " + args[0]);
     return m.invoke(conn, args);
   } catch (InvocationTargetException e) {
     throw e.getTargetException();
   }
 }
示例#3
0
 public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
   Object obj = null;
   if (CLOSE_METHOD_NAME.equals(m.getName())) {
     SimpleConnectionPool.pushConnectionBackToPool(this);
   } else {
     obj = m.invoke(m_originConnection, args);
   }
   lastAccessTime = System.currentTimeMillis();
   return obj;
 }
  //
  // Examine a single method to see if it raises SQLFeatureNotSupportedException.
  //
  private void vetMethod(
      Object candidate,
      Class iface,
      Method method,
      HashSet<String> unsupportedList,
      HashSet<String> notUnderstoodList)
      throws Exception {
    try {
      method.invoke(candidate, getNullArguments(method.getParameterTypes()));

      // it's ok for the method to succeed
    } catch (Throwable e) {
      if (!(e instanceof InvocationTargetException)) {
        recordUnexpectedError(candidate, iface, method, notUnderstoodList, e);
      } else {
        Throwable cause = e.getCause();

        if (cause instanceof SQLFeatureNotSupportedException) {
          boolean isExcludable = isExcludable(method);

          if (!isExcludable) {
            StackTraceElement[] stack = cause.getStackTrace();
            int i = 0;
            while (i < stack.length && !stack[i].getMethodName().equals("notImplemented")) {
              ++i;
            }
            while (i < stack.length && stack[i].getMethodName().equals("notImplemented")) {
              ++i;
            }
            if (i == stack.length) {
              // cause.printStackTrace();
            }

            unsupportedList.add(
                candidate.getClass().getName()
                    + ": "
                    + method
                    + "@"
                    + (i == stack.length ? "no source" : cause.getStackTrace()[i]));
          } else {

          }
        } else if (cause instanceof SQLException) {
          // swallow other SQLExceptions, caused by bogus args
        } else if (cause instanceof NullPointerException) {
          // swallow other NPEs, caused by bogus args
        } else if (cause instanceof ArrayIndexOutOfBoundsException) {
          // swallow these, caused by bogus args
        } else {
          recordUnexpectedError(candidate, iface, method, notUnderstoodList, cause);
        }
      }
    }
  }
示例#5
0
 /**
  * Checks if the invocation of the method throws a SQLExceptio as expected.
  *
  * @param LOB the Object that implements the Blob interface
  * @param method the method that needs to be tested to ensure that it throws the correct exception
  * @return true If the method throws the SQLException required after the free method has been
  *     called on the LOB object
  */
 boolean checkIfMethodThrowsSQLException(Object LOB, Method method)
     throws IllegalAccessException, InvocationTargetException {
   try {
     method.invoke(LOB, getNullValues(method.getParameterTypes()));
   } catch (InvocationTargetException ite) {
     Throwable cause = ite.getCause();
     if (cause instanceof SQLException) {
       return ((SQLException) cause).getSQLState().equals("XJ215");
     }
     throw ite;
   }
   return false;
 }
示例#6
0
  boolean closeAndRemoveResourcesInSet(Set s, Method closeMethod) {
    boolean okay = true;

    Set temp;
    synchronized (s) {
      temp = new HashSet(s);
    }

    for (Iterator ii = temp.iterator(); ii.hasNext(); ) {
      Object rsrc = ii.next();
      try {
        closeMethod.invoke(rsrc, CLOSE_ARGS);
      } catch (Exception e) {
        Throwable t = e;
        if (t instanceof InvocationTargetException)
          t = ((InvocationTargetException) e).getTargetException();
        logger.log(MLevel.WARNING, "An exception occurred while cleaning up a resource.", t);
        // t.printStackTrace();
        okay = false;
      } finally {
        s.remove(rsrc);
      }
    }

    // We had to abandon the idea of simply iterating over s directly, because
    // our resource close methods sometimes try to remove the resource from
    // its parent Set. This is important (when the user closes the resources
    // directly), but leads to ConcurrenModificationExceptions while we are
    // iterating over the Set to close. So, now we iterate over a copy, but remove
    // from the original Set. Since removal is idempotent, it don't matter if
    // the close method already provoked a remove. Sucks that we have to copy
    // the set though.
    //
    // Original (direct iteration) version:
    //
    //  	synchronized (s)
    //  	    {
    //  		for (Iterator ii = s.iterator(); ii.hasNext(); )
    //  		    {
    //  			Object rsrc = ii.next();
    //  			try
    //  			    { closeMethod.invoke(rsrc, CLOSE_ARGS); }
    //  			catch (Exception e)
    //  			    {
    //  				Throwable t = e;
    //  				if (t instanceof InvocationTargetException)
    //  				    t = ((InvocationTargetException) e).getTargetException();
    //  				t.printStackTrace();
    //  				okay = false;
    //  			    }
    //  			finally
    //  			    { ii.remove(); }
    //  		    }
    //  	    }

    return okay;
  }
  //
  // Returns true if this method is allowed to raise SQLFeatureNotSupportedException.
  //
  private boolean isExcludable(Method method) throws Exception {
    Class iface = method.getDeclaringClass();
    HashSet<Method> excludableMethods = excludableMap.get(iface);

    if (excludableMethods == null) {
      return false;
    }

    return excludableMethods.contains(method);
  }
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   if (state != STATE_IDLE) {
     String methodName = method.getName();
     if (methodName.equals("commit")
         || methodName.equals("rollback")
         || methodName.equals("setSavePoint")
         || (methodName.equals("setAutoCommit") && ((Boolean) args[0]).booleanValue())) {
       throw new PSQLException(
           GT.tr(
               "Transaction control methods setAutoCommit(true), commit, rollback and setSavePoint not allowed while an XA transaction is active."),
           PSQLState.OBJECT_NOT_IN_STATE);
     }
   }
   try {
     return method.invoke(con, args);
   } catch (InvocationTargetException ex) {
     throw ex.getTargetException();
   }
 }
示例#9
0
    protected void generateDelegateCode(
        Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {
      String mname = method.getName();
      if (jdbc4WrapperMethod(mname)) {
        generateWrapperDelegateCode(intfcl, genclass, method, iw);
        return;
      }

      Class retType = method.getReturnType();

      if (ResultSet.class.isAssignableFrom(retType)) {
        iw.println("ResultSet innerResultSet = inner." + CodegenUtils.methodCall(method) + ";");
        iw.println("if (innerResultSet == null) return null;");
        iw.println(
            "return new NewProxyResultSet( innerResultSet, parentPooledConnection, inner, this );");
      } else if (mname.equals("getConnection")) {
        iw.println("return this.proxyCon;");
      } else super.generateDelegateCode(intfcl, genclass, method, iw);
    }
示例#10
0
  /**
   * Enumerate the methods of the Clob interface and get the list of methods present in the
   * interface
   *
   * @param LOB an instance of the Clob interface implementation
   */
  void buildMethodList(Object LOB) throws IllegalAccessException, InvocationTargetException {
    // If the given method throws the correct exception
    // set this to true and add it to the
    boolean valid = true;

    // create a list of the methods that fail the test
    Vector<Method> methodList = new Vector<Method>();

    // The class whose methods are to be verified
    Class clazz = Clob.class;

    // The list of the methods in the class that need to be invoked
    // and verified
    Method[] methods = clazz.getMethods();

    // Check each of the methods to ensure that
    // they throw the required exception
    for (int i = 0; i < methods.length; i++) {
      if (!checkIfExempted(methods[i])) {
        valid = checkIfMethodThrowsSQLException(LOB, methods[i]);

        // add the method to the list if the method does
        // not throw the required exception
        if (valid == false) methodList.add(methods[i]);

        // reset valid
        valid = true;
      }
    }

    if (!methodList.isEmpty()) {
      int c = 0;
      String failureMessage = "The Following methods don't throw " + "required exception - ";
      for (Method m : methodList) {
        c = c + 1;
        if (c == methodList.size() && c != 1) failureMessage += " & ";
        else if (c != 1) failureMessage += " , ";
        failureMessage += m.getName();
      }
      fail(failureMessage);
    }
  }
示例#11
0
    protected void generatePreDelegateCode(
        Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {
      if ("setClientInfo".equals(method.getName())) {
        iw.println("try");
        iw.println("{");
        iw.upIndent();

        super.generatePreDelegateCode(intfcl, genclass, method, iw);

      } else super.generatePreDelegateCode(intfcl, genclass, method, iw);
    }
示例#12
0
    protected void generatePostDelegateCode(
        Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {
      if ("setClientInfo".equals(method.getName())) {
        super.generatePostDelegateCode(intfcl, genclass, method, iw);

        iw.downIndent();
        iw.println("}");
        iw.println("catch (Exception e)");
        iw.println("{ throw SqlUtils.toSQLClientInfoException( e ); }");
      } else super.generatePostDelegateCode(intfcl, genclass, method, iw);
    }
示例#13
0
    void generateFindMethodAndArgs(Method method, IndentedWriter iw) throws IOException {
      iw.println("Class[] argTypes = ");
      iw.println("{");
      iw.upIndent();

      Class[] argTypes = method.getParameterTypes();
      for (int i = 0, len = argTypes.length; i < len; ++i) {
        if (i != 0) iw.println(",");
        iw.print(CodegenUtils.simpleClassName(argTypes[i]) + ".class");
      }
      iw.println();
      iw.downIndent();
      iw.println("};");
      iw.println(
          "Method method = Connection.class.getMethod( \042"
              + method.getName()
              + "\042 , argTypes );");
      iw.println();
      iw.println("Object[] args = ");
      iw.println("{");
      iw.upIndent();

      for (int i = 0, len = argTypes.length; i < len; ++i) {
        if (i != 0) iw.println(",");
        String argName = CodegenUtils.generatedArgumentName(i);
        Class argType = argTypes[i];
        if (argType.isPrimitive()) {
          if (argType == boolean.class) iw.print("Boolean.valueOf( " + argName + " )");
          else if (argType == byte.class) iw.print("new Byte( " + argName + " )");
          else if (argType == char.class) iw.print("new Character( " + argName + " )");
          else if (argType == short.class) iw.print("new Short( " + argName + " )");
          else if (argType == int.class) iw.print("new Integer( " + argName + " )");
          else if (argType == long.class) iw.print("new Long( " + argName + " )");
          else if (argType == float.class) iw.print("new Float( " + argName + " )");
          else if (argType == double.class) iw.print("new Double( " + argName + " )");
        } else iw.print(argName);
      }

      iw.downIndent();
      iw.println("};");
    }
示例#14
0
 private static void generateWrapperDelegateCode(
     Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {
   String mname = method.getName();
   if ("isWrapperFor".equals(mname)) {
     iw.println("return ( isWrapperForInner( a ) || isWrapperForThis( a ) );");
   } else if ("unwrap".equals(mname)) {
     iw.println("if (this.isWrapperForInner( a )) return inner.unwrap( a );");
     iw.println("if (this.isWrapperForThis( a )) return this;");
     iw.println(
         "else throw new SQLException( this + \042 is not a wrapper for or implementation of \042 + a.getName());");
   }
 }
示例#15
0
      public Object doRawStatementOperation(Method m, Object target, Object[] args)
          throws IllegalAccessException, InvocationTargetException, SQLException {
        if (target == C3P0ProxyStatement.RAW_STATEMENT) target = nakedInner;
        for (int i = 0, len = args.length; i < len; ++i)
          if (args[i] == C3P0ProxyStatement.RAW_STATEMENT) args[i] = nakedInner;

        Object out = m.invoke(target, args);

        if (out instanceof ResultSet) out = wrap((ResultSet) out);

        return out;
      }
示例#16
0
  /** private method which actually will do all of our work for the sample */
  private void executeSample() {

    String query = "select anEmployee from staff2";
    try {
      Statement stmt = _con.createStatement();
      ;

      // Execute the query which will return an Employee object
      // We will cast this using the Person interface. Note the
      // Person interface class MUST be in your CLASSPATH. You
      // Do not need Employee in your CLASSPATH.
      ResultSet rs = stmt.executeQuery(query);

      output("***Using interface class\n");
      while (rs.next()) {
        Person aPerson = (Person) rs.getObject(1);
        displayMethods(aPerson.getClass());
        output(
            "The person is: "
                + aPerson.toString()
                + "\nFirst Name= "
                + aPerson.getFirstName()
                + "\nLast Name= "
                + aPerson.getLastName()
                + "\n");
      }
      // Now execute the same query, but this time we will use
      // reflection to access the class.  Again, only the interface
      // Person is required in the CLASSPATH
      rs = stmt.executeQuery(query);

      output("***Using reflection\n");
      Object theObj = null;
      while (rs.next()) {
        theObj = rs.getObject(1);
        output("The person is: " + theObj.toString() + "\n");
        Class theClass = theObj.getClass();
        displayMethods(theClass);
        Method m1 = theClass.getMethod("toString", new Class[0]);
        Method m2 = theClass.getMethod("getFirstName", new Class[0]);
        Method m3 = theClass.getMethod("getLastName", new Class[0]);
        output(
            "The person is: "
                + (Object) m1.invoke(theObj, new Object[0])
                + "\nFirst Name= "
                + (Object) m2.invoke(theObj, new Object[0])
                + "\nLast Name= "
                + (Object) m3.invoke(theObj, new Object[0])
                + "\n");
      }
      rs.close();
      stmt.close();
    } catch (SQLException sqe) {
      displaySQLEx(sqe);
    } catch (Exception e) {
      error("Unexpected exception : " + e.toString() + "\n");
      e.printStackTrace();
    }
  }
示例#17
0
    private Object doRawConnectionOperation(Method m, Object target, Object[] args)
        throws IllegalAccessException, InvocationTargetException, SQLException, Exception {
      if (activeConnection == null)
        throw new SQLException(
            "Connection previously closed. You cannot operate on a closed Connection.");

      if (target == C3P0ProxyConnection.RAW_CONNECTION) target = activeConnection;
      for (int i = 0, len = args.length; i < len; ++i)
        if (args[i] == C3P0ProxyConnection.RAW_CONNECTION) args[i] = activeConnection;

      Object out = m.invoke(target, args);

      // we never cache Statements generated by an operation on the raw Connection
      if (out instanceof Statement) out = createProxyStatement(false, (Statement) out);
      else if (out instanceof ResultSet) {
        if (doRawResultSets == null) doRawResultSets = new HashSet();
        out = new NullStatementSetManagedResultSet((ResultSet) out, doRawResultSets);
      }
      return out;
    }
示例#18
0
    protected void generateDelegateCode(
        Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {

      String mname = method.getName();
      if (jdbc4WrapperMethod(mname)) {
        generateWrapperDelegateCode(intfcl, genclass, method, iw);
        return;
      }

      Class retType = method.getReturnType();

      iw.println("maybeDirtyTransaction();");
      iw.println();

      if (ResultSet.class.isAssignableFrom(retType)) {
        iw.println("ResultSet innerResultSet = inner." + CodegenUtils.methodCall(method) + ";");
        iw.println("if (innerResultSet == null) return null;");
        iw.println(
            "parentPooledConnection.markActiveResultSetForStatement( inner, innerResultSet );");
        iw.println(
            "NewProxyResultSet out = new NewProxyResultSet( innerResultSet, parentPooledConnection, inner, this );");
        iw.println("synchronized ( myProxyResultSets ) { myProxyResultSets.add( out ); }");
        iw.println("return out;");
      } else if (mname.equals("getConnection")) {
        iw.println("if (! this.isDetached())");
        iw.upIndent();
        iw.println("return creatorProxy;");
        iw.downIndent();
        iw.println("else");
        iw.upIndent();
        iw.println("throw new SQLException(\"You cannot operate on a closed Statement!\");");
        iw.downIndent();
      } else if (mname.equals("close")) {
        iw.println("if (! this.isDetached())");
        iw.println("{");
        iw.upIndent();
        // iw.println("System.err.println(\042Closing proxy Statement: \042 + this);");
        iw.println("synchronized ( myProxyResultSets )");
        iw.println("{");
        iw.upIndent();
        iw.println("for( Iterator ii = myProxyResultSets.iterator(); ii.hasNext(); )");
        iw.println("{");
        iw.upIndent();
        iw.println("ResultSet closeMe = (ResultSet) ii.next();");
        iw.println("ii.remove();");
        iw.println();
        iw.println("try { closeMe.close(); }");
        iw.println("catch (SQLException e)");
        iw.println("{");
        iw.upIndent();
        iw.println("if (logger.isLoggable( MLevel.WARNING ))");
        iw.upIndent();
        iw.println(
            "logger.log( MLevel.WARNING, \042Exception on close of apparently orphaned ResultSet.\042, e);");
        iw.downIndent();
        iw.downIndent();
        iw.println("}");
        iw.println("if (logger.isLoggable( MLevel.FINE ))");
        iw.upIndent();
        iw.println(
            "logger.log( MLevel.FINE, this + \042 closed orphaned ResultSet: \042 +closeMe);");
        iw.downIndent();
        iw.downIndent();
        iw.println("}");
        iw.downIndent();
        iw.println("}");
        iw.println();
        iw.println("if ( is_cached )");
        iw.upIndent();
        iw.println("parentPooledConnection.checkinStatement( inner );");
        iw.downIndent();
        iw.println("else");
        iw.println("{");
        iw.upIndent();
        iw.println("parentPooledConnection.markInactiveUncachedStatement( inner );");

        iw.println("try{ inner.close(); }");
        iw.println("catch (Exception e )");
        iw.println("{");
        iw.upIndent();

        iw.println("if (logger.isLoggable( MLevel.WARNING ))");
        iw.upIndent();
        iw.println(
            "logger.log( MLevel.WARNING, \042Exception on close of inner statement.\042, e);");
        iw.downIndent();

        iw.println("SQLException sqle = SqlUtils.toSQLException( e );");
        iw.println("throw sqle;");
        iw.downIndent();
        iw.println("}");
        iw.downIndent();
        iw.println("}");

        iw.println();
        iw.println("this.detach();");
        iw.println("this.inner = null;");
        iw.println("this.creatorProxy = null;");

        iw.downIndent();
        iw.println("}");
      } else if (mname.equals("isClosed")) {
        iw.println("return this.isDetached();");
      } else super.generateDelegateCode(intfcl, genclass, method, iw);
    }
示例#19
0
  void generateTryCloserAndCatch(Class intfcl, String genclass, Method method, IndentedWriter iw)
      throws IOException {
    iw.downIndent();
    iw.println("}");
    iw.println("catch (NullPointerException exc)");
    iw.println("{");
    iw.upIndent();
    iw.println("if ( this.isDetached() )");
    iw.println("{");
    iw.upIndent();
    // iw.println( "System.err.print(\042probably 'cuz we're closed -- \042);" );
    // iw.println( "exc.printStackTrace();" );
    if ("close".equals(method.getName())) {
      iw.println("if (Debug.DEBUG && logger.isLoggable( MLevel.FINE ))");
      iw.println("{");
      iw.upIndent();
      iw.println("logger.log( MLevel.FINE, this + \042: close() called more than once.\042 );");

      // premature-detach-debug-debug only!
      if (PREMATURE_DETACH_DEBUG) {
        iw.println("prematureDetachRecorder.record();");
        iw.println(
            "logger.warning( prematureDetachRecorder.getDump(\042Apparent multiple close of "
                + getInnerTypeName()
                + ".\042) );");
      }
      // end-premature-detach-debug-only!

      iw.downIndent();
      iw.println("}");
    } else {
      // premature-detach-debug-debug only!
      if (PREMATURE_DETACH_DEBUG) {
        iw.println("prematureDetachRecorder.record();");
        iw.println(
            "logger.warning( prematureDetachRecorder.getDump(\042Use of already detached "
                + getInnerTypeName()
                + ".\042) );");
      }
      // end-premature-detach-debug-only!

      iw.println(
          "throw SqlUtils.toSQLException(\042You can't operate on a closed "
              + getInnerTypeName()
              + "!!!\042, exc);");
    }
    iw.downIndent();
    iw.println("}");
    iw.println("else throw exc;");
    iw.downIndent();
    iw.println("}");
    iw.println("catch (Exception exc)");
    iw.println("{");
    iw.upIndent();
    iw.println("if (! this.isDetached())");
    iw.println("{");
    iw.upIndent();
    // iw.println( "exc.printStackTrace();" );
    iw.println("throw parentPooledConnection.handleThrowable( exc );");
    iw.downIndent();
    iw.println("}");
    iw.println("else throw SqlUtils.toSQLException( exc );");
    iw.downIndent();
    iw.println("}");
  }
示例#20
0
 protected void generatePostDelegateCode(
     Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {
   if (method.getExceptionTypes().length > 0)
     super.generatePostDelegateCode(intfcl, genclass, method, iw);
 }
示例#21
0
 protected void generatePostDelegateCode(
     Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {
   if (!jdbc4WrapperMethod(method.getName()))
     generateTryCloserAndCatch(intfcl, genclass, method, iw);
 }
示例#22
0
 protected void generatePreDelegateCode(
     Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {
   if (!jdbc4WrapperMethod(method.getName())) generateTryOpener(iw);
 }
示例#23
0
    public synchronized Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
      if (OBJECT_METHODS.contains(m)) return m.invoke(this, args);

      try {
        String mname = m.getName();
        if (activeConnection != null) {
          if (mname.equals("rawConnectionOperation")) {
            ensureOkay();
            txn_known_resolved = false;

            return doRawConnectionOperation((Method) args[0], args[1], (Object[]) args[2]);
          } else if (mname.equals("setTransactionIsolation")) {
            ensureOkay();

            // don't modify txn_known_resolved

            m.invoke(activeConnection, args);

            int lvl = ((Integer) args[0]).intValue();
            isolation_lvl_nondefault = (lvl != dflt_txn_isolation);

            // System.err.println("updated txn isolation to " + lvl + ", nondefault level? " +
            // isolation_lvl_nondefault);

            return null;
          } else if (mname.equals("setCatalog")) {
            ensureOkay();

            // don't modify txn_known_resolved

            m.invoke(activeConnection, args);

            String catalog = (String) args[0];
            catalog_nondefault = ObjectUtils.eqOrBothNull(catalog, dflt_catalog);

            return null;
          } else if (mname.equals("setHoldability")) {
            ensureOkay();

            // don't modify txn_known_resolved

            m.invoke(
                activeConnection,
                args); // will throw an exception if setHoldability() not supported...

            int holdability = ((Integer) args[0]).intValue();
            holdability_nondefault = (holdability != dflt_holdability);

            return null;
          } else if (mname.equals("createStatement")) {
            ensureOkay();
            txn_known_resolved = false;

            Object stmt = m.invoke(activeConnection, args);
            return createProxyStatement((Statement) stmt);
          } else if (mname.equals("prepareStatement")) {
            ensureOkay();
            txn_known_resolved = false;

            Object pstmt;
            if (scache == null) {
              pstmt = m.invoke(activeConnection, args);
              return createProxyStatement((Statement) pstmt);
            } else {
              pstmt = scache.checkoutStatement(physicalConnection, m, args);
              return createProxyStatement(true, (Statement) pstmt);
            }
          } else if (mname.equals("prepareCall")) {
            ensureOkay();
            txn_known_resolved = false;

            Object cstmt;
            if (scache == null) {
              cstmt = m.invoke(activeConnection, args);
              return createProxyStatement((Statement) cstmt);
            } else {
              cstmt = scache.checkoutStatement(physicalConnection, m, args);
              return createProxyStatement(true, (Statement) cstmt);
            }
          } else if (mname.equals("getMetaData")) {
            ensureOkay();
            txn_known_resolved = false; // views of tables etc. might be txn dependent

            DatabaseMetaData innerMd = activeConnection.getMetaData();
            if (metaData == null) {
              // exposedProxy is protected by C3P0PooledConnection.this' lock
              synchronized (C3P0PooledConnection.this) {
                metaData =
                    new SetManagedDatabaseMetaData(innerMd, activeMetaDataResultSets, exposedProxy);
              }
            }
            return metaData;
          } else if (mname.equals("silentClose")) {
            // the PooledConnection doesn't have to be okay

            doSilentClose(proxy, ((Boolean) args[0]).booleanValue(), this.txn_known_resolved);
            return null;
          } else if (mname.equals("close")) {
            // the PooledConnection doesn't have to be okay

            Exception e = doSilentClose(proxy, false, this.txn_known_resolved);
            if (!connection_error_signaled) ces.fireConnectionClosed();
            // System.err.println("close() called on a ProxyConnection.");
            if (e != null) {
              // 					    System.err.print("user close exception -- ");
              // 					    e.printStackTrace();
              throw e;
            } else return null;
          }
          // 			    else if ( mname.equals("finalize") ) //REMOVE THIS CASE -- TMP DEBUG
          // 				{
          // 				    System.err.println("Connection apparently finalized!");
          // 				    return m.invoke( activeConnection, args );
          // 				}
          else {
            ensureOkay();

            // we've disabled setting txn_known_resolved to true, ever, because
            // we failed to deal with the case that clients would work with previously
            // acquired Statements and ResultSets after a commit(), rollback(), or setAutoCommit().
            // the new non-reflective proxies have been modified to deal with this case.
            // here, with soon-to-be-deprecated in "traditional reflective proxies mode"
            // we are reverting to the conservative, always-presume-you-have-to-rollback
            // policy.

            // txn_known_resolved = ( mname.equals("commit") || mname.equals( "rollback" ) ||
            // mname.equals( "setAutoCommit" ) );
            txn_known_resolved = false;

            return m.invoke(activeConnection, args);
          }
        } else {
          if (mname.equals("close") || mname.equals("silentClose")) return null;
          else if (mname.equals("isClosed")) return Boolean.TRUE;
          else {
            throw new SQLException("You can't operate on " + "a closed connection!!!");
          }
        }
      } catch (InvocationTargetException e) {
        Throwable convertMe = e.getTargetException();
        SQLException sqle = handleMaybeFatalToPooledConnection(convertMe, proxy, false);
        sqle.fillInStackTrace();
        throw sqle;
      }
    }
 public String toString() {
   return _method.toString();
 }
示例#25
0
  public static void main(String arg[]) {
    Hashtable ignoreList = new Hashtable();
    Class cl = null;
    Model model = null;
    System.out.println("Synchronizing forms with database...");
    Db.init();

    try {
      DatabaseMetaData meta = Db.getCon().getMetaData();
      String[] types = {"TABLE"};
      ResultSet rs = meta.getTables(null, null, "%", types);

      // read ignore.list
      ignoreList = AutogenerateUtil.readIgnoreList();
      // prepare directory
      File fDir = new File("../../web/WEB-INF/views/crud_form");
      if (!fDir.exists()) fDir.mkdir();
      while (rs.next()) {
        // proper file name generationm
        String className = "";
        String tableName = rs.getString("TABLE_NAME");
        className = StringUtil.toProperClassName(tableName); // space allowed...
        // tableName = tableName.toUpperCase(); //If Oracle that need uppercase tablename. In MySQL
        // in Mac OS X (and probably Linux), it mustbe case sensitive
        // open table
        String sql = "select * from " + tableName;
        PreparedStatement pstmt =
            Db.getCon()
                .prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet = pstmt.executeQuery();
        ResultSetMetaData metaColumn = resultSet.getMetaData();
        int nColoumn = metaColumn.getColumnCount();

        // get foreign keys,and stored it in hashtable
        ResultSet rsFk = meta.getImportedKeys(Db.getCon().getCatalog(), null, tableName);
        Hashtable hashFk = new Hashtable();
        System.out.println("FK Infos for table " + tableName);
        while (rsFk.next()) {
          String pkTableName = rsFk.getString("PKTABLE_NAME");
          String pkColumnName = rsFk.getString("PKCOLUMN_NAME");
          String fkColumnName = rsFk.getString("FKCOLUMN_NAME");

          int fkSequence = rsFk.getInt("KEY_SEQ");
          System.out.println(
              tableName + "." + fkColumnName + " => " + pkTableName + "." + pkColumnName);
          hashFk.put(fkColumnName, pkColumnName);
          hashFk.put(fkColumnName + "_table", pkTableName);
        }
        rsFk.close();

        // create form page
        System.out.println(
            "Creating form page for "
                + tableName
                + " from table + "
                + application.config.Database.DB
                + "."
                + tableName);
        fDir = new File("../../web/WEB-INF/views/" + tableName);
        if (!fDir.exists()) fDir.mkdir();
        File f = new File("../../web/WEB-INF/views/" + tableName + "/form_" + tableName + ".jsp");
        if (ignoreList.get("form_" + tableName + ".jsp") != null) {
          Logger.getLogger(GenerateForm.class.getName())
              .log(Level.INFO, "Ignoring creation of form_" + tableName + ".jsp");
        } else {
          Writer out = new FileWriter(f);
          out.write(
              "<%@ page contentType=\"text/html; charset=UTF-8\" language=\"java\" import=\"java.sql.*,recite18th.library.Db,application.config.Config,recite18th.library.Pagination\" %>");
          out.write("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n");
          out.write("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\" %>\n");

          // create model for this class, use in detecting its PK Field
          cl = Class.forName("application.models." + className + "Model");
          model = (Model) cl.newInstance();

          // iterate all columns
          resultSet.beforeFirst();
          resultSet.next();
          out.write(
              "<table border=\"1\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" bordercolor=\"#E8EDFF\">\n");
          out.write("<tr>\n");
          out.write("<td>\n");
          out.write(
              "<form action=\"<%=Config.base_url%>index/"
                  + className
                  + "/save\" method=\"post\" enctype=\"multipart/form-data\">\n"); // I hope it's
          // okay to
          // default it to
          // multipart data
          out.write("<table id=\"hor-zebra\" summary=\"Form " + className + "\">\n");
          out.write("<thead>\n");
          out.write("<tr>\n");
          out.write("<th colspan=\"2\" class=\"odd\" scope=\"col\">Form " + className + " </th>\n");
          out.write("</tr>\n");
          out.write("</thead>\n");
          out.write("<tbody>\n");

          for (int i = 1; i <= nColoumn; i++) {
            String columnName = metaColumn.getColumnName(i);
            String dataType = metaColumn.getColumnClassName(i);
            out.write("<tr>\n");

            // if(!columnName.equals(model.getPkFieldName())) // implementing the case of PK not
            // AutoIncrement
            // if(!metaColumn.isAutoIncrement(i))
            // {
            // varying field input for type

            // foreign field, as chooser page view
            if (hashFk.get(columnName)
                != null) // TODO: what if PK is chooser also?? :) CUrrently I add it manually the
            // hidden_*Pk_nama* field
            {
              String fkTableName = hashFk.get(columnName + "_table") + "";
              String fkColumnName = hashFk.get(columnName) + "";
              String fkController = StringUtil.toProperClassName(fkTableName);

              out.write("<td>" + columnName + "</td>\n");
              out.write("<td>\n");
              out.write(
                  "<input name=\""
                      + columnName
                      + "\" type=\"hidden\" id=\""
                      + columnName
                      + "\" value=\"${model."
                      + columnName
                      + "}\"/>\n");
              out.write(
                  "<input name=\"label_"
                      + columnName
                      + "\" readonly=\"true\" type=\"text\" id=\"label_"
                      + columnName
                      + "\" value=\"${model."
                      + columnName
                      + "}\"/>\n"); // TODO : translate I
              out.write(
                  "<a href=\"<%=Config.base_url%>index/"
                      + fkController
                      + "/chooseView?height=220&width=700\" class=\"thickbox\">Pilih</a>");
              out.write("</td>\n");
            } else {

              // regular field input, not foreign key case
              if (!columnName.equals(model.getPkFieldName())) {
                out.write("<td>" + columnName + "</td>\n");
                out.write("<td>\n");

                // ENUM Column, displayed as HTML SELECT. May will only work for mysql only...
                Logger.getLogger(GenerateForm.class.getName())
                    .log(Level.INFO, columnName + " type is " + metaColumn.getColumnType(i));
                if (metaColumn.getColumnType(i) == 1) {
                  String enum_content[][] =
                      Db.getDataSet(
                          "SELECT SUBSTRING(COLUMN_TYPE,6,length(SUBSTRING(COLUMN_TYPE,6))-1) as enum_content "
                              + " FROM information_schema.COLUMNS "
                              + " WHERE TABLE_NAME='"
                              + tableName
                              + "' "
                              + " AND COLUMN_NAME='"
                              + columnName
                              + "'");
                  if (enum_content.length > 0) {
                    // Logger.getLogger(Model.class.getName()).log(Level.INFO, "Enum Content = " +
                    // enum_content[0][0]);
                    String enum_list[] = enum_content[0][0].split(",");
                    out.write("<select name=\"" + columnName + "\" id=\"" + columnName + "\">\n");
                    for (int ienum_list = 0; ienum_list < enum_list.length; ienum_list++)
                      out.write(
                          "\t<option <c:if test=\"${model."
                              + columnName
                              + "=='"
                              + enum_list[ienum_list].substring(
                                  1, enum_list[ienum_list].length() - 1)
                              + "'}\"> selected=\"selected\" </c:if> value=\""
                              + enum_list[ienum_list].substring(
                                  1, enum_list[ienum_list].length() - 1)
                              + "\">"
                              + enum_list[ienum_list].substring(
                                  1, enum_list[ienum_list].length() - 1)
                              + "</option>\n");
                    out.write("</select>\n\n");

                  } else {
                    // no enum content detected.. :)
                    out.write(
                        "<input name=\""
                            + columnName
                            + "\" type=\"text\" id=\""
                            + columnName
                            + "\" value=\"${model."
                            + columnName
                            + "}\"/>\n");
                  }
                } else if (metaColumn.getColumnType(i) == 91) {
                  out.write(
                      "<input name=\""
                          + columnName
                          + "\" type=\"text\" id=\""
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                  out.write("<script>\n");
                  out.write(
                      " if(!isValidDate($('#"
                          + columnName
                          + "').val())) $('#"
                          + columnName
                          + "').val('1980-1-1');\n"); // TODO: default value
                  out.write("  (function($){\n");

                  out.write("  $('#" + columnName + "').click(function() {\n");
                  out.write("    $('#" + columnName + "').DatePickerShow();\n");
                  out.write("  });\n");

                  out.write("  $('#" + columnName + "').DatePicker({\n");
                  out.write("    format:'Y-m-d',\n");
                  out.write("    date: $('#" + columnName + "').val(),\n");
                  out.write("    current: $('#" + columnName + "').val(),\n");
                  out.write("    starts: 1,\n");
                  out.write("    position: 'r',\n");

                  out.write("    onBeforeShow: function(){\n");
                  out.write(
                      "      $('#"
                          + columnName
                          + "').DatePickerSetDate($('#"
                          + columnName
                          + "').val(), true);\n");
                  out.write("    },\n");

                  out.write("    onChange: function(formated, dates){\n");
                  out.write("      $('#" + columnName + "').DatePickerHide();\n");
                  out.write("      $('#" + columnName + "').val(formated);\n");
                  out.write("    }\n");
                  out.write("  });\n");
                  out.write("  })(jQuery)\n");
                  out.write(" </script>\n");
                } else {
                  out.write(
                      "<input name=\""
                          + columnName
                          + "\" type=\"text\" id=\""
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                  out.write("${" + columnName + "_error}\n"); // regular input field
                }
              } else { // PK case
                if (metaColumn.isAutoIncrement(i)) {
                  out.write(
                      "<input name=\"hidden_"
                          + columnName
                          + "\" type=\"hidden\" id=\"hidden_"
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                } else {
                  out.write("<td>" + columnName + "</td>\n");
                  out.write("<td>\n");

                  out.write(
                      "<input name=\""
                          + columnName
                          + "\" type=\"text\" id=\""
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                  out.write("${" + columnName + "_error}\n");
                  out.write(
                      "<input name=\"hidden_"
                          + columnName
                          + "\" type=\"hidden\" id=\"hidden_"
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                }
              }
              out.write("</td>\n");
            }
            out.write("</tr>\n");
          }
          out.write("<tr class=\"odd\">\n");
          out.write("<td>&nbsp;</td>\n");
          out.write("<td><input type=\"submit\" name=\"Submit\" value=\"Simpan\">");
          out.write(
              "<input name=\"Button\" type=\"button\" id=\"Submit\" value=\"Batal\" onClick=\"javascript:history.back(-1);\"></td>\n");
          out.write("</tr>\n");
          out.write("</tbody>\n");
          out.write("</table>\n");
          out.write("</form></td>\n");
          out.write("</tr>\n");
          out.write("</table>\n");
          out.flush();
          out.close();
        }

        // create viewPage
        if (ignoreList.get("view_" + tableName + ".jsp") != null) {
          Logger.getLogger(GenerateForm.class.getName())
              .log(Level.INFO, "Ignoring creation of view_" + tableName + ".jsp");
        } else {
          System.out.println("Creating view page " + tableName);

          fDir = new File("../../web/WEB-INF/views/" + tableName);
          if (!fDir.exists()) fDir.mkdir();
          File fView =
              new File("../../web/WEB-INF/views/" + tableName + "/view_" + tableName + ".jsp");
          Writer outView = new FileWriter(fView);
          outView.write(
              "<%@ page contentType=\"text/html; charset=UTF-8\" language=\"java\" import=\"java.sql.*,recite18th.library.Db,application.config.Config,recite18th.library.Pagination\" %>");
          outView.write("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n");
          outView.write(
              "<%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\" %>\n");
          outView.write("<% int pagenum = 0; %>\n");
          // outView.write("<%@ include file=\"/WEB-INF/views/header.jsp\" %>");
          outView.write(
              "<a href=\"<%=Config.base_url%>index/" + className + "/input/-1\">Tambah Data</a>\n");
          outView.write(
              "|| <a href=\"<%=Config.base_url%>index/" + className + "/print\">Cetak</a>\n");
          outView.write("<table width=\"100%\" id=\"rounded-corner\">\n");
          outView.write("<thead>\n");
          // iterate all columns : table header
          outView.write("  <tr>\n");
          outView.write("  <th scope=\"col\" class=\"rounded-company\">No.</th>\n");
          resultSet.beforeFirst();
          resultSet.next();

          // get Primary Key Field Name : often use
          String pkFieldName = "";
          try {
            Class params[] = null;
            Method objMethod = cl.getMethod("getPkFieldName", params);
            pkFieldName = "" + objMethod.invoke(model);
          } catch (Exception ex) {
            Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
          }

          // ALL Lower Case
          pkFieldName = pkFieldName.toLowerCase();

          // customize column view page
          for (int i = 1; i <= nColoumn; i++) {
            String columnName =
                metaColumn.getColumnName(i).toLowerCase(); // Caution : ALL LowerCase
            String dataType = metaColumn.getColumnClassName(i);
            String thClass = "rounded-q1";
            String thTitle = StringUtil.toProperFieldTitle(columnName);

            if (TableCustomization.getTable(tableName)
                != null) // there is customization for this table
            {
              if (TableCustomization.getTable(tableName).get(columnName) != null) {
                thTitle = TableCustomization.getTable(tableName).get(columnName) + "";
                outView.write(
                    "  <th scope=\"col\" class=\"" + thClass + "\">" + thTitle + "</th>\n");
              }
            } else { // standard view for this table : hide PK, because mostly is auto increment
              if (!metaColumn.isAutoIncrement(i))
                outView.write(
                    "  <th scope=\"col\" class=\"" + thClass + "\">" + thTitle + "</th>\n");
            }
          }

          outView.write("  <th scope=\"col\" class=\"rounded-q4\">Aksi</th>\n");
          outView.write("  </tr>\n");
          outView.write("</thead>\n");
          outView.write("<tfoot>\n");
          outView.write("  <tr>\n");
          outView.write(
              "    <td colspan=\""
                  + (nColoumn + 1)
                  + "\" class=\"rounded-foot-left\"><%=Pagination.createLinks(pagenum)%></td>\n");
          outView.write("    <td class=\"rounded-foot-right\">&nbsp;</td>\n");
          outView.write("  </tr>\n");
          outView.write("</tfoot>\n");

          outView.write("<tbody>\n");
          outView.write("  <c:forEach items=\"${row}\" var=\"item\" varStatus=\"status\" >\n");
          outView.write("    <tr>\n");
          outView.write("      <td>${status.count}</td>\n");

          // iterate all columns : table data
          resultSet.beforeFirst();
          resultSet.next();
          for (int i = 1; i <= nColoumn; i++) {
            String columnName = metaColumn.getColumnName(i);
            // if(!columnName.equals(pkFieldName)) //TOFIX : currently, PK Field is not shown
            if (TableCustomization.getTable(tableName) != null) {
              if (TableCustomization.getTable(tableName).get(columnName) != null) {
                outView.write("      <td>${item." + columnName + "}</td>\n");
              }
            } else {
              if (!metaColumn.isAutoIncrement(i))
                outView.write("      <td>${item." + columnName + "}</td>\n");
            }
          }

          outView.write("      <td>\n");
          outView.write(
              "         <a href=\"<%=Config.base_url%>index/"
                  + className
                  + "/input/${item."
                  + pkFieldName
                  + "}\">Ubah</a>\n");
          outView.write(
              "         <a href=\"<%=Config.base_url%>index/"
                  + className
                  + "/delete/${item."
                  + pkFieldName
                  + "}\" onClick=\"return confirm('Apakah Anda yakin?');\">Hapus</a>\n");
          outView.write("      </td>\n");

          outView.write("    </tr>\n");
          outView.write("  </c:forEach>\n");
          outView.write("</tbody>\n");
          outView.write("</table>\n");
          // outView.write("<%@ include file=\"/WEB-INF/views/footer.jsp\" %>");
          outView.flush();
          outView.close();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#26
0
    protected void generateDelegateCode(
        Class intfcl, String genclass, Method method, IndentedWriter iw) throws IOException {
      String mname = method.getName();
      if (jdbc4WrapperMethod(mname)) {
        generateWrapperDelegateCode(intfcl, genclass, method, iw);
        return;
      }

      if (mname.equals("createStatement")) {
        iw.println("txn_known_resolved = false;");
        iw.println();
        iw.println("Statement innerStmt = inner." + CodegenUtils.methodCall(method) + ";");
        iw.println("parentPooledConnection.markActiveUncachedStatement( innerStmt );");
        iw.println(
            "return new NewProxyStatement( innerStmt, parentPooledConnection, false, this );");
      } else if (mname.equals("prepareStatement")) {
        iw.println("txn_known_resolved = false;");
        iw.println();
        iw.println("PreparedStatement innerStmt;");
        iw.println();
        iw.println("if ( parentPooledConnection.isStatementCaching() )");
        iw.println("{");
        iw.upIndent();

        iw.println("try");
        iw.println("{");
        iw.upIndent();

        generateFindMethodAndArgs(method, iw);
        iw.println(
            "innerStmt = (PreparedStatement) parentPooledConnection.checkoutStatement( method, args );");
        iw.println(
            "return new NewProxyPreparedStatement( innerStmt, parentPooledConnection, true, this );");

        iw.downIndent();
        iw.println("}");
        iw.println("catch (ResourceClosedException e)");
        iw.println("{");
        iw.upIndent();

        iw.println("if ( logger.isLoggable( MLevel.FINE ) )");
        iw.upIndent();
        iw.println(
            "logger.log( MLevel.FINE, "
                + "\042A Connection tried to prepare a Statement via a Statement cache that is already closed. "
                + "This can happen -- rarely -- if a DataSource is closed or reset() while Connections are checked-out and in use.\042, e );");
        iw.downIndent();

        // repeated code... any changes probably need to be duplicated below
        iw.println("innerStmt = inner." + CodegenUtils.methodCall(method) + ";");
        iw.println("parentPooledConnection.markActiveUncachedStatement( innerStmt );");
        iw.println(
            "return new NewProxyPreparedStatement( innerStmt, parentPooledConnection, false, this );");

        iw.downIndent();
        iw.println("}");

        iw.downIndent();
        iw.println("}");
        iw.println("else");
        iw.println("{");
        iw.upIndent();

        // repeated code... any changes probably need to be duplicated above
        iw.println("innerStmt = inner." + CodegenUtils.methodCall(method) + ";");
        iw.println("parentPooledConnection.markActiveUncachedStatement( innerStmt );");
        iw.println(
            "return new NewProxyPreparedStatement( innerStmt, parentPooledConnection, false, this );");

        iw.downIndent();
        iw.println("}");

      } else if (mname.equals("prepareCall")) {
        iw.println("txn_known_resolved = false;");
        iw.println();
        iw.println("CallableStatement innerStmt;");
        iw.println();
        iw.println("if ( parentPooledConnection.isStatementCaching() )");
        iw.println("{");
        iw.upIndent();

        iw.println("try");
        iw.println("{");
        iw.upIndent();

        generateFindMethodAndArgs(method, iw);
        iw.println(
            "innerStmt = (CallableStatement) parentPooledConnection.checkoutStatement( method, args );");
        iw.println(
            "return new NewProxyCallableStatement( innerStmt, parentPooledConnection, true, this );");

        iw.downIndent();
        iw.println("}");
        iw.println("catch (ResourceClosedException e)");
        iw.println("{");
        iw.upIndent();

        iw.println("if ( logger.isLoggable( MLevel.FINE ) )");
        iw.upIndent();
        iw.println(
            "logger.log( MLevel.FINE, "
                + "\042A Connection tried to prepare a CallableStatement via a Statement cache that is already closed. "
                + "This can happen -- rarely -- if a DataSource is closed or reset() while Connections are checked-out and in use.\042, e );");
        iw.downIndent();

        // repeated code... any changes probably need to be duplicated below
        iw.println("innerStmt = inner." + CodegenUtils.methodCall(method) + ";");
        iw.println("parentPooledConnection.markActiveUncachedStatement( innerStmt );");
        iw.println(
            "return new NewProxyCallableStatement( innerStmt, parentPooledConnection, false, this );");

        iw.downIndent();
        iw.println("}");

        iw.downIndent();
        iw.println("}");
        iw.println("else");
        iw.println("{");
        iw.upIndent();

        // repeated code... any changes probably need to be duplicated above
        iw.println("innerStmt = inner." + CodegenUtils.methodCall(method) + ";");
        iw.println("parentPooledConnection.markActiveUncachedStatement( innerStmt );");
        iw.println(
            "return new NewProxyCallableStatement( innerStmt, parentPooledConnection, false, this );");

        iw.downIndent();
        iw.println("}");

      } else if (mname.equals("getMetaData")) {
        iw.println("txn_known_resolved = false;");
        iw.println();
        iw.println("if (this.metaData == null)");
        iw.println("{");
        iw.upIndent();
        iw.println(
            "DatabaseMetaData innerMetaData = inner." + CodegenUtils.methodCall(method) + ";");
        iw.println(
            "this.metaData = new NewProxyDatabaseMetaData( innerMetaData, parentPooledConnection, this );");
        iw.downIndent();
        iw.println("}");
        iw.println("return this.metaData;");
      } else if (mname.equals("setTransactionIsolation")) {
        // do nothing with txn_known_resolved

        super.generateDelegateCode(intfcl, genclass, method, iw);
        iw.println(
            "parentPooledConnection.markNewTxnIsolation( "
                + CodegenUtils.generatedArgumentName(0)
                + " );");
      } else if (mname.equals("setCatalog")) {
        // do nothing with txn_known_resolved

        super.generateDelegateCode(intfcl, genclass, method, iw);
        iw.println(
            "parentPooledConnection.markNewCatalog( "
                + CodegenUtils.generatedArgumentName(0)
                + " );");
      } else if (mname.equals("setHoldability")) {
        // do nothing with txn_known_resolved

        super.generateDelegateCode(intfcl, genclass, method, iw);
        iw.println(
            "parentPooledConnection.markNewHoldability( "
                + CodegenUtils.generatedArgumentName(0)
                + " );");
      } else if (mname.equals("setReadOnly")) {
        // do nothing with txn_known_resolved

        super.generateDelegateCode(intfcl, genclass, method, iw);
        iw.println(
            "parentPooledConnection.markNewReadOnly( "
                + CodegenUtils.generatedArgumentName(0)
                + " );");
      } else if (mname.equals("setTypeMap")) {
        // do nothing with txn_known_resolved

        super.generateDelegateCode(intfcl, genclass, method, iw);
        iw.println(
            "parentPooledConnection.markNewTypeMap( "
                + CodegenUtils.generatedArgumentName(0)
                + " );");
      } else if (mname.equals("getWarnings") || mname.equals("clearWarnings")) {
        // do nothing with txn_known_resolved

        super.generateDelegateCode(intfcl, genclass, method, iw);
      } else if (mname.equals("close")) {
        iw.println("if (! this.isDetached())");
        iw.println("{");
        iw.upIndent();
        iw.println("NewPooledConnection npc = parentPooledConnection;");
        iw.println("this.detach();");
        iw.println("npc.markClosedProxyConnection( this, txn_known_resolved );");
        iw.println("this.inner = null;");
        iw.downIndent();
        iw.println("}");
        iw.println("else if (Debug.DEBUG && logger.isLoggable( MLevel.FINE ))");
        iw.println("{");
        iw.upIndent();
        iw.println("logger.log( MLevel.FINE, this + \042: close() called more than once.\042 );");

        // premature-detach-debug-debug only!
        if (PREMATURE_DETACH_DEBUG) {
          iw.println("prematureDetachRecorder.record();");
          iw.println(
              "logger.warning( prematureDetachRecorder.getDump(\042Apparent multiple close of "
                  + getInnerTypeName()
                  + ".\042) );");
        }
        // end-premature-detach-debug-only!

        iw.downIndent();
        iw.println("}");
      } else if (mname.equals("isClosed")) {
        iw.println("return this.isDetached();");
      } else if (mname.equals("isValid")) {
        iw.println("if (this.isDetached()) return false;");

        super.generateDelegateCode(intfcl, genclass, method, iw);
      } else {
        boolean known_resolved =
            (mname.equals("commit") || mname.equals("rollback") || mname.equals("setAutoCommit"));

        if (!known_resolved) {
          iw.println("txn_known_resolved = false;");
          iw.println();
        }
        super.generateDelegateCode(intfcl, genclass, method, iw);
        if (known_resolved) {
          iw.println();
          iw.println("txn_known_resolved = true;");
        }
      }
    }
示例#27
0
  /**
   * Getting all the alerts in the NMS Alert table and using the alerts, forming the array of
   * CompositeData.Using the CompositeData forming the TabularData and returning the TabularData
   */
  TabularData getTable() {

    if (!agentName.initAlert()) return null;

    TabularData td = null;

    OpenMBeanParameterInfo[] parameterInfo = new OpenMBeanParameterInfo[names.length];

    String returnType = null;
    try {

      Class entryClassName = Class.forName(instrClassName);

      for (int i = 0; i < names.length; i++) {

        String methodName = "get" + names[i]; // No I18N

        Method method = entryClassName.getMethod(methodName, null);

        returnType = method.getReturnType().getName();

        parameterInfo[i] = new OpenMBeanParameterInfo(names[i], returnType, null, null, null);
      }
    } catch (Exception e) {
      agentName.agentErr.fail("Exception in getTable(): ", e); // No I18N
      return null;
    }

    try {

      int numalerts = agentName.alertAPI.getTotalAlertCount();

      CompositeData[] comps = new CompositeData[numalerts];

      int count = 0;

      Alert alert = null;

      String entity = ""; // No I18N

      String ownerName = ""; // No I18N

      while (true) {

        if (alert == null) {
          try {
            /**
             * getting the oldest/first alert in the database which has the least recent mod time
             */
            alert = agentName.alertAPI.getOldestModifiedAlert();
          } catch (Exception e) {
            agentName.agentErr.fail("exception ", e); // No I18N
          }
        } else {
          try {
            entity = alert.getEntity();

            ownerName = alert.getOwnerName();

            /** getting the next alert from the database using the modified time as criteria */
            if (ownerName != null)
              alert =
                  agentName.alertAPI.getNextAlertBasedOnModtime(
                      entity + "\t" + ownerName); // No I18N
            else alert = agentName.alertAPI.getNextAlertBasedOnModtime(entity);
          } catch (Exception e) {
            agentName.agentErr.fail("exception", e); // No I18N
          }
        }

        if (alert == null) break;

        comps[count++] = makeComData(alert);

        if (count == numalerts) break;
      } // end of while

      TabularParameterInfo tinfo =
          new TabularParameterInfo(null, null, null, null, null, parameterInfo, indexNames);

      td = new TabularData(tinfo, comps);
    } catch (Exception e) {
      agentName.agentErr.fail(" Exception in getTable(): ", e); // No I18N
    }

    return td;
  } // end of getTable