/** Creates a Pooled connection and adds it to the connection pool. */
  private void installConnection() throws EmanagerDatabaseException {
    logger.debug("enter");

    PooledConnection connection;

    try {
      connection = poolDataSource.getPooledConnection();
      connection.addConnectionEventListener(this);
      connection.getConnection().setAutoCommit(false);
      synchronized (connectionPool) {
        connectionPool.add(connection);
        logger.debug("Database connection added.");
      }
    } catch (SQLException ex) {
      logger.fatal("exception caught while obtaining database " + "connection: ex = " + ex);
      SQLException ex1 = ex.getNextException();
      while (ex1 != null) {
        logger.fatal("chained sql exception ex1 = " + ex1);
        SQLException nextEx = ex1.getNextException();
        ex1 = nextEx;
      }
      String logString;
      EmanagerDatabaseException ede;

      logString =
          EmanagerDatabaseStatusCode.DatabaseConnectionFailure.getStatusCodeDescription()
              + ex.getMessage();

      logger.fatal(logString);
      ede =
          new EmanagerDatabaseException(
              EmanagerDatabaseStatusCode.DatabaseConnectionFailure, logString);
      throw ede;
    }
  }
  /**
   * @param arg0
   * @roseuid 3F4E5F400123
   */
  public void connectionClosed(ConnectionEvent event) {
    logger.debug("Enter: " + event.getSource());

    synchronized (connectionPool) {
      if (!SHUTTING_DOWN) {
        if (connectionPool.size() < connectionPoolSize) {
          logger.debug("Reading Connection: " + event.getSource());

          connectionPool.add(event.getSource());
        }
      }
    }
  }
예제 #3
0
  private PGStream enableSSL(PGStream pgStream, boolean requireSSL, Properties info, Logger logger)
      throws IOException, SQLException {
    if (logger.logDebug()) logger.debug(" FE=> SSLRequest");

    // Send SSL request packet
    pgStream.SendInteger4(8);
    pgStream.SendInteger2(1234);
    pgStream.SendInteger2(5679);
    pgStream.flush();

    // Now get the response from the backend, one of N, E, S.
    int beresp = pgStream.ReceiveChar();
    switch (beresp) {
      case 'E':
        if (logger.logDebug()) logger.debug(" <=BE SSLError");

        // Server doesn't even know about the SSL handshake protocol
        if (requireSSL)
          throw new PSQLException(
              GT.tr("The server does not support SSL."), PSQLState.CONNECTION_FAILURE);

        // We have to reconnect to continue.
        pgStream.close();
        return new PGStream(pgStream.getHost(), pgStream.getPort());

      case 'N':
        if (logger.logDebug()) logger.debug(" <=BE SSLRefused");

        // Server does not support ssl
        if (requireSSL)
          throw new PSQLException(
              GT.tr("The server does not support SSL."), PSQLState.CONNECTION_FAILURE);

        return pgStream;

      case 'S':
        if (logger.logDebug()) logger.debug(" <=BE SSLOk");

        // Server supports ssl
        Driver.makeSSL(pgStream, info, logger);
        return pgStream;

      default:
        throw new PSQLException(
            GT.tr("An error occured while setting up the SSL connection."),
            PSQLState.CONNECTION_FAILURE);
    }
  }
예제 #4
0
 /**
  * 采用批方式插入多条数据
  *
  * @param collection collection
  * @throws Exception
  */
 public void insertAll(Collection collection) throws Exception {
   StringBuffer buffer = new StringBuffer(200);
   buffer.append("INSERT INTO LineLoss (");
   buffer.append("LineCode,");
   buffer.append("R,");
   buffer.append("LineLong,");
   buffer.append("Volt,");
   buffer.append("T,");
   buffer.append("ValidStatus,");
   buffer.append("Flag,");
   buffer.append("Remark ");
   buffer.append(") ");
   buffer.append("VALUES(?,?,?,?,?,?,?,?)");
   if (logger.isDebugEnabled()) {
     logger.debug(buffer.toString());
   }
   dbManager.prepareStatement(buffer.toString());
   for (Iterator i = collection.iterator(); i.hasNext(); ) {
     LineLossDto lineLossDto = (LineLossDto) i.next();
     dbManager.setString(1, lineLossDto.getLineCode());
     dbManager.setDouble(2, lineLossDto.getR());
     dbManager.setDouble(3, lineLossDto.getLineLong());
     dbManager.setDouble(4, lineLossDto.getVolt());
     dbManager.setDouble(5, lineLossDto.getT());
     dbManager.setString(6, lineLossDto.getValidStatus());
     dbManager.setString(7, lineLossDto.getFlag());
     dbManager.setString(8, lineLossDto.getRemark());
     dbManager.addBatch();
   }
   dbManager.executePreparedUpdateBatch();
 }
예제 #5
0
 /**
  * 采用批方式插入多条数据
  *
  * @param collection collection
  * @throws Exception
  */
 public void insertAll(Collection collection) throws Exception {
   StringBuffer buffer = new StringBuffer(200);
   buffer.append("INSERT INTO LwWholeSalePrice (");
   buffer.append("PowerClass,");
   buffer.append("SaleArea,");
   buffer.append("VoltageBegin,");
   buffer.append("VoltageEnd,");
   buffer.append("Price,");
   buffer.append("ValidStatus,");
   buffer.append("Flag,");
   buffer.append("Remark ");
   buffer.append(") ");
   buffer.append("VALUES(?,?,?,?,?,?,?,?)");
   if (logger.isDebugEnabled()) {
     logger.debug(buffer.toString());
   }
   dbManager.prepareStatement(buffer.toString());
   for (Iterator i = collection.iterator(); i.hasNext(); ) {
     LwWholeSalePriceDto lwWholeSalePriceDto = (LwWholeSalePriceDto) i.next();
     dbManager.setString(1, lwWholeSalePriceDto.getPowerClass());
     dbManager.setString(2, lwWholeSalePriceDto.getSaleArea());
     dbManager.setDouble(3, lwWholeSalePriceDto.getVoltageBegin());
     dbManager.setDouble(4, lwWholeSalePriceDto.getVoltageEnd());
     dbManager.setDouble(5, lwWholeSalePriceDto.getPrice());
     dbManager.setString(6, lwWholeSalePriceDto.getValidStatus());
     dbManager.setString(7, lwWholeSalePriceDto.getFlag());
     dbManager.setString(8, lwWholeSalePriceDto.getRemark());
     dbManager.addBatch();
   }
   dbManager.executePreparedUpdateBatch();
 }
  private void initializeDatabaseContext() throws EmanagerDatabaseException {
    logger.debug("Enter");

    Properties properties;
    SybConnectionPoolDataSource poolDataSource;

    properties = new Properties();
    poolDataSource = new com.sybase.jdbc2.jdbc.SybConnectionPoolDataSource();

    poolDataSource.setUser(userAccount);
    poolDataSource.setPassword(password);
    poolDataSource.setDatabaseName(databaseName);
    poolDataSource.setServerName(databaseHost);
    poolDataSource.setPortNumber(connectionPort);
    poolDataSource.setDescription(connectionPoolDescription);

    properties.put("user", userAccount);
    properties.put("password", password);
    properties.put("APPLICATIONNAME", clientAppName);
    // fix
    // hopefully these have defaults
    // properties.put("USE_METADATA", userMetaData);
    // properties.put("REPEAT_READ", useRepeatRead);
    // properties.put("CHARSET_CONVERTER_CLASS", charsetConverter);

    properties.put("server", "jdbc:sybase:Tds:" + databaseHost + ":" + connectionPort);

    try {
      poolDataSource.setConnectionProperties(properties);
      // jndiContext.bind("jdbc/protoDB", poolDataSource);
      jndiContext.bind(JNDIContextName, poolDataSource);
    } catch (Exception ex) {
      String logString;
      EmanagerDatabaseException ede;

      logString =
          EmanagerDatabaseStatusCode.UnableToBindJNDIContext.getStatusCodeDescription()
              + ex.getMessage();

      logger.fatal(logString);
      ede =
          new EmanagerDatabaseException(
              EmanagerDatabaseStatusCode.UnableToBindJNDIContext, logString);
      throw ede;
    }
  }
  /**
   * @param arg0
   * @roseuid 3F4E5F40012D
   */
  public void connectionErrorOccurred(ConnectionEvent event) {
    logger.debug("Connection Error " + event.getSQLException().getMessage());

    synchronized (connectionPool) {
      if (connectionPool.size() <= connectionPoolSize) {
        connectionPool.remove(event.getSource());
        if (!SHUTTING_DOWN) {
          try {
            installConnection();
          } catch (EmanagerDatabaseException e) {
            // noop.  can't throw an exception here, so we'll ignore.
            // It will surface later.
          }
        }
      }
    }
  }
예제 #8
0
 @Override
 public CloseableIterator<JdbcEntry> getSubCursor(String identifier) {
   if (isSub) {
     log.debug("Using getSubCursor for " + identifier);
     return getSqlCursor(getSql(identifier));
   } else {
     return getSqlCursor(getFindSql(identifier));
   }
 }
 /**
  * 按条件删除数据
  *
  * @param conditions 查询条件
  * @return 删除的行数
  * @throws Exception
  */
 public int deleteByConditions(String conditions) throws Exception {
   StringBuffer buffer = new StringBuffer(100);
   buffer.append("DELETE FROM LwWholeSaleSummary WHERE ");
   buffer.append(conditions);
   if (logger.isDebugEnabled()) {
     logger.debug(buffer.toString());
   }
   int count = dbManager.executeUpdate(buffer.toString());
   return count;
 }
  /** @roseuid 3F3A89D40175 */
  public void shutdown() {
    logger.debug("Enter");

    Iterator iter;
    PooledConnection pooledConnection;

    SHUTTING_DOWN = true;
    iter = connectionPool.iterator();
    while (iter.hasNext()) {
      pooledConnection = (PooledConnection) iter.next();

      try {
        if (!pooledConnection.getConnection().isClosed()) {
          pooledConnection.getConnection().close();
        }
      } catch (Exception ex) {
        // We don't care what happens here, we're on the way out!
      }
    }

    connectionPool.clear();
  }
예제 #11
0
 /**
  * 查询满足模糊查询条件的记录数
  *
  * @param conditions conditions
  * @return 满足模糊查询条件的记录数
  * @throws Exception
  */
 public int getCount(String conditions) throws Exception {
   int count = -1;
   StringBuffer buffer = new StringBuffer(100);
   buffer.append("SELECT count(*) FROM LwWholeSaleSummary WHERE ");
   buffer.append(conditions);
   if (logger.isDebugEnabled()) {
     logger.debug(buffer.toString());
   }
   ResultSet resultSet = dbManager.executeQuery(buffer.toString());
   resultSet.next();
   count = dbManager.getInt(resultSet, 1);
   resultSet.close();
   return count;
 }
예제 #12
0
  /**
   * 按主键更新一条数据(主键本身无法变更)
   *
   * @param lwWholeSalePriceDto lwWholeSalePriceDto
   * @throws Exception
   */
  public void update(LwWholeSalePriceDto lwWholeSalePriceDto) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    buffer.append("UPDATE LwWholeSalePrice SET ");
    buffer.append("PowerClass = ?, ");
    buffer.append("VoltageEnd = ?, ");
    buffer.append("Price = ?, ");
    buffer.append("ValidStatus = ?, ");
    buffer.append("Flag = ?, ");
    buffer.append("Remark = ? ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append("UPDATE LwWholeSalePrice SET ");
      debugBuffer.append("PowerClass = '" + lwWholeSalePriceDto.getPowerClass() + "', ");
      debugBuffer.append("VoltageEnd = " + lwWholeSalePriceDto.getVoltageEnd() + ", ");
      debugBuffer.append("Price = " + lwWholeSalePriceDto.getPrice() + ", ");
      debugBuffer.append("ValidStatus = '" + lwWholeSalePriceDto.getValidStatus() + "', ");
      debugBuffer.append("Flag = '" + lwWholeSalePriceDto.getFlag() + "', ");
      debugBuffer.append("Remark = '" + lwWholeSalePriceDto.getRemark() + "' ");
      debugBuffer.append("WHERE ");
      debugBuffer
          .append("SaleArea=")
          .append("'")
          .append(lwWholeSalePriceDto.getSaleArea())
          .append("' AND ");
      debugBuffer
          .append("VoltageBegin=")
          .append("")
          .append(lwWholeSalePriceDto.getVoltageBegin())
          .append("");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("WHERE ");
    buffer.append("SaleArea = ? And ");
    buffer.append("VoltageBegin = ?");

    dbManager.prepareStatement(buffer.toString());
    // 设置更新字段;
    dbManager.setString(1, lwWholeSalePriceDto.getPowerClass());
    dbManager.setDouble(2, lwWholeSalePriceDto.getVoltageEnd());
    dbManager.setDouble(3, lwWholeSalePriceDto.getPrice());
    dbManager.setString(4, lwWholeSalePriceDto.getValidStatus());
    dbManager.setString(5, lwWholeSalePriceDto.getFlag());
    dbManager.setString(6, lwWholeSalePriceDto.getRemark());
    // 设置条件字段;
    dbManager.setString(7, lwWholeSalePriceDto.getSaleArea());
    dbManager.setDouble(8, lwWholeSalePriceDto.getVoltageBegin());
    dbManager.executePreparedUpdate();
  }
예제 #13
0
 protected boolean executeOnlyIf(Connection con, String q) throws SQLException {
   if (q == null) return true;
   Statement stmt = null;
   try {
     stmt = con.createStatement();
     q = q.replace("$PREFIX", getPrefix());
     LOG.debug(" Executing query " + q);
     ResultSet rs = stmt.executeQuery(q);
     rs.next();
     boolean res = rs.getBoolean(1);
     LOG.debug("Result: " + res);
     return res;
   } catch (SQLException sqe) {
     LOG.error(sqe.getMessage() + " from " + q);
     throw sqe;
   } finally {
     try {
       if (stmt != null) {
         stmt.close();
       }
     } catch (Exception g) {
     }
   }
 }
  /**
   * The constructor obtains a ConnectionPoolDataSource reference via JNDI. This datasource is used
   * when new database connections need to be established and maintained in some container (pool).
   */
  public void initializeConnectionPoolConnections() throws EmanagerDatabaseException {
    logger.debug("enter");

    try {
      poolDataSource = (ConnectionPoolDataSource) jndiContext.lookup(JNDIContextName);
    } catch (Exception ex) {
      String logString;
      EmanagerDatabaseException ede;

      logString =
          EmanagerDatabaseStatusCode.DatabaseJNDILookupFailure.getStatusCodeDescription()
              + ex.getMessage();

      logger.fatal(logString);
      ede =
          new EmanagerDatabaseException(
              EmanagerDatabaseStatusCode.DatabaseJNDILookupFailure, logString);
      throw ede;
    }

    for (int i = 0; i < connectionPoolSize; i++) {
      installConnection();
    }
  }
예제 #15
0
  /**
   * 按主键查找一条数据
   *
   * @param saleArea 趸售区域
   * @param voltageBegin 起始电压
   * @return LwWholeSalePriceDto
   * @throws Exception
   */
  public LwWholeSalePriceDto findByPrimaryKey(String saleArea, double voltageBegin)
      throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    // 拼SQL语句
    buffer.append("SELECT ");
    buffer.append("PowerClass,");
    buffer.append("SaleArea,");
    buffer.append("VoltageBegin,");
    buffer.append("VoltageEnd,");
    buffer.append("Price,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark ");
    buffer.append("FROM LwWholeSalePrice ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append(buffer.toString());
      debugBuffer.append("WHERE ");
      debugBuffer.append("SaleArea=").append("'").append(saleArea).append("' AND ");
      debugBuffer.append("VoltageBegin=").append("").append(voltageBegin).append("");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("WHERE ");
    buffer.append("SaleArea = ? And ");
    buffer.append("VoltageBegin = ?");

    dbManager.prepareStatement(buffer.toString());
    // 设置条件字段;
    dbManager.setString(1, saleArea);
    dbManager.setDouble(2, voltageBegin);
    ResultSet resultSet = dbManager.executePreparedQuery();
    LwWholeSalePriceDto lwWholeSalePriceDto = null;
    if (resultSet.next()) {
      lwWholeSalePriceDto = new LwWholeSalePriceDto();
      lwWholeSalePriceDto.setPowerClass(dbManager.getString(resultSet, 1));
      lwWholeSalePriceDto.setSaleArea(dbManager.getString(resultSet, 2));
      lwWholeSalePriceDto.setVoltageBegin(dbManager.getDouble(resultSet, 3));
      lwWholeSalePriceDto.setVoltageEnd(dbManager.getDouble(resultSet, 4));
      lwWholeSalePriceDto.setPrice(dbManager.getDouble(resultSet, 5));
      lwWholeSalePriceDto.setValidStatus(dbManager.getString(resultSet, 6));
      lwWholeSalePriceDto.setFlag(dbManager.getString(resultSet, 7));
      lwWholeSalePriceDto.setRemark(dbManager.getString(resultSet, 8));
    }
    resultSet.close();
    return lwWholeSalePriceDto;
  }
예제 #16
0
  @Override
  public org.mmbase.bridge.Node getNode(final Cloud userCloud, final Document doc) {
    String docId = doc.get("number");
    if (docId == null) {
      throw new IllegalArgumentException("No number found in " + doc);
    }
    LazyMap m = nodeCache.get(docId); //
    if (m == null) {
      Map<String, String> keys = new HashMap<String, String>();
      for (String keyWord : keyWords) {
        keys.put(keyWord, doc.get(keyWord));
      }
      m = new LazyMap(docId, keys);
      nodeCache.put(docId, m);
    }
    org.mmbase.bridge.Node node =
        new MapNode<String>(
            m,
            new MapNodeManager(userCloud, m) {
              @Override
              public boolean hasField(String name) {
                if (JdbcIndexDefinition.this.key.equals(name)) return true;
                return super.hasField(name);
              }

              @Override
              public org.mmbase.bridge.Field getField(String name) {
                if (map == null && JdbcIndexDefinition.this.key.equals(name)) {
                  org.mmbase.core.CoreField fd =
                      org.mmbase.core.util.Fields.createField(
                          name,
                          org.mmbase.core.util.Fields.classToType(Object.class),
                          org.mmbase.bridge.Field.TYPE_UNKNOWN,
                          org.mmbase.bridge.Field.STATE_VIRTUAL,
                          null);
                  return new org.mmbase.bridge.implementation.BasicField(fd, this);
                } else {
                  return super.getField(name);
                }
              }
            });
    if (log.isDebugEnabled()) {
      log.debug("Returning node for " + node);
    }
    return node;
  }
예제 #17
0
  /**
   * 按主键查找一条数据
   *
   * @param lineCode 线路名称
   * @return LineLossDto
   * @throws Exception
   */
  public LineLossDto findByPrimaryKey(String lineCode) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    // 拼SQL语句
    buffer.append("SELECT ");
    buffer.append("LineCode,");
    buffer.append("R,");
    buffer.append("LineLong,");
    buffer.append("Volt,");
    buffer.append("T,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark ");
    buffer.append("FROM LineLoss ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append(buffer.toString());
      debugBuffer.append("WHERE ");
      debugBuffer.append("LineCode=").append("'").append(lineCode).append("'");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("WHERE ");
    buffer.append("LineCode = ?");

    dbManager.prepareStatement(buffer.toString());
    // 设置条件字段;
    dbManager.setString(1, lineCode);
    ResultSet resultSet = dbManager.executePreparedQuery();
    LineLossDto lineLossDto = null;
    if (resultSet.next()) {
      lineLossDto = new LineLossDto();
      lineLossDto.setLineCode(dbManager.getString(resultSet, 1));
      lineLossDto.setR(dbManager.getDouble(resultSet, 2));
      lineLossDto.setLineLong(dbManager.getDouble(resultSet, 3));
      lineLossDto.setVolt(dbManager.getDouble(resultSet, 4));
      lineLossDto.setT(dbManager.getDouble(resultSet, 5));
      lineLossDto.setValidStatus(dbManager.getString(resultSet, 6));
      lineLossDto.setFlag(dbManager.getString(resultSet, 7));
      lineLossDto.setRemark(dbManager.getString(resultSet, 8));
    }
    resultSet.close();
    return lineLossDto;
  }
예제 #18
0
  /**
   * 按主键删除一条数据
   *
   * @param lineCode 线路名称
   * @throws Exception
   */
  public void delete(String lineCode) throws Exception {
    StringBuffer buffer = new StringBuffer(100);
    buffer.append("DELETE FROM LineLoss ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append(buffer.toString());
      debugBuffer.append("WHERE ");
      debugBuffer.append("LineCode=").append("'").append(lineCode).append("'");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("WHERE ");
    buffer.append("LineCode = ?");

    dbManager.prepareStatement(buffer.toString());
    // 设置条件字段;
    dbManager.setString(1, lineCode);
    dbManager.executePreparedUpdate();
  }
예제 #19
0
  /**
   * 按主键更新一条数据(主键本身无法变更)
   *
   * @param lineLossDto lineLossDto
   * @throws Exception
   */
  public void update(LineLossDto lineLossDto) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    buffer.append("UPDATE LineLoss SET ");
    buffer.append("R = ?, ");
    buffer.append("LineLong = ?, ");
    buffer.append("Volt = ?, ");
    buffer.append("T = ?, ");
    buffer.append("ValidStatus = ?, ");
    buffer.append("Flag = ?, ");
    buffer.append("Remark = ? ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append("UPDATE LineLoss SET ");
      debugBuffer.append("R = " + lineLossDto.getR() + ", ");
      debugBuffer.append("LineLong = " + lineLossDto.getLineLong() + ", ");
      debugBuffer.append("Volt = " + lineLossDto.getVolt() + ", ");
      debugBuffer.append("T = " + lineLossDto.getT() + ", ");
      debugBuffer.append("ValidStatus = '" + lineLossDto.getValidStatus() + "', ");
      debugBuffer.append("Flag = '" + lineLossDto.getFlag() + "', ");
      debugBuffer.append("Remark = '" + lineLossDto.getRemark() + "' ");
      debugBuffer.append("WHERE ");
      debugBuffer.append("LineCode=").append("'").append(lineLossDto.getLineCode()).append("'");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("WHERE ");
    buffer.append("LineCode = ?");

    dbManager.prepareStatement(buffer.toString());
    // 设置更新字段;
    dbManager.setDouble(1, lineLossDto.getR());
    dbManager.setDouble(2, lineLossDto.getLineLong());
    dbManager.setDouble(3, lineLossDto.getVolt());
    dbManager.setDouble(4, lineLossDto.getT());
    dbManager.setString(5, lineLossDto.getValidStatus());
    dbManager.setString(6, lineLossDto.getFlag());
    dbManager.setString(7, lineLossDto.getRemark());
    // 设置条件字段;
    dbManager.setString(8, lineLossDto.getLineCode());
    dbManager.executePreparedUpdate();
  }
예제 #20
0
 public void run() {
   Connection con = null;
   Statement stmt = null;
   try {
     DataSource ds = getDataSource();
     con = ds.getConnection();
     if (executeOnlyIf(con, onlyIfQuery)) {
       stmt = con.createStatement();
       if (query != null) {
         executeQuery(stmt, query);
       } else if (update != null) {
         executeUpdate(stmt, update);
       } else {
         throw new IllegalStateException("Both query and update properties are unset");
       }
     } else {
       LOG.debug("Skipped because of " + onlyIfQuery);
     }
   } catch (RuntimeException e) {
     throw e;
   } catch (Throwable t) {
     if (ignore.matcher(t.getMessage()).matches()) {
       LOG.info("Ignoring " + t.getMessage());
     } else {
       throw new RuntimeException(t.getMessage(), t);
     }
   } finally {
     try {
       if (stmt != null) {
         stmt.close();
       }
     } catch (Exception g) {
     }
     try {
       if (con != null) {
         con.close();
       }
     } catch (Exception g) {
     }
   }
 }
예제 #21
0
  /**
   * 按主键删除一条数据
   *
   * @param lineCode 线路代码
   * @param statMonth 统计年月
   * @throws Exception
   */
  public void delete(String lineCode, String statMonth) throws Exception {
    StringBuffer buffer = new StringBuffer(100);
    buffer.append("DELETE FROM LwWholeSaleSummary ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append(buffer.toString());
      debugBuffer.append("WHERE ");
      debugBuffer.append("LineCode=").append("'").append(lineCode).append("' AND ");
      debugBuffer.append("StatMonth=").append("'").append(statMonth).append("'");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("WHERE ");
    buffer.append("LineCode = ? And ");
    buffer.append("StatMonth = ?");

    dbManager.prepareStatement(buffer.toString());
    // 设置条件字段;
    dbManager.setString(1, lineCode);
    dbManager.setString(2, statMonth);
    dbManager.executePreparedUpdate();
  }
예제 #22
0
  /**
   * 插入一条数据
   *
   * @param lineLossDto lineLossDto
   * @throws Exception
   */
  public void insert(LineLossDto lineLossDto) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    buffer.append("INSERT INTO LineLoss (");
    buffer.append("LineCode,");
    buffer.append("R,");
    buffer.append("LineLong,");
    buffer.append("Volt,");
    buffer.append("T,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark ");
    buffer.append(") ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append(buffer.toString());
      debugBuffer.append("VALUES(");
      debugBuffer.append("'").append(lineLossDto.getLineCode()).append("',");
      debugBuffer.append("").append(lineLossDto.getR()).append(",");
      debugBuffer.append("").append(lineLossDto.getLineLong()).append(",");
      debugBuffer.append("").append(lineLossDto.getVolt()).append(",");
      debugBuffer.append("").append(lineLossDto.getT()).append(",");
      debugBuffer.append("'").append(lineLossDto.getValidStatus()).append("',");
      debugBuffer.append("'").append(lineLossDto.getFlag()).append("',");
      debugBuffer.append("'").append(lineLossDto.getRemark()).append("')");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("VALUES(?,?,?,?,?,?,?,?)");
    dbManager.prepareStatement(buffer.toString());
    dbManager.setString(1, lineLossDto.getLineCode());
    dbManager.setDouble(2, lineLossDto.getR());
    dbManager.setDouble(3, lineLossDto.getLineLong());
    dbManager.setDouble(4, lineLossDto.getVolt());
    dbManager.setDouble(5, lineLossDto.getT());
    dbManager.setString(6, lineLossDto.getValidStatus());
    dbManager.setString(7, lineLossDto.getFlag());
    dbManager.setString(8, lineLossDto.getRemark());
    dbManager.executePreparedUpdate();
  }
예제 #23
0
  /**
   * 插入一条数据
   *
   * @param lwWholeSalePriceDto lwWholeSalePriceDto
   * @throws Exception
   */
  public void insert(LwWholeSalePriceDto lwWholeSalePriceDto) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    buffer.append("INSERT INTO LwWholeSalePrice (");
    buffer.append("PowerClass,");
    buffer.append("SaleArea,");
    buffer.append("VoltageBegin,");
    buffer.append("VoltageEnd,");
    buffer.append("Price,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark ");
    buffer.append(") ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append(buffer.toString());
      debugBuffer.append("VALUES(");
      debugBuffer.append("'").append(lwWholeSalePriceDto.getPowerClass()).append("',");
      debugBuffer.append("'").append(lwWholeSalePriceDto.getSaleArea()).append("',");
      debugBuffer.append("").append(lwWholeSalePriceDto.getVoltageBegin()).append(",");
      debugBuffer.append("").append(lwWholeSalePriceDto.getVoltageEnd()).append(",");
      debugBuffer.append("").append(lwWholeSalePriceDto.getPrice()).append(",");
      debugBuffer.append("'").append(lwWholeSalePriceDto.getValidStatus()).append("',");
      debugBuffer.append("'").append(lwWholeSalePriceDto.getFlag()).append("',");
      debugBuffer.append("'").append(lwWholeSalePriceDto.getRemark()).append("')");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("VALUES(?,?,?,?,?,?,?,?)");
    dbManager.prepareStatement(buffer.toString());
    dbManager.setString(1, lwWholeSalePriceDto.getPowerClass());
    dbManager.setString(2, lwWholeSalePriceDto.getSaleArea());
    dbManager.setDouble(3, lwWholeSalePriceDto.getVoltageBegin());
    dbManager.setDouble(4, lwWholeSalePriceDto.getVoltageEnd());
    dbManager.setDouble(5, lwWholeSalePriceDto.getPrice());
    dbManager.setString(6, lwWholeSalePriceDto.getValidStatus());
    dbManager.setString(7, lwWholeSalePriceDto.getFlag());
    dbManager.setString(8, lwWholeSalePriceDto.getRemark());
    dbManager.executePreparedUpdate();
  }
예제 #24
0
  /**
   * 按主键删除一条数据
   *
   * @param saleArea 趸售区域
   * @param voltageBegin 起始电压
   * @throws Exception
   */
  public void delete(String saleArea, double voltageBegin) throws Exception {
    StringBuffer buffer = new StringBuffer(100);
    buffer.append("DELETE FROM LwWholeSalePrice ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append(buffer.toString());
      debugBuffer.append("WHERE ");
      debugBuffer.append("SaleArea=").append("'").append(saleArea).append("' AND ");
      debugBuffer.append("VoltageBegin=").append("").append(voltageBegin).append("");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("WHERE ");
    buffer.append("SaleArea = ? And ");
    buffer.append("VoltageBegin = ?");

    dbManager.prepareStatement(buffer.toString());
    // 设置条件字段;
    dbManager.setString(1, saleArea);
    dbManager.setDouble(2, voltageBegin);
    dbManager.executePreparedUpdate();
  }
예제 #25
0
  /**
   * 按主键删除一条数据
   *
   * @param userNo 户号
   * @param statMonth 账期
   * @throws Exception
   */
  public void delete(String userNo, String statMonth) throws Exception {
    StringBuffer buffer = new StringBuffer(100);
    buffer.append("DELETE FROM LwTownIndicator ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append(buffer.toString());
      debugBuffer.append("WHERE ");
      debugBuffer.append("UserNo=").append("'").append(userNo).append("' AND ");
      debugBuffer.append("StatMonth=").append("'").append(statMonth).append("'");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("WHERE ");
    buffer.append("UserNo = ? And ");
    buffer.append("StatMonth = ?");

    dbManager.prepareStatement(buffer.toString());
    // 设置条件字段;
    dbManager.setString(1, userNo);
    dbManager.setString(2, statMonth);
    dbManager.executePreparedUpdate();
  }
예제 #26
0
  private void sendStartupPacket(PGStream pgStream, String[][] params, Logger logger)
      throws IOException {
    if (logger.logDebug()) {
      String details = "";
      for (int i = 0; i < params.length; ++i) {
        if (i != 0) details += ", ";
        details += params[i][0] + "=" + params[i][1];
      }
      logger.debug(" FE=> StartupPacket(" + details + ")");
    }

    /*
     * Precalculate message length and encode params.
     */
    int length = 4 + 4;
    byte[][] encodedParams = new byte[params.length * 2][];
    for (int i = 0; i < params.length; ++i) {
      encodedParams[i * 2] = params[i][0].getBytes("US-ASCII");
      encodedParams[i * 2 + 1] = params[i][1].getBytes("US-ASCII");
      length += encodedParams[i * 2].length + 1 + encodedParams[i * 2 + 1].length + 1;
    }

    length += 1; // Terminating \0

    /*
     * Send the startup message.
     */
    pgStream.SendInteger4(length);
    pgStream.SendInteger2(3); // protocol major
    pgStream.SendInteger2(0); // protocol minor
    for (int i = 0; i < encodedParams.length; ++i) {
      pgStream.Send(encodedParams[i]);
      pgStream.SendChar(0);
    }

    pgStream.SendChar(0);
    pgStream.flush();
  }
예제 #27
0
  public ProtocolConnection openConnectionImpl(
      String host, int port, String user, String database, Properties info, Logger logger)
      throws SQLException {
    // Extract interesting values from the info properties:
    //  - the SSL setting
    boolean requireSSL = (info.getProperty("ssl") != null);
    boolean trySSL = requireSSL; // XXX temporary until we revisit the ssl property values

    // NOTE: To simplify this code, it is assumed that if we are
    // using the V3 protocol, then the database is at least 7.4.  That
    // eliminates the need to check database versions and maintain
    // backward-compatible code here.
    //
    // Change by Chris Smith <*****@*****.**>

    if (logger.logDebug())
      logger.debug("Trying to establish a protocol version 3 connection to " + host + ":" + port);

    if (!Driver.sslEnabled()) {
      if (requireSSL)
        throw new PSQLException(
            GT.tr("The driver does not support SSL."), PSQLState.CONNECTION_FAILURE);
      trySSL = false;
    }

    //
    // Establish a connection.
    //

    PGStream newStream = null;
    try {
      newStream = new PGStream(host, port);

      // Construct and send an ssl startup packet if requested.
      if (trySSL) newStream = enableSSL(newStream, requireSSL, info, logger);

      // Construct and send a startup packet.
      String[][] params = {
        {"user", user},
        {"database", database},
        {"client_encoding", "UNICODE"},
        {"DateStyle", "ISO"},
        {"extra_float_digits", "2"}
      };

      sendStartupPacket(newStream, params, logger);

      // Do authentication (until AuthenticationOk).
      doAuthentication(newStream, user, info.getProperty("password"), logger);

      // Do final startup.
      ProtocolConnectionImpl protoConnection =
          new ProtocolConnectionImpl(newStream, user, database, info, logger);
      readStartupMessages(newStream, protoConnection, logger);

      // And we're done.
      return protoConnection;
    } catch (UnsupportedProtocolException upe) {
      // Swallow this and return null so ConnectionFactory tries the next protocol.
      if (logger.logDebug()) logger.debug("Protocol not supported, abandoning connection.");
      try {
        newStream.close();
      } catch (IOException e) {
      }
      return null;
    } catch (ConnectException cex) {
      // Added by Peter Mount <*****@*****.**>
      // ConnectException is thrown when the connection cannot be made.
      // we trap this an return a more meaningful message for the end user
      throw new PSQLException(
          GT.tr(
              "Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections."),
          PSQLState.CONNECTION_REJECTED,
          cex);
    } catch (IOException ioe) {
      if (newStream != null) {
        try {
          newStream.close();
        } catch (IOException e) {
        }
      }
      throw new PSQLException(
          GT.tr("The connection attempt failed."), PSQLState.CONNECTION_UNABLE_TO_CONNECT, ioe);
    } catch (SQLException se) {
      if (newStream != null) {
        try {
          newStream.close();
        } catch (IOException e) {
        }
      }
      throw se;
    }
  }
예제 #28
0
  private void readStartupMessages(
      PGStream pgStream, ProtocolConnectionImpl protoConnection, Logger logger)
      throws IOException, SQLException {
    while (true) {
      int beresp = pgStream.ReceiveChar();
      switch (beresp) {
        case 'Z':
          // Ready For Query; we're done.
          if (pgStream.ReceiveInteger4() != 5)
            throw new IOException("unexpected length of ReadyForQuery packet");

          char tStatus = (char) pgStream.ReceiveChar();
          if (logger.logDebug()) logger.debug(" <=BE ReadyForQuery(" + tStatus + ")");

          // Update connection state.
          switch (tStatus) {
            case 'I':
              protoConnection.setTransactionState(ProtocolConnection.TRANSACTION_IDLE);
              break;
            case 'T':
              protoConnection.setTransactionState(ProtocolConnection.TRANSACTION_OPEN);
              break;
            case 'E':
              protoConnection.setTransactionState(ProtocolConnection.TRANSACTION_FAILED);
              break;
            default:
              // Huh?
              break;
          }

          return;

        case 'K':
          // BackendKeyData
          int l_msgLen = pgStream.ReceiveInteger4();
          if (l_msgLen != 12)
            throw new PSQLException(
                GT.tr("Protocol error.  Session setup failed."),
                PSQLState.CONNECTION_UNABLE_TO_CONNECT);

          int pid = pgStream.ReceiveInteger4();
          int ckey = pgStream.ReceiveInteger4();

          if (logger.logDebug())
            logger.debug(" <=BE BackendKeyData(pid=" + pid + ",ckey=" + ckey + ")");

          protoConnection.setBackendKeyData(pid, ckey);
          break;

        case 'E':
          // Error
          int l_elen = pgStream.ReceiveInteger4();
          ServerErrorMessage l_errorMsg =
              new ServerErrorMessage(pgStream.ReceiveString(l_elen - 4), logger.getLogLevel());

          if (logger.logDebug()) logger.debug(" <=BE ErrorMessage(" + l_errorMsg + ")");

          throw new PSQLException(l_errorMsg);

        case 'N':
          // Warning
          int l_nlen = pgStream.ReceiveInteger4();
          ServerErrorMessage l_warnMsg =
              new ServerErrorMessage(pgStream.ReceiveString(l_nlen - 4), logger.getLogLevel());

          if (logger.logDebug()) logger.debug(" <=BE NoticeResponse(" + l_warnMsg + ")");

          protoConnection.addWarning(new PSQLWarning(l_warnMsg));
          break;

        case 'S':
          // ParameterStatus
          int l_len = pgStream.ReceiveInteger4();
          String name = pgStream.ReceiveString();
          String value = pgStream.ReceiveString();

          if (logger.logDebug())
            logger.debug(" <=BE ParameterStatus(" + name + " = " + value + ")");

          if (name.equals("server_version")) protoConnection.setServerVersion(value);
          else if (name.equals("client_encoding")) {
            if (!value.equals("UNICODE"))
              throw new PSQLException(
                  GT.tr("Protocol error.  Session setup failed."),
                  PSQLState.CONNECTION_UNABLE_TO_CONNECT);
            pgStream.setEncoding(Encoding.getDatabaseEncoding("UNICODE"));
          } else if (name.equals("standard_conforming_strings")) {
            if (value.equals("on")) protoConnection.setStandardConformingStrings(true);
            else if (value.equals("off")) protoConnection.setStandardConformingStrings(false);
            else
              throw new PSQLException(
                  GT.tr("Protocol error.  Session setup failed."),
                  PSQLState.CONNECTION_UNABLE_TO_CONNECT);
          }

          break;

        default:
          if (logger.logDebug()) logger.debug("invalid message type=" + (char) beresp);
          throw new PSQLException(
              GT.tr("Protocol error.  Session setup failed."),
              PSQLState.CONNECTION_UNABLE_TO_CONNECT);
      }
    }
  }
예제 #29
0
  private void doAuthentication(PGStream pgStream, String user, String password, Logger logger)
      throws IOException, SQLException {
    // Now get the response from the backend, either an error message
    // or an authentication request

    while (true) {
      int beresp = pgStream.ReceiveChar();

      switch (beresp) {
        case 'E':
          // An error occured, so pass the error message to the
          // user.
          //
          // The most common one to be thrown here is:
          // "User authentication failed"
          //
          int l_elen = pgStream.ReceiveInteger4();
          if (l_elen > 30000) {
            // if the error length is > than 30000 we assume this is really a v2 protocol
            // server, so trigger fallback.
            throw new UnsupportedProtocolException();
          }

          ServerErrorMessage errorMsg =
              new ServerErrorMessage(pgStream.ReceiveString(l_elen - 4), logger.getLogLevel());
          if (logger.logDebug()) logger.debug(" <=BE ErrorMessage(" + errorMsg + ")");
          throw new PSQLException(errorMsg);

        case 'R':
          // Authentication request.
          // Get the message length
          int l_msgLen = pgStream.ReceiveInteger4();

          // Get the type of request
          int areq = pgStream.ReceiveInteger4();

          // Process the request.
          switch (areq) {
            case AUTH_REQ_CRYPT:
              {
                byte[] rst = new byte[2];
                rst[0] = (byte) pgStream.ReceiveChar();
                rst[1] = (byte) pgStream.ReceiveChar();
                String salt = new String(rst, 0, 2, "US-ASCII");

                if (logger.logDebug())
                  logger.debug(" <=BE AuthenticationReqCrypt(salt='" + salt + "')");

                if (password == null)
                  throw new PSQLException(
                      GT.tr(
                          "The server requested password-based authentication, but no password was provided."),
                      PSQLState.CONNECTION_REJECTED);

                String result = UnixCrypt.crypt(salt, password);
                byte[] encodedResult = result.getBytes("US-ASCII");

                if (logger.logDebug()) logger.debug(" FE=> Password(crypt='" + result + "')");

                pgStream.SendChar('p');
                pgStream.SendInteger4(4 + encodedResult.length + 1);
                pgStream.Send(encodedResult);
                pgStream.SendChar(0);
                pgStream.flush();

                break;
              }

            case AUTH_REQ_MD5:
              {
                byte[] md5Salt = pgStream.Receive(4);
                if (logger.logDebug()) {
                  logger.debug(
                      " <=BE AuthenticationReqMD5(salt=" + Utils.toHexString(md5Salt) + ")");
                }

                if (password == null)
                  throw new PSQLException(
                      GT.tr(
                          "The server requested password-based authentication, but no password was provided."),
                      PSQLState.CONNECTION_REJECTED);

                byte[] digest = MD5Digest.encode(user, password, md5Salt);

                if (logger.logDebug()) {
                  logger.debug(" FE=> Password(md5digest=" + new String(digest, "US-ASCII") + ")");
                }

                pgStream.SendChar('p');
                pgStream.SendInteger4(4 + digest.length + 1);
                pgStream.Send(digest);
                pgStream.SendChar(0);
                pgStream.flush();

                break;
              }

            case AUTH_REQ_PASSWORD:
              {
                if (logger.logDebug()) {
                  logger.debug(" <=BE AuthenticationReqPassword");
                  logger.debug(" FE=> Password(password=<not shown>)");
                }

                if (password == null)
                  throw new PSQLException(
                      GT.tr(
                          "The server requested password-based authentication, but no password was provided."),
                      PSQLState.CONNECTION_REJECTED);

                byte[] encodedPassword = password.getBytes("US-ASCII");

                pgStream.SendChar('p');
                pgStream.SendInteger4(4 + encodedPassword.length + 1);
                pgStream.Send(encodedPassword);
                pgStream.SendChar(0);
                pgStream.flush();

                break;
              }

            case AUTH_REQ_OK:
              if (logger.logDebug()) logger.debug(" <=BE AuthenticationOk");

              return; // We're done.

            default:
              if (logger.logDebug())
                logger.debug(" <=BE AuthenticationReq (unsupported type " + ((int) areq) + ")");

              throw new PSQLException(
                  GT.tr(
                      "The authentication type {0} is not supported. Check that you have configured the pg_hba.conf file to include the client''s IP address or subnet, and that it is using an authentication scheme supported by the driver.",
                      new Integer(areq)),
                  PSQLState.CONNECTION_REJECTED);
          }

          break;

        default:
          throw new PSQLException(
              GT.tr("Protocol error.  Session setup failed."),
              PSQLState.CONNECTION_UNABLE_TO_CONNECT);
      }
    }
  }
  /**
   * @return Connection
   * @roseuid 3F3A5FFD0338
   */
  public Connection getConnection() throws EmanagerDatabaseException {
    long connectionId;
    Connection connection;
    PooledConnection pooledConnection;

    connection = null;
    pooledConnection = null;
    connectionId = InvalidConnectionId;

    try {
      synchronized (connectionPool) {
        if (!connectionPool.isEmpty()) {
          try {
            boolean connectionClosed;

            connectionClosed = false;

            pooledConnection = (PooledConnection) connectionPool.remove(0);
            connection = pooledConnection.getConnection();
            connection.clearWarnings();
            connectionId = getConnectionID(connection);
            connectionClosed = connection.isClosed();
            if (connectionId == InvalidConnectionId || connectionClosed == true) {
              logger.debug("Pooled connection closed.");
              connection = null;
            }
          } catch (SQLException sqe) {
            logger.debug("Pooled connection closed.");
            connection = null;
          }
        }
      }

      if (connection == null) {
        logger.debug("Getting a new connection.");
        pooledConnection = poolDataSource.getPooledConnection();
        pooledConnection.addConnectionEventListener(this);
        connection = pooledConnection.getConnection();
        connection.clearWarnings();
        connectionId = getConnectionID(connection);
      }
    } catch (SQLException sqe) {
      String logString;
      EmanagerDatabaseException ede;

      logString =
          EmanagerDatabaseStatusCode.UnableToGetPooledConnection.getStatusCodeDescription()
              + sqe.getMessage();

      logger.error(logString);
      ede =
          new EmanagerDatabaseException(
              EmanagerDatabaseStatusCode.UnableToGetPooledConnection, logString);
      throw ede;
    }

    if (connectionId == InvalidConnectionId) {
      EmanagerDatabaseException ede;
      ede =
          new EmanagerDatabaseException(
              EmanagerDatabaseStatusCode.UnableToGetPooledConnection,
              EmanagerDatabaseStatusCode.UnableToGetPooledConnection.getStatusCodeDescription());
      throw ede;
    }

    logger.debug(
        "\n*****************************"
            + "\nPooled Connection Init"
            + "\nCon ID:"
            + connectionId
            + "\nCon Object:"
            + pooledConnection
            + "\nPool Object:"
            + connection
            + "\n*****************************");

    return connection;
  }