/** 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;
    }
  }
Пример #2
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();
 }
Пример #3
0
  public static Customer[] getCustomers() {
    Logger.log("Database.getCustomers", CALL_FLAG);
    Customer[] customers = new Customer[0];
    try {
      String name;
      String phoneNumber;
      int id;
      ResultSet rs = query("SELECT COUNT(*) FROM kunder");
      rs.next();
      customers = new Customer[rs.getInt("COUNT(*)")];
      rs.next();
      rs = query("SELECT * FROM kunder");

      while (rs.next()) {
        name = rs.getString("navn");
        phoneNumber = rs.getString("telefon");
        id = rs.getInt("kunde_id");
        customers[rs.getRow() - 1] = new Customer(name, phoneNumber, id);
      }
    } catch (SQLException exception) {
      Logger.log(exception, "Database:getCustomers");
    }
    Logger.log("Database.getCustomer Finised", FINISHED_FLAG);
    return customers;
  }
Пример #4
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();
 }
Пример #5
0
  public static Show[] getShows() {
    Logger.log("Database.getShows", CALL_FLAG);
    Show[] shows = new Show[0];
    try {
      Hall[] halls = getHalls();
      Movie[] movies = getMovies();
      Timestamp time;
      Hall hall;
      Movie movie;
      int ID;

      ResultSet rs = query("SELECT COUNT(*) FROM forestillinger");
      rs.next();
      shows = new Show[rs.getInt("COUNT(*)")];
      rs = query("SELECT * FROM forestillinger ORDER BY tid ASC");

      while (rs.next()) {
        hall = halls[rs.getInt("sal_id") - 1];
        movie = movies[rs.getInt("film_id") - 1];
        time = rs.getTimestamp("tid");
        ID = rs.getInt("forestilling_id");
        shows[rs.getRow() - 1] = new Show(hall, movie, time, ID);
      }
    } catch (Exception exception) {
      Logger.log(exception, "Database:getShows");
    }
    Logger.log("Database.getShows", FINISHED_FLAG);
    return shows;
  }
Пример #6
0
 protected void executeQuery(Statement stmt, String q) throws SQLException {
   q = q.replace("$PREFIX", getPrefix());
   LOG.info(" Executing " + q);
   ResultSet rs = stmt.executeQuery(q);
   StringBuilder header = new StringBuilder();
   for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
     if (i > 1) {
       header.append("|");
     }
     header.append(rs.getMetaData().getColumnName(i));
   }
   LOG.info(header);
   int seq = 0;
   while (true) {
     boolean valid = rs.next();
     if (!valid) break;
     seq++;
     StringBuilder line = new StringBuilder();
     for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
       if (i > 1) {
         line.append("|");
       }
       line.append(rs.getString(i));
     }
     LOG.info(seq + ":" + line);
   }
 }
Пример #7
0
 protected boolean insertComment() throws SQLException {
   try {
     String dburl = getServletContext().getInitParameter("DBUrl");
     String dbuser = getServletContext().getInitParameter("DBUser");
     String dbpasswd = getServletContext().getInitParameter("DBPasswd");
     Class.forName("com.mysql.jdbc.Driver");
     conn = DriverManager.getConnection(dburl, dbuser, dbpasswd);
     String sqlqry = "INSERT INTO feedback (name, email, feedback) VALUES (?,?,?)";
     pstmt = conn.prepareStatement(sqlqry);
     pstmt.setString(1, name);
     pstmt.setString(2, email);
     pstmt.setString(3, comment);
     if (pstmt.executeUpdate() > 0) return true;
   } catch (ClassNotFoundException e) {
     // TODO Auto-generated catch block
     logger.error(e);
     e.printStackTrace();
   } catch (SQLException e) {
     // TODO Auto-generated catch block
     logger.error(e);
     e.printStackTrace();
   } finally {
     conn.close();
     pstmt.close();
   }
   return false;
 }
Пример #8
0
  protected void processData(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException {
    try {
      String dispatchUrl = "/feedback.jsp";
      name = request.getParameter("txtName");
      email = request.getParameter("txtEmail");
      comment = request.getParameter("txtComment");

      if (!insertComment()) {
        logger.error("Error. Could not insert comment");
        request.setAttribute("status", "fail");
      } else {
        request.setAttribute("status", "success");
      }
      RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(dispatchUrl);
      dispatcher.include(request, response);
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      logger.error(e);
      e.printStackTrace();
    } finally {
      conn.close();
      pstmt.close();
    }
  }
Пример #9
0
 public static boolean createCustomer(String name, String phoneNumber) {
   Logger.log("Database.createCustomer", CALL_FLAG);
   if (update(
       "INSERT INTO kunder (telefon, navn) VALUES('" + phoneNumber + "', '" + name + "' )")) {
     Logger.log("Database.createCustomer", FINISHED_FLAG);
     return true;
   }
   return false;
 }
Пример #10
0
 public static void deleteReservation(int kunde_ID, int forestilling_id) {
   Logger.log("Database.deleteReservation");
   update(
       "DELETE FROM reservation WHERE forestilling_id = "
           + forestilling_id
           + " AND kunde_id = "
           + kunde_ID
           + ";");
   Logger.log("Database.deleteReservation Done");
 }
Пример #11
0
 /**
  * 按条件删除数据
  *
  * @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;
 }
Пример #12
0
  public static ArrayList<Reservation> getReservations(Show[] shows, Customer[] customers) {
    Logger.log("Database.getReservations");
    ArrayList<Reservation> reservations = new ArrayList<Reservation>();
    try {
      ArrayList<Reservation> tempReservations = new ArrayList<Reservation>();
      Show show = null;
      Customer customer = null;

      ResultSet rs = query("SELECT COUNT(*) FROM reservation");
      rs.next();

      rs = query("SELECT * FROM reservation");
      while (rs.next()) {
        ArrayList<Point> position = new ArrayList<Point>();
        for (Show s : shows) {
          if (s.getID() == rs.getInt("forestilling_id")) {
            show = s;
          }
        }
        position.add(new Point(rs.getInt("pos_x"), rs.getInt("pos_y")));
        for (Customer c : customers) {
          if (c.getID() == rs.getInt("kunde_id")) {
            customer = c;
          }
        }
        tempReservations.add(
            new Reservation(show, position, customer, rs.getInt("reservation_id")));
      }
      // Merge all reservations which have the same show AND customer and save them in reservations
      // list
      while (tempReservations.size() != 0) {
        Customer cus = tempReservations.get(0).getCustomer();
        Show s = tempReservations.get(0).getShow();
        ArrayList<Point> seats = new ArrayList<Point>();
        int ID = tempReservations.get(0).getID();
        for (int x = 0; x < tempReservations.size(); x++) {
          if (tempReservations.get(x).getCustomer() == cus
              && tempReservations.get(x).getShow() == s) {
            seats.add(tempReservations.get(x).getFirstPos());
            tempReservations.remove(tempReservations.get(x));
            // After deleting the object, decrease x with 1 (else one element would never be
            // reached)
            x--;
          }
        }
        reservations.add(new Reservation(s, seats, cus, ID));
      }

    } catch (SQLException exception) {
      Logger.log(exception, "Database:getReservations");
    }
    Logger.log("Database.getReservations");
    return reservations;
  }
  /**
   * Gets the ConnectionID attribute of the SybaseConnector class
   *
   * @param connection
   * @return The ConnectionID value
   */
  public static long getConnectionID(Connection connection) {
    try {
      Statement stmt = connection.createStatement();
      ResultSet res = stmt.executeQuery("select connection_property('Number')");
      res.next();
      return res.getLong(1);
    } catch (SQLException ex) {
      logger.error("SQL exception retrieving connection ID:" + ex.getMessage());
    }

    return InvalidConnectionId;
  }
 /**
  * Checks if a lock is left behind in the DB.
  *
  * @param con
  * @param conID
  * @return true if a lock is found.
  */
 public static boolean checkLocks(Connection connection, long conID) {
   try {
     Statement stmt = connection.createStatement();
     ResultSet res = stmt.executeQuery("exec sa_locks " + conID);
     while (res.next()) {
       return true;
     }
   } catch (SQLException ex) {
     logger.error("Unable to retrieve connection ID", ex);
   }
   return false;
 }
Пример #15
0
 public static Customer getCustomerByTlf(String tlfnr) {
   Logger.log("Database.getCustomerByTlf", CALL_FLAG);
   try {
     ResultSet rs = query("SELECT * FROM kunder WHERE telefon = " + tlfnr);
     rs.next();
     Logger.log("Database.getCustomerByTlf", FINISHED_FLAG);
     return new Customer(rs.getString("navn"), rs.getString("telefon"), rs.getInt("kunde_id"));
   } catch (SQLException e) {
     Logger.log(e, "Database:getCustomerByTlf");
   }
   return null;
 }
  /**
   * @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());
        }
      }
    }
  }
Пример #17
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;
 }
Пример #18
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();
  }
  private void initDriverList() {
    try {
      Thread thread = Thread.currentThread();
      ClassLoader loader = thread.getContextClassLoader();

      Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver");
      while (iter.hasMoreElements()) {
        URL url = (URL) iter.nextElement();

        ReadStream is = null;
        try {
          is = Vfs.lookup(url.toString()).openRead();

          String filename;

          while ((filename = is.readLine()) != null) {
            int p = filename.indexOf('#');

            if (p >= 0) filename = filename.substring(0, p);

            filename = filename.trim();
            if (filename.length() == 0) continue;

            try {
              Class cl = Class.forName(filename, false, loader);
              Driver driver = null;

              if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance();

              if (driver != null) {
                log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName()));

                _driverList.add(driver);
              }
            } catch (Exception e) {
              log.log(Level.FINE, e.toString(), e);
            }
          }
        } catch (Exception e) {
          log.log(Level.FINE, e.toString(), e);
        } finally {
          if (is != null) is.close();
        }
      }
    } catch (Exception e) {
      log.log(Level.FINE, e.toString(), e);
    }
  }
Пример #20
0
 public static void logm(String t, int lvl, String msg, Object o) {
   // System.out.println("LOG:" + t + ":" + lvl + ":" + msg + ":" + (o != null ? ser_json(o) :
   // ""));
   if (lvl <= LogLvlMax) {
     logger.info(t + ":" + lvl + ":" + msg + ":" + (o != null ? ser_json(o) : ""));
   }
 }
Пример #21
0
  public static String getVariable(Connection conn, String name) throws SQLException {
    String method = "getVariable";
    int location = 1000;
    try {
      location = 2000;
      String value = "";

      location = 2100;
      Statement stmt = conn.createStatement();
      String strSQL = "SELECT os.fn_get_variable('" + name + "')";

      if (debug) Logger.printMsg("Getting Variable: " + strSQL);

      location = 2200;
      ResultSet rs = stmt.executeQuery(strSQL);

      while (rs.next()) {
        value = rs.getString(1);
      }

      location = 2300;
      return value;

    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Пример #22
0
  public static String getVersion(Connection conn) throws SQLException {
    String method = "getVersion";
    int location = 1000;
    try {
      location = 2000;
      String value = "";

      location = 2100;
      Statement stmt = conn.createStatement();
      String strSQL =
          "SELECT CASE "
              + "WHEN POSITION ('HAWQ 2.0.1' in version) > 0 THEN 'HAWQ_2_0_1' "
              + "WHEN POSITION ('HAWQ 2.0.0' in version) > 0 THEN 'HAWQ_2_0_0' "
              + "WHEN POSITION ('HAWQ 1' in version) > 0 THEN 'HAWQ_1' "
              + "WHEN POSITION ('HAWQ' in version) = 0 AND POSITION ('Greenplum Database' IN version) > 0 THEN 'GPDB' "
              + "ELSE 'OTHER' END "
              + "FROM version()";
      if (debug) Logger.printMsg("Getting Variable: " + strSQL);

      location = 2200;
      ResultSet rs = stmt.executeQuery(strSQL);

      while (rs.next()) {
        value = rs.getString(1);
      }

      location = 2300;
      return value;

    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
  public final Response executeCommand(
      Object inputPar,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    GridParams gridParams = (GridParams) inputPar;
    try {
      String companyCode =
          (String) gridParams.getOtherGridParams().get(ApplicationConsts.COMPANY_CODE_SYS01);
      BigDecimal progressiveHie02 =
          (BigDecimal) gridParams.getOtherGridParams().get(ApplicationConsts.PROGRESSIVE_HIE02);

      ItemFields bean = (ItemFields) JAIOBeanFactory.getInstance().getBean(ItemFields.class);
      Response answer =
          bean.loadItemFields(
              companyCode,
              progressiveHie02,
              ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId(),
              userSessionPars.getUsername());

      return answer;
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while processing request",
          ex);
      return new ErrorResponse(ex.getMessage());
    }
  }
  /**
   * Retrieves all of the Discussion Threads associated with a Group Id
   *
   * @param groupId The Group Id to get Threads for
   * @return A List of Discussion Threads that belong to the Group
   */
  public List<DiscussionThread> getThreads(int groupId) {
    ArrayList<DiscussionThread> threads = new ArrayList<>();

    try {
      // Create a prepared statement
      PreparedStatement pstmt =
          conn.prepareStatement("SELECT * FROM DiscussionThreads WHERE GroupId = ?");

      // Set the required parameters and execute
      pstmt.setInt(1, groupId);
      ResultSet rs = pstmt.executeQuery();

      // Get the results and add to the list
      if (rs.isBeforeFirst()) {
        while (!rs.isAfterLast()) {
          DiscussionThread thread = DiscussionThread.fromResultSet(rs);
          if (thread != null) {
            threads.add(thread);
          }
        }
      }
    } catch (Exception e) {
      logger.log(Level.SEVERE, "SQL Error", e);
    }

    return threads;
  }
  public final Response executeCommand(
      Object inputPar,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    try {
      String tableName = ((Object[]) inputPar)[0].toString();
      ArrayList oldVOs = (ArrayList) ((Object[]) inputPar)[1];
      ArrayList newVOs = (ArrayList) ((Object[]) inputPar)[2];

      VariantTypes bean = (VariantTypes) JAIOBeanFactory.getInstance().getBean(VariantTypes.class);
      Response answer =
          bean.updateVariantTypes(
              tableName,
              oldVOs,
              newVOs,
              ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId(),
              userSessionPars.getUsername());

      return answer;
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while processing request",
          ex);
      return new ErrorResponse(ex.getMessage());
    }
  }
  /**
   * Retrieves a List of Discussion Posts for a given Thread Id
   *
   * @param threadId The Id of the Thread to query
   * @return A List of Discussion Posts for the Thread
   */
  public List<DiscussionPost> getPosts(int threadId) {
    ArrayList<DiscussionPost> posts = new ArrayList<>();

    try {
      // Create a prepared statement
      PreparedStatement pstmt =
          conn.prepareStatement("SELECT * FROM DiscussionPosts WHERE ThreadId = ?");

      // Set the required parameters adn execute
      pstmt.setInt(1, threadId);
      ResultSet rs = pstmt.executeQuery();

      // Retrieve the results and add to the list
      if (rs.isBeforeFirst()) {
        while (!rs.isAfterLast()) {
          DiscussionPost post = DiscussionPost.fromResultSet(rs);

          if (post != null) posts.add(post);
        }
      }
    } catch (Exception e) {
      logger.log(Level.SEVERE, "SQL Error", e);
    }

    return posts;
  }
  public final Response executeCommand(
      Object inputPar,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    ArrayList vos = (ArrayList) inputPar;
    try {

      ItemDiscounts bean =
          (ItemDiscounts) JAIOBeanFactory.getInstance().getBean(ItemDiscounts.class);
      Response answer =
          bean.deleteItemDiscounts(
              vos,
              ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId(),
              userSessionPars.getUsername());

      return answer;
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while processing request",
          ex);
      return new ErrorResponse(ex.getMessage());
    }
  }
Пример #28
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;
  }
  /**
   * @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.
          }
        }
      }
    }
  }
  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;
    }
  }