Exemplo n.º 1
0
/**
 * 这是LWTownIndicatorAppend-直供乡追加电费指针记录表的数据访问对象类<br>
 * 创建于 2008-12-17 11:27:43.218<br>
 * JToolpad(1.6.0) Vendor:[email protected]
 */
public class DBLwTownIndicatorAppend extends DBLwTownIndicatorAppendBase {
  private static Logger logger = Logger.getLogger(DBLwTownIndicatorAppend.class);

  /**
   * 构造函数
   *
   * @param dbManager 资源管理类
   */
  public DBLwTownIndicatorAppend(DBManager dbManager) {
    super(dbManager);
  }
}
/**
 * Provides the functionality to communicate with the database and perform queries pertaining to
 * Discussions
 *
 * @author Tyler Haigh - C3182929
 * @author Simon Hartcher - C3185790
 * @author Josh Crompton - C3165877
 */
public class DiscussionManager extends DataManager {
  private final Logger logger = Logger.getLogger("rgms.datacontext.DiscussionManager");

  /**
   * Creates a Discussion Thread in the database
   *
   * @param discussion The Discussion to insert
   */
  public void createDiscussion(DiscussionThread discussion) {
    try {
      // Create a prepared statement
      PreparedStatement pstmt =
          conn.prepareStatement(
              "INSERT INTO DiscussionThreads (GroupId, ThreadName)" + "VALUES (?, ?)",
              Statement.RETURN_GENERATED_KEYS);

      // Set the required parameters and execute
      pstmt.setInt(1, discussion.getGroupId());
      pstmt.setString(2, discussion.getThreadName());
      pstmt.executeUpdate();

      // Get the generated id
      ResultSet rs = pstmt.getGeneratedKeys();
      if (rs.next()) discussion.setId(rs.getInt(1));
    } catch (Exception e) {
      logger.log(Level.SEVERE, "SQL Error", e);
    }
  }

  /**
   * Creates a Discussion Post in the database
   *
   * @param post The Discussion Post to insert
   */
  public void createPost(DiscussionPost post) {
    try {
      // Create a prepared statement
      PreparedStatement pstmt =
          conn.prepareStatement(
              "INSERT INTO DiscussionPosts (ThreadId, UserId, Message)" + "VALUES (?, ?, ?)",
              Statement.RETURN_GENERATED_KEYS);

      // Set the required parameters and execute
      pstmt.setInt(1, post.getThreadId());
      pstmt.setInt(2, post.getUserId());
      pstmt.setString(3, post.getMessage());
      pstmt.executeUpdate();

      // get the generated id
      ResultSet rs = pstmt.getGeneratedKeys();
      if (rs.next()) post.setId(rs.getInt(1));
    } catch (Exception e) {
      logger.log(Level.SEVERE, "SQL Error", e);
    }
  }

  /**
   * 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;
  }

  /**
   * Retrieves a single thread based on its Id
   *
   * @param threadId The Id of the Thread
   * @return The Thread with the given Id
   */
  public DiscussionThread getThread(int threadId) {
    DiscussionThread thread = null;

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

      // Set the required parameters and execute
      pstmt.setInt(1, threadId);
      ResultSet rs = pstmt.executeQuery();
      thread = DiscussionThread.fromResultSet(rs);
    } catch (Exception e) {
      logger.log(Level.SEVERE, "SQL Error", e);
    }

    return thread;
  }

  /**
   * 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;
  }
}
Exemplo n.º 3
0
public class LineDAOImpl extends HibernateDaoSupport {
  private static Logger logger = Logger.getLogger("LineDAOImpl");

  public Line addLine(Line line) throws Exception {
    this.getHibernateTemplate().save(line);
    return line;
  }

  public Line findById(String id) throws Exception {
    return (Line) this.getHibernateTemplate().load(Line.class, id);
  }

  public void removeLine(Line line) throws Exception {
    this.getHibernateTemplate().delete(line);
  }

  public Line updateLine(Line line) throws Exception {
    this.getHibernateTemplate().saveOrUpdate(line);
    return line;
  }

  /**
   * 检验LineName 是否存在
   *
   * @param name String
   * @return boolean
   */
  public boolean validateLineName(String name, String type, String region) {
    String sql =
        "select count(lineid) i from lineinfo where linename='"
            + name
            + "' and regionid='"
            + region
            + "'";
    ResultSet rs = null;
    try {
      QueryUtil query = new QueryUtil();
      logger.info("validateLineName() sql :" + sql);
      rs = query.executeQuery(sql);
      rs.next();
      int i = rs.getInt("i");
      logger.info("i=" + i);
      if ("edit".equals(type)) {
        if (i < 1) {
          rs.close();
          return true;
        } else {
          rs.close();
          return false;
        }
      } else {
        if (i == 0) {
          rs.close();
          return true;
        } else {
          rs.close();
          return false;
        }
      }
    } catch (Exception ex) {
      logger.error("检查线路是否重名时出错: " + ex.getMessage());
      return false;
    }
  }

  /**
   * 功能:检查指定的线能否被删除,
   *
   * <p>参数:指定线的id
   *
   * <p>返回值:能删除返回true,否则返回false;
   */
  public boolean valiLineCanDele(String lineid) {

    ResultSet rst = null;
    String sql = "select count(*) aa from  sublineinfo  where lineid='" + lineid + "'";
    try {
      QueryUtil excu = new QueryUtil();
      rst = excu.executeQuery(sql);
      rst.next();
      if (rst.getInt("aa") == 0) {
        rst.close();
        return true;
      } else {
        rst.close();
        return false;
      }
    } catch (Exception e) {
      logger.error("检查指定的线能否被删除出错:" + e.getMessage());
      return false;
    }
  }

  public List getLine(String sql) {
    QueryUtil query = null;
    BasicDynaBean dynaBean = null;
    // Vector resultVct = new Vector();
    ArrayList lableList = new ArrayList();
    logger.info("SQL :" + sql);
    try {
      query = new QueryUtil();
      Iterator it = query.queryBeans(sql).iterator();
      while (it.hasNext()) {
        dynaBean = (BasicDynaBean) it.next();
        // logger.info("lavel :"+dynaBean.get("linename")+"  value :"+dynaBean.get("lineid"));
        lableList.add(
            new LabelValueBean(
                (String) (dynaBean.get("linename")), (String) (dynaBean.get("lineid"))));
      }
      // resultVct.add(lableList);
      logger.info(lableList);
      return lableList;
    } catch (Exception ex) {
      logger.error("加载线路时出错:" + ex.getMessage());
      return null;
    }
  }
}
public class DatabaseConnectionManager implements ConnectionEventListener {
  private static Logger logger = Logger.getLogger(DatabaseConnectionManager.class);

  /** Connection pool datasource. */
  ConnectionPoolDataSource poolDataSource = null;

  /** Container of the pooled connections. */
  List connectionPool = Collections.synchronizedList(new LinkedList());

  /** a JNDI context. */
  Context jndiContext = null;

  private boolean SHUTTING_DOWN = false;

  // Driver config
  // final static String DRIVER_NAME = "com.sybase.jdbc2.jdbc.SybDriver";

  // private SybDriver sybaseDriver = null;

  /*
   * We are using a single instance to allow for pools now.
   */
  private static DatabaseConnectionManager connectionManager = null;

  private static final String JNDIContextName = "jdbc/emanagerDB";

  public static final long InvalidConnectionId = -1;

  // Database Connection properties
  private String userAccount;
  private String password;
  private String databaseName;
  private String databaseHost;
  private String clientAppName;
  private String userMetaData;
  private String useRepeatRead;
  private String charsetConverter;
  private String connectionPoolDescription;
  private int connectionPort;
  private static int connectionPoolSize;

  /** Constructor for the DatabaseConnectionManager object */
  private DatabaseConnectionManager() throws EmanagerDatabaseException {
    jndiContext = JNDIRegistryManager.instance().getJNDIContext();
    initializeDatabaseConnectionConfigurationParameters();
    initializeDatabaseContext();
    initializeConnectionPoolConnections();
  }

  private void initializeDatabaseConnectionConfigurationParameters() {
    String propertyValue;
    Properties systemProperties;

    systemProperties = GlobalProperties.instance().getProperties();

    userAccount = systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionUserAccountKey);
    if (userAccount == null) {
      userAccount = DatabaseGlobals.DatabaseConnectionUserAccountDefault;
    }
    logger.info(DatabaseGlobals.UserAccountValueMsg + userAccount);

    password = systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionPasswordKey);
    if (password == null) {
      password = DatabaseGlobals.DatabaseConnectionPasswordDefault;
    }
    logger.info(DatabaseGlobals.PasswordValueMsg + password);

    databaseName = systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionDatabaseNameKey);
    if (databaseName == null) {
      databaseName = DatabaseGlobals.DatabaseConnectionDatabaseNameDefault;
    }
    logger.info(DatabaseGlobals.DatabaseNameValueMsg + databaseName);

    databaseHost = systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionDatabaseHostKey);
    if (databaseHost == null) {
      databaseHost = DatabaseGlobals.DatabaseConnectionDatabaseHostDefault;
    }
    logger.info(DatabaseGlobals.DatabaseHostValueMsg + databaseHost);

    clientAppName =
        systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionClientAppNameKey);
    if (clientAppName == null) {
      clientAppName = DatabaseGlobals.DatabaseConnectionClientAppNameDefault;
    }
    logger.info(DatabaseGlobals.ClientAppNameValueMsg + clientAppName);

    userMetaData = systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionUserMetaDataKey);
    if (userMetaData == null) {
      userMetaData = DatabaseGlobals.DatabaseConnectionUserMetaDataDefault;
    }
    logger.info(DatabaseGlobals.UserMetaDataValueMsg + userMetaData);

    useRepeatRead =
        systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionUseRepeatReadKey);
    if (useRepeatRead == null) {
      useRepeatRead = DatabaseGlobals.DatabaseConnectionUseRepeatReadDefault;
    }
    logger.info(DatabaseGlobals.UseRepeatReadValueMsg + useRepeatRead);

    charsetConverter =
        systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionCharsetConverterKey);
    if (charsetConverter == null) {
      charsetConverter = DatabaseGlobals.DatabaseConnectionCharsetConverterDefault;
    }
    logger.info(DatabaseGlobals.CharsetConverterValueMsg + charsetConverter);

    connectionPoolDescription =
        systemProperties.getProperty(
            DatabaseGlobals.DatabaseConnectionConnectionPoolDescriptionKey);
    if (connectionPoolDescription == null) {
      connectionPoolDescription =
          DatabaseGlobals.DatabaseConnectionConnectionPoolDescriptionDefault;
    }
    logger.info(DatabaseGlobals.ConnectionPoolDescriptionValueMsg + connectionPoolDescription);

    propertyValue =
        systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionConnectionPortKey);
    if (propertyValue == null) {
      connectionPort = DatabaseGlobals.DatabaseConnectionConnectionPortDefault;
      logger.info("Using default connectionPort value: " + connectionPort);
    } else {
      try {
        connectionPort = Integer.parseInt(propertyValue);
        logger.info("Using connectionPort value: " + connectionPort);
      } catch (NumberFormatException e) {
        connectionPort = DatabaseGlobals.DatabaseConnectionConnectionPortDefault;
        logger.info(
            "Error converting property value.  Using default connectionPort value: "
                + connectionPort);
      }
    }

    propertyValue =
        systemProperties.getProperty(DatabaseGlobals.DatabaseConnectionConnectionPoolSizeKey);
    if (propertyValue == null) {
      connectionPoolSize = DatabaseGlobals.DatabaseConnectionConnectionPoolSizeDefault;
      logger.info("Using default connectionPoolSize value: " + connectionPoolSize);
    } else {
      try {
        connectionPoolSize = Integer.parseInt(propertyValue);
        logger.info("Using connectionPoolSize value: " + connectionPoolSize);
      } catch (NumberFormatException e) {
        connectionPoolSize = DatabaseGlobals.DatabaseConnectionConnectionPoolSizeDefault;
        logger.info(
            "Error converting property value.  Using default connectionPoolSize value: "
                + connectionPoolSize);
      }
    }
  }

  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;
    }
  }

  /**
   * 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();
    }
  }

  /** 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;
    }
  }

  /**
   * @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;
  }

  /**
   * @return com.cisco.eManager.eManager.database.DatabaseConnectionManager
   * @roseuid 3F3A63E40370
   */
  public static DatabaseConnectionManager instance() throws EmanagerDatabaseException {
    if (connectionManager == null) {
      connectionManager = new DatabaseConnectionManager();
    }

    return connectionManager;
  }

  /** @roseuid 3F3A88C50359 */
  private void addConnectionToPool() {}

  /**
   * @param maximumConnections
   * @roseuid 3F3A891C02B3
   */
  public static void setMaximumPooledConnections(int maximumConnections) {
    connectionPoolSize = maximumConnections;
  }

  /**
   * @return int
   * @roseuid 3F3A8939033A
   */
  public static int getMaximumPooledConnections() {
    return connectionPoolSize;
  }

  /** @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();
  }

  /**
   * @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());
        }
      }
    }
  }

  /**
   * 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;
  }

  /**
   * @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.
          }
        }
      }
    }
  }

  /**
   * Resets the con pool.
   *
   * @exception NamingException Description of Exception
   */
  public void reset() throws NamingException, EmanagerDatabaseException {
    shutdown();
    jndiContext.unbind(JNDIContextName);
    instance();
  }

  public String getDatabaseConnectionDatabaseHost() {
    return databaseHost;
  }
}
/**
 * ★★★★★警告:本文件不允许手工修改!!!请使用JToolpad生成!<br>
 * 这是LWWholeSaleSummary-趸售电费计算总表的数据访问对象基类<br>
 */
public class DBLwWholeSaleSummaryBase {
  /** 资源管理类的实例,处理数据库操作. */
  protected DBManager dbManager = null;

  private static Logger logger = Logger.getLogger(DBLwWholeSaleSummaryBase.class);

  /**
   * 构造函数
   *
   * @param dbManager 资源管理类
   */
  public DBLwWholeSaleSummaryBase(DBManager dbManager) {
    this.dbManager = dbManager;
  }

  /**
   * 插入一条数据
   *
   * @param lwWholeSaleSummaryDto lwWholeSaleSummaryDto
   * @throws Exception
   */
  public void insert(LwWholeSaleSummaryDto lwWholeSaleSummaryDto) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    buffer.append("INSERT INTO LwWholeSaleSummary (");
    buffer.append("LineCode,");
    buffer.append("StatMonth,");
    buffer.append("PowerClass,");
    buffer.append("ElectricQuantity,");
    buffer.append("PointerQuantity,");
    buffer.append("SanXiaFee,");
    buffer.append("Surcharge,");
    buffer.append("SumFee,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark,");
    buffer.append("TransLoss,");
    buffer.append("LineLoss,");
    buffer.append("UnPointerQuantity,");
    buffer.append("RateCode,");
    buffer.append("AdjustRate,");
    buffer.append("FarmUseScale,");
    buffer.append("FarmUsePrice,");
    buffer.append("FarmUseQuantity,");
    buffer.append("FarmUseFee,");
    buffer.append("ProductScale,");
    buffer.append("ProductPrice,");
    buffer.append("ProductQuantity,");
    buffer.append("ProductFee,");
    buffer.append("DenizenScale,");
    buffer.append("DenizenPrice,");
    buffer.append("DenizenQuantity,");
    buffer.append("DenizenFee,");
    buffer.append("UnDenizenScale,");
    buffer.append("UnDenizenPrice,");
    buffer.append("UnDenizenQuantity,");
    buffer.append("UnDenizenFee,");
    buffer.append("IndustryScale,");
    buffer.append("IndustryPrice,");
    buffer.append("IndustryQuantity,");
    buffer.append("IndustryFee,");
    buffer.append("BizScale,");
    buffer.append("BizPrice,");
    buffer.append("BizQuantity,");
    buffer.append("BizFee,");
    buffer.append("PowerRateFee,");
    buffer.append("UpCompany,");
    buffer.append("PowerFee,");
    buffer.append("InputDate,");
    buffer.append("Kv,");
    buffer.append("Wholesaletype,");
    buffer.append("WorkNum,");
    buffer.append("UnWorkNum,");
    buffer.append("OtherSurcharge,");
    buffer.append("DifferenceQuantity,");
    buffer.append("UnTransLoss,");
    buffer.append("UnLineLoss ");
    buffer.append(") ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append(buffer.toString());
      debugBuffer.append("VALUES(");
      debugBuffer.append("'").append(lwWholeSaleSummaryDto.getLineCode()).append("',");
      debugBuffer.append("'").append(lwWholeSaleSummaryDto.getStatMonth()).append("',");
      debugBuffer.append("'").append(lwWholeSaleSummaryDto.getPowerClass()).append("',");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getElectricQuantity()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getPointerQuantity()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getSanXiaFee()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getSurcharge()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getSumFee()).append(",");
      debugBuffer.append("'").append(lwWholeSaleSummaryDto.getValidStatus()).append("',");
      debugBuffer.append("'").append(lwWholeSaleSummaryDto.getFlag()).append("',");
      debugBuffer.append("'").append(lwWholeSaleSummaryDto.getRemark()).append("',");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getTransLoss()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getLineLoss()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getUnPointerQuantity()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getRateCode()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getAdjustRate()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getFarmUseScale()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getFarmUsePrice()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getFarmUseQuantity()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getFarmUseFee()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getProductScale()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getProductPrice()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getProductQuantity()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getProductFee()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getDenizenScale()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getDenizenPrice()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getDenizenQuantity()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getDenizenFee()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getUnDenizenScale()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getUnDenizenPrice()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getUnDenizenQuantity()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getUnDenizenFee()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getIndustryScale()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getIndustryPrice()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getIndustryQuantity()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getIndustryFee()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getBizScale()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getBizPrice()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getBizQuantity()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getBizFee()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getPowerRateFee()).append(",");
      debugBuffer.append("'").append(lwWholeSaleSummaryDto.getUpCompany()).append("',");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getPowerFee()).append(",");
      debugBuffer.append("'").append(lwWholeSaleSummaryDto.getInputDate()).append("',");
      debugBuffer.append("'").append(lwWholeSaleSummaryDto.getKv()).append("',");
      debugBuffer.append("'").append(lwWholeSaleSummaryDto.getWholesaletype()).append("',");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getWorkNum()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getUnWorkNum()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getOtherSurcharge()).append(",");
      debugBuffer.append("'").append(lwWholeSaleSummaryDto.getDifferenceQuantity()).append("',");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getUnTransLoss()).append(",");
      debugBuffer.append("").append(lwWholeSaleSummaryDto.getUnLineLoss()).append(")");
      logger.debug(debugBuffer.toString());
    }

    buffer.append(
        "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
    dbManager.prepareStatement(buffer.toString());
    dbManager.setString(1, lwWholeSaleSummaryDto.getLineCode());
    dbManager.setString(2, lwWholeSaleSummaryDto.getStatMonth());
    dbManager.setString(3, lwWholeSaleSummaryDto.getPowerClass());
    dbManager.setDouble(4, lwWholeSaleSummaryDto.getElectricQuantity());
    dbManager.setDouble(5, lwWholeSaleSummaryDto.getPointerQuantity());
    dbManager.setDouble(6, lwWholeSaleSummaryDto.getSanXiaFee());
    dbManager.setDouble(7, lwWholeSaleSummaryDto.getSurcharge());
    dbManager.setDouble(8, lwWholeSaleSummaryDto.getSumFee());
    dbManager.setString(9, lwWholeSaleSummaryDto.getValidStatus());
    dbManager.setString(10, lwWholeSaleSummaryDto.getFlag());
    dbManager.setString(11, lwWholeSaleSummaryDto.getRemark());
    dbManager.setDouble(12, lwWholeSaleSummaryDto.getTransLoss());
    dbManager.setDouble(13, lwWholeSaleSummaryDto.getLineLoss());
    dbManager.setDouble(14, lwWholeSaleSummaryDto.getUnPointerQuantity());
    dbManager.setDouble(15, lwWholeSaleSummaryDto.getRateCode());
    dbManager.setDouble(16, lwWholeSaleSummaryDto.getAdjustRate());
    dbManager.setDouble(17, lwWholeSaleSummaryDto.getFarmUseScale());
    dbManager.setDouble(18, lwWholeSaleSummaryDto.getFarmUsePrice());
    dbManager.setDouble(19, lwWholeSaleSummaryDto.getFarmUseQuantity());
    dbManager.setDouble(20, lwWholeSaleSummaryDto.getFarmUseFee());
    dbManager.setDouble(21, lwWholeSaleSummaryDto.getProductScale());
    dbManager.setDouble(22, lwWholeSaleSummaryDto.getProductPrice());
    dbManager.setDouble(23, lwWholeSaleSummaryDto.getProductQuantity());
    dbManager.setDouble(24, lwWholeSaleSummaryDto.getProductFee());
    dbManager.setDouble(25, lwWholeSaleSummaryDto.getDenizenScale());
    dbManager.setDouble(26, lwWholeSaleSummaryDto.getDenizenPrice());
    dbManager.setDouble(27, lwWholeSaleSummaryDto.getDenizenQuantity());
    dbManager.setDouble(28, lwWholeSaleSummaryDto.getDenizenFee());
    dbManager.setDouble(29, lwWholeSaleSummaryDto.getUnDenizenScale());
    dbManager.setDouble(30, lwWholeSaleSummaryDto.getUnDenizenPrice());
    dbManager.setDouble(31, lwWholeSaleSummaryDto.getUnDenizenQuantity());
    dbManager.setDouble(32, lwWholeSaleSummaryDto.getUnDenizenFee());
    dbManager.setDouble(33, lwWholeSaleSummaryDto.getIndustryScale());
    dbManager.setDouble(34, lwWholeSaleSummaryDto.getIndustryPrice());
    dbManager.setDouble(35, lwWholeSaleSummaryDto.getIndustryQuantity());
    dbManager.setDouble(36, lwWholeSaleSummaryDto.getIndustryFee());
    dbManager.setDouble(37, lwWholeSaleSummaryDto.getBizScale());
    dbManager.setDouble(38, lwWholeSaleSummaryDto.getBizPrice());
    dbManager.setDouble(39, lwWholeSaleSummaryDto.getBizQuantity());
    dbManager.setDouble(40, lwWholeSaleSummaryDto.getBizFee());
    dbManager.setDouble(41, lwWholeSaleSummaryDto.getPowerRateFee());
    dbManager.setString(42, lwWholeSaleSummaryDto.getUpCompany());
    dbManager.setDouble(43, lwWholeSaleSummaryDto.getPowerFee());
    dbManager.setString(44, lwWholeSaleSummaryDto.getInputDate());
    dbManager.setString(45, lwWholeSaleSummaryDto.getKv());
    dbManager.setString(46, lwWholeSaleSummaryDto.getWholesaletype());
    dbManager.setDouble(47, lwWholeSaleSummaryDto.getWorkNum());
    dbManager.setDouble(48, lwWholeSaleSummaryDto.getUnWorkNum());
    dbManager.setDouble(49, lwWholeSaleSummaryDto.getOtherSurcharge());
    dbManager.setString(50, lwWholeSaleSummaryDto.getDifferenceQuantity());
    dbManager.setDouble(51, lwWholeSaleSummaryDto.getUnTransLoss());
    dbManager.setDouble(52, lwWholeSaleSummaryDto.getUnLineLoss());
    dbManager.executePreparedUpdate();
  }

  /**
   * 采用批方式插入多条数据
   *
   * @param collection collection
   * @throws Exception
   */
  public void insertAll(Collection collection) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    buffer.append("INSERT INTO LwWholeSaleSummary (");
    buffer.append("LineCode,");
    buffer.append("StatMonth,");
    buffer.append("PowerClass,");
    buffer.append("ElectricQuantity,");
    buffer.append("PointerQuantity,");
    buffer.append("SanXiaFee,");
    buffer.append("Surcharge,");
    buffer.append("SumFee,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark,");
    buffer.append("TransLoss,");
    buffer.append("LineLoss,");
    buffer.append("UnPointerQuantity,");
    buffer.append("RateCode,");
    buffer.append("AdjustRate,");
    buffer.append("FarmUseScale,");
    buffer.append("FarmUsePrice,");
    buffer.append("FarmUseQuantity,");
    buffer.append("FarmUseFee,");
    buffer.append("ProductScale,");
    buffer.append("ProductPrice,");
    buffer.append("ProductQuantity,");
    buffer.append("ProductFee,");
    buffer.append("DenizenScale,");
    buffer.append("DenizenPrice,");
    buffer.append("DenizenQuantity,");
    buffer.append("DenizenFee,");
    buffer.append("UnDenizenScale,");
    buffer.append("UnDenizenPrice,");
    buffer.append("UnDenizenQuantity,");
    buffer.append("UnDenizenFee,");
    buffer.append("IndustryScale,");
    buffer.append("IndustryPrice,");
    buffer.append("IndustryQuantity,");
    buffer.append("IndustryFee,");
    buffer.append("BizScale,");
    buffer.append("BizPrice,");
    buffer.append("BizQuantity,");
    buffer.append("BizFee,");
    buffer.append("PowerRateFee,");
    buffer.append("UpCompany,");
    buffer.append("PowerFee,");
    buffer.append("InputDate,");
    buffer.append("Kv,");
    buffer.append("Wholesaletype,");
    buffer.append("WorkNum,");
    buffer.append("UnWorkNum,");
    buffer.append("OtherSurcharge,");
    buffer.append("DifferenceQuantity,");
    buffer.append("UnTransLoss,");
    buffer.append("UnLineLoss ");
    buffer.append(") ");
    buffer.append(
        "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
    if (logger.isDebugEnabled()) {
      logger.debug(buffer.toString());
    }
    dbManager.prepareStatement(buffer.toString());
    for (Iterator i = collection.iterator(); i.hasNext(); ) {
      LwWholeSaleSummaryDto lwWholeSaleSummaryDto = (LwWholeSaleSummaryDto) i.next();
      dbManager.setString(1, lwWholeSaleSummaryDto.getLineCode());
      dbManager.setString(2, lwWholeSaleSummaryDto.getStatMonth());
      dbManager.setString(3, lwWholeSaleSummaryDto.getPowerClass());
      dbManager.setDouble(4, lwWholeSaleSummaryDto.getElectricQuantity());
      dbManager.setDouble(5, lwWholeSaleSummaryDto.getPointerQuantity());
      dbManager.setDouble(6, lwWholeSaleSummaryDto.getSanXiaFee());
      dbManager.setDouble(7, lwWholeSaleSummaryDto.getSurcharge());
      dbManager.setDouble(8, lwWholeSaleSummaryDto.getSumFee());
      dbManager.setString(9, lwWholeSaleSummaryDto.getValidStatus());
      dbManager.setString(10, lwWholeSaleSummaryDto.getFlag());
      dbManager.setString(11, lwWholeSaleSummaryDto.getRemark());
      dbManager.setDouble(12, lwWholeSaleSummaryDto.getTransLoss());
      dbManager.setDouble(13, lwWholeSaleSummaryDto.getLineLoss());
      dbManager.setDouble(14, lwWholeSaleSummaryDto.getUnPointerQuantity());
      dbManager.setDouble(15, lwWholeSaleSummaryDto.getRateCode());
      dbManager.setDouble(16, lwWholeSaleSummaryDto.getAdjustRate());
      dbManager.setDouble(17, lwWholeSaleSummaryDto.getFarmUseScale());
      dbManager.setDouble(18, lwWholeSaleSummaryDto.getFarmUsePrice());
      dbManager.setDouble(19, lwWholeSaleSummaryDto.getFarmUseQuantity());
      dbManager.setDouble(20, lwWholeSaleSummaryDto.getFarmUseFee());
      dbManager.setDouble(21, lwWholeSaleSummaryDto.getProductScale());
      dbManager.setDouble(22, lwWholeSaleSummaryDto.getProductPrice());
      dbManager.setDouble(23, lwWholeSaleSummaryDto.getProductQuantity());
      dbManager.setDouble(24, lwWholeSaleSummaryDto.getProductFee());
      dbManager.setDouble(25, lwWholeSaleSummaryDto.getDenizenScale());
      dbManager.setDouble(26, lwWholeSaleSummaryDto.getDenizenPrice());
      dbManager.setDouble(27, lwWholeSaleSummaryDto.getDenizenQuantity());
      dbManager.setDouble(28, lwWholeSaleSummaryDto.getDenizenFee());
      dbManager.setDouble(29, lwWholeSaleSummaryDto.getUnDenizenScale());
      dbManager.setDouble(30, lwWholeSaleSummaryDto.getUnDenizenPrice());
      dbManager.setDouble(31, lwWholeSaleSummaryDto.getUnDenizenQuantity());
      dbManager.setDouble(32, lwWholeSaleSummaryDto.getUnDenizenFee());
      dbManager.setDouble(33, lwWholeSaleSummaryDto.getIndustryScale());
      dbManager.setDouble(34, lwWholeSaleSummaryDto.getIndustryPrice());
      dbManager.setDouble(35, lwWholeSaleSummaryDto.getIndustryQuantity());
      dbManager.setDouble(36, lwWholeSaleSummaryDto.getIndustryFee());
      dbManager.setDouble(37, lwWholeSaleSummaryDto.getBizScale());
      dbManager.setDouble(38, lwWholeSaleSummaryDto.getBizPrice());
      dbManager.setDouble(39, lwWholeSaleSummaryDto.getBizQuantity());
      dbManager.setDouble(40, lwWholeSaleSummaryDto.getBizFee());
      dbManager.setDouble(41, lwWholeSaleSummaryDto.getPowerRateFee());
      dbManager.setString(42, lwWholeSaleSummaryDto.getUpCompany());
      dbManager.setDouble(43, lwWholeSaleSummaryDto.getPowerFee());
      dbManager.setString(44, lwWholeSaleSummaryDto.getInputDate());
      dbManager.setString(45, lwWholeSaleSummaryDto.getKv());
      dbManager.setString(46, lwWholeSaleSummaryDto.getWholesaletype());
      dbManager.setDouble(47, lwWholeSaleSummaryDto.getWorkNum());
      dbManager.setDouble(48, lwWholeSaleSummaryDto.getUnWorkNum());
      dbManager.setDouble(49, lwWholeSaleSummaryDto.getOtherSurcharge());
      dbManager.setString(50, lwWholeSaleSummaryDto.getDifferenceQuantity());
      dbManager.setDouble(51, lwWholeSaleSummaryDto.getUnTransLoss());
      dbManager.setDouble(52, lwWholeSaleSummaryDto.getUnLineLoss());
      dbManager.addBatch();
    }
    dbManager.executePreparedUpdateBatch();
  }

  /**
   * 按主键删除一条数据
   *
   * @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();
  }

  /**
   * 按主键更新一条数据(主键本身无法变更)
   *
   * @param lwWholeSaleSummaryDto lwWholeSaleSummaryDto
   * @throws Exception
   */
  public void update(LwWholeSaleSummaryDto lwWholeSaleSummaryDto) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    buffer.append("UPDATE LwWholeSaleSummary SET ");
    buffer.append("PowerClass = ?, ");
    buffer.append("ElectricQuantity = ?, ");
    buffer.append("PointerQuantity = ?, ");
    buffer.append("SanXiaFee = ?, ");
    buffer.append("Surcharge = ?, ");
    buffer.append("SumFee = ?, ");
    buffer.append("ValidStatus = ?, ");
    buffer.append("Flag = ?, ");
    buffer.append("Remark = ?, ");
    buffer.append("TransLoss = ?, ");
    buffer.append("LineLoss = ?, ");
    buffer.append("UnPointerQuantity = ?, ");
    buffer.append("RateCode = ?, ");
    buffer.append("AdjustRate = ?, ");
    buffer.append("FarmUseScale = ?, ");
    buffer.append("FarmUsePrice = ?, ");
    buffer.append("FarmUseQuantity = ?, ");
    buffer.append("FarmUseFee = ?, ");
    buffer.append("ProductScale = ?, ");
    buffer.append("ProductPrice = ?, ");
    buffer.append("ProductQuantity = ?, ");
    buffer.append("ProductFee = ?, ");
    buffer.append("DenizenScale = ?, ");
    buffer.append("DenizenPrice = ?, ");
    buffer.append("DenizenQuantity = ?, ");
    buffer.append("DenizenFee = ?, ");
    buffer.append("UnDenizenScale = ?, ");
    buffer.append("UnDenizenPrice = ?, ");
    buffer.append("UnDenizenQuantity = ?, ");
    buffer.append("UnDenizenFee = ?, ");
    buffer.append("IndustryScale = ?, ");
    buffer.append("IndustryPrice = ?, ");
    buffer.append("IndustryQuantity = ?, ");
    buffer.append("IndustryFee = ?, ");
    buffer.append("BizScale = ?, ");
    buffer.append("BizPrice = ?, ");
    buffer.append("BizQuantity = ?, ");
    buffer.append("BizFee = ?, ");
    buffer.append("PowerRateFee = ?, ");
    buffer.append("UpCompany = ?, ");
    buffer.append("PowerFee = ?, ");
    buffer.append("InputDate = ?, ");
    buffer.append("Kv = ?, ");
    buffer.append("Wholesaletype = ?, ");
    buffer.append("WorkNum = ?, ");
    buffer.append("UnWorkNum = ?, ");
    buffer.append("OtherSurcharge = ?, ");
    buffer.append("DifferenceQuantity = ?, ");
    buffer.append("UnTransLoss = ?, ");
    buffer.append("UnLineLoss = ? ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append("UPDATE LwWholeSaleSummary SET ");
      debugBuffer.append("PowerClass = '" + lwWholeSaleSummaryDto.getPowerClass() + "', ");
      debugBuffer.append(
          "ElectricQuantity = " + lwWholeSaleSummaryDto.getElectricQuantity() + ", ");
      debugBuffer.append("PointerQuantity = " + lwWholeSaleSummaryDto.getPointerQuantity() + ", ");
      debugBuffer.append("SanXiaFee = " + lwWholeSaleSummaryDto.getSanXiaFee() + ", ");
      debugBuffer.append("Surcharge = " + lwWholeSaleSummaryDto.getSurcharge() + ", ");
      debugBuffer.append("SumFee = " + lwWholeSaleSummaryDto.getSumFee() + ", ");
      debugBuffer.append("ValidStatus = '" + lwWholeSaleSummaryDto.getValidStatus() + "', ");
      debugBuffer.append("Flag = '" + lwWholeSaleSummaryDto.getFlag() + "', ");
      debugBuffer.append("Remark = '" + lwWholeSaleSummaryDto.getRemark() + "', ");
      debugBuffer.append("TransLoss = " + lwWholeSaleSummaryDto.getTransLoss() + ", ");
      debugBuffer.append("LineLoss = " + lwWholeSaleSummaryDto.getLineLoss() + ", ");
      debugBuffer.append(
          "UnPointerQuantity = " + lwWholeSaleSummaryDto.getUnPointerQuantity() + ", ");
      debugBuffer.append("RateCode = " + lwWholeSaleSummaryDto.getRateCode() + ", ");
      debugBuffer.append("AdjustRate = " + lwWholeSaleSummaryDto.getAdjustRate() + ", ");
      debugBuffer.append("FarmUseScale = " + lwWholeSaleSummaryDto.getFarmUseScale() + ", ");
      debugBuffer.append("FarmUsePrice = " + lwWholeSaleSummaryDto.getFarmUsePrice() + ", ");
      debugBuffer.append("FarmUseQuantity = " + lwWholeSaleSummaryDto.getFarmUseQuantity() + ", ");
      debugBuffer.append("FarmUseFee = " + lwWholeSaleSummaryDto.getFarmUseFee() + ", ");
      debugBuffer.append("ProductScale = " + lwWholeSaleSummaryDto.getProductScale() + ", ");
      debugBuffer.append("ProductPrice = " + lwWholeSaleSummaryDto.getProductPrice() + ", ");
      debugBuffer.append("ProductQuantity = " + lwWholeSaleSummaryDto.getProductQuantity() + ", ");
      debugBuffer.append("ProductFee = " + lwWholeSaleSummaryDto.getProductFee() + ", ");
      debugBuffer.append("DenizenScale = " + lwWholeSaleSummaryDto.getDenizenScale() + ", ");
      debugBuffer.append("DenizenPrice = " + lwWholeSaleSummaryDto.getDenizenPrice() + ", ");
      debugBuffer.append("DenizenQuantity = " + lwWholeSaleSummaryDto.getDenizenQuantity() + ", ");
      debugBuffer.append("DenizenFee = " + lwWholeSaleSummaryDto.getDenizenFee() + ", ");
      debugBuffer.append("UnDenizenScale = " + lwWholeSaleSummaryDto.getUnDenizenScale() + ", ");
      debugBuffer.append("UnDenizenPrice = " + lwWholeSaleSummaryDto.getUnDenizenPrice() + ", ");
      debugBuffer.append(
          "UnDenizenQuantity = " + lwWholeSaleSummaryDto.getUnDenizenQuantity() + ", ");
      debugBuffer.append("UnDenizenFee = " + lwWholeSaleSummaryDto.getUnDenizenFee() + ", ");
      debugBuffer.append("IndustryScale = " + lwWholeSaleSummaryDto.getIndustryScale() + ", ");
      debugBuffer.append("IndustryPrice = " + lwWholeSaleSummaryDto.getIndustryPrice() + ", ");
      debugBuffer.append(
          "IndustryQuantity = " + lwWholeSaleSummaryDto.getIndustryQuantity() + ", ");
      debugBuffer.append("IndustryFee = " + lwWholeSaleSummaryDto.getIndustryFee() + ", ");
      debugBuffer.append("BizScale = " + lwWholeSaleSummaryDto.getBizScale() + ", ");
      debugBuffer.append("BizPrice = " + lwWholeSaleSummaryDto.getBizPrice() + ", ");
      debugBuffer.append("BizQuantity = " + lwWholeSaleSummaryDto.getBizQuantity() + ", ");
      debugBuffer.append("BizFee = " + lwWholeSaleSummaryDto.getBizFee() + ", ");
      debugBuffer.append("PowerRateFee = " + lwWholeSaleSummaryDto.getPowerRateFee() + ", ");
      debugBuffer.append("UpCompany = '" + lwWholeSaleSummaryDto.getUpCompany() + "', ");
      debugBuffer.append("PowerFee = " + lwWholeSaleSummaryDto.getPowerFee() + ", ");
      debugBuffer.append("InputDate = '" + lwWholeSaleSummaryDto.getInputDate() + "', ");
      debugBuffer.append("Kv = '" + lwWholeSaleSummaryDto.getKv() + "', ");
      debugBuffer.append("Wholesaletype = '" + lwWholeSaleSummaryDto.getWholesaletype() + "', ");
      debugBuffer.append("WorkNum = " + lwWholeSaleSummaryDto.getWorkNum() + ", ");
      debugBuffer.append("UnWorkNum = " + lwWholeSaleSummaryDto.getUnWorkNum() + ", ");
      debugBuffer.append("OtherSurcharge = " + lwWholeSaleSummaryDto.getOtherSurcharge() + ", ");
      debugBuffer.append(
          "DifferenceQuantity = '" + lwWholeSaleSummaryDto.getDifferenceQuantity() + "', ");
      debugBuffer.append("UnTransLoss = " + lwWholeSaleSummaryDto.getUnTransLoss() + ", ");
      debugBuffer.append("UnLineLoss = " + lwWholeSaleSummaryDto.getUnLineLoss() + " ");
      debugBuffer.append("WHERE ");
      debugBuffer
          .append("LineCode=")
          .append("'")
          .append(lwWholeSaleSummaryDto.getLineCode())
          .append("' AND ");
      debugBuffer
          .append("StatMonth=")
          .append("'")
          .append(lwWholeSaleSummaryDto.getStatMonth())
          .append("'");
      logger.debug(debugBuffer.toString());
    }

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

    dbManager.prepareStatement(buffer.toString());
    // 设置更新字段;
    dbManager.setString(1, lwWholeSaleSummaryDto.getPowerClass());
    dbManager.setDouble(2, lwWholeSaleSummaryDto.getElectricQuantity());
    dbManager.setDouble(3, lwWholeSaleSummaryDto.getPointerQuantity());
    dbManager.setDouble(4, lwWholeSaleSummaryDto.getSanXiaFee());
    dbManager.setDouble(5, lwWholeSaleSummaryDto.getSurcharge());
    dbManager.setDouble(6, lwWholeSaleSummaryDto.getSumFee());
    dbManager.setString(7, lwWholeSaleSummaryDto.getValidStatus());
    dbManager.setString(8, lwWholeSaleSummaryDto.getFlag());
    dbManager.setString(9, lwWholeSaleSummaryDto.getRemark());
    dbManager.setDouble(10, lwWholeSaleSummaryDto.getTransLoss());
    dbManager.setDouble(11, lwWholeSaleSummaryDto.getLineLoss());
    dbManager.setDouble(12, lwWholeSaleSummaryDto.getUnPointerQuantity());
    dbManager.setDouble(13, lwWholeSaleSummaryDto.getRateCode());
    dbManager.setDouble(14, lwWholeSaleSummaryDto.getAdjustRate());
    dbManager.setDouble(15, lwWholeSaleSummaryDto.getFarmUseScale());
    dbManager.setDouble(16, lwWholeSaleSummaryDto.getFarmUsePrice());
    dbManager.setDouble(17, lwWholeSaleSummaryDto.getFarmUseQuantity());
    dbManager.setDouble(18, lwWholeSaleSummaryDto.getFarmUseFee());
    dbManager.setDouble(19, lwWholeSaleSummaryDto.getProductScale());
    dbManager.setDouble(20, lwWholeSaleSummaryDto.getProductPrice());
    dbManager.setDouble(21, lwWholeSaleSummaryDto.getProductQuantity());
    dbManager.setDouble(22, lwWholeSaleSummaryDto.getProductFee());
    dbManager.setDouble(23, lwWholeSaleSummaryDto.getDenizenScale());
    dbManager.setDouble(24, lwWholeSaleSummaryDto.getDenizenPrice());
    dbManager.setDouble(25, lwWholeSaleSummaryDto.getDenizenQuantity());
    dbManager.setDouble(26, lwWholeSaleSummaryDto.getDenizenFee());
    dbManager.setDouble(27, lwWholeSaleSummaryDto.getUnDenizenScale());
    dbManager.setDouble(28, lwWholeSaleSummaryDto.getUnDenizenPrice());
    dbManager.setDouble(29, lwWholeSaleSummaryDto.getUnDenizenQuantity());
    dbManager.setDouble(30, lwWholeSaleSummaryDto.getUnDenizenFee());
    dbManager.setDouble(31, lwWholeSaleSummaryDto.getIndustryScale());
    dbManager.setDouble(32, lwWholeSaleSummaryDto.getIndustryPrice());
    dbManager.setDouble(33, lwWholeSaleSummaryDto.getIndustryQuantity());
    dbManager.setDouble(34, lwWholeSaleSummaryDto.getIndustryFee());
    dbManager.setDouble(35, lwWholeSaleSummaryDto.getBizScale());
    dbManager.setDouble(36, lwWholeSaleSummaryDto.getBizPrice());
    dbManager.setDouble(37, lwWholeSaleSummaryDto.getBizQuantity());
    dbManager.setDouble(38, lwWholeSaleSummaryDto.getBizFee());
    dbManager.setDouble(39, lwWholeSaleSummaryDto.getPowerRateFee());
    dbManager.setString(40, lwWholeSaleSummaryDto.getUpCompany());
    dbManager.setDouble(41, lwWholeSaleSummaryDto.getPowerFee());
    dbManager.setString(42, lwWholeSaleSummaryDto.getInputDate());
    dbManager.setString(43, lwWholeSaleSummaryDto.getKv());
    dbManager.setString(44, lwWholeSaleSummaryDto.getWholesaletype());
    dbManager.setDouble(45, lwWholeSaleSummaryDto.getWorkNum());
    dbManager.setDouble(46, lwWholeSaleSummaryDto.getUnWorkNum());
    dbManager.setDouble(47, lwWholeSaleSummaryDto.getOtherSurcharge());
    dbManager.setString(48, lwWholeSaleSummaryDto.getDifferenceQuantity());
    dbManager.setDouble(49, lwWholeSaleSummaryDto.getUnTransLoss());
    dbManager.setDouble(50, lwWholeSaleSummaryDto.getUnLineLoss());
    // 设置条件字段;
    dbManager.setString(51, lwWholeSaleSummaryDto.getLineCode());
    dbManager.setString(52, lwWholeSaleSummaryDto.getStatMonth());
    dbManager.executePreparedUpdate();
  }

  /**
   * 按主键查找一条数据
   *
   * @param lineCode 线路代码
   * @param statMonth 统计年月
   * @return LwWholeSaleSummaryDto
   * @throws Exception
   */
  public LwWholeSaleSummaryDto findByPrimaryKey(String lineCode, String statMonth)
      throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    // 拼SQL语句
    buffer.append("SELECT ");
    buffer.append("LineCode,");
    buffer.append("StatMonth,");
    buffer.append("PowerClass,");
    buffer.append("ElectricQuantity,");
    buffer.append("PointerQuantity,");
    buffer.append("SanXiaFee,");
    buffer.append("Surcharge,");
    buffer.append("SumFee,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark,");
    buffer.append("TransLoss,");
    buffer.append("LineLoss,");
    buffer.append("UnPointerQuantity,");
    buffer.append("RateCode,");
    buffer.append("AdjustRate,");
    buffer.append("FarmUseScale,");
    buffer.append("FarmUsePrice,");
    buffer.append("FarmUseQuantity,");
    buffer.append("FarmUseFee,");
    buffer.append("ProductScale,");
    buffer.append("ProductPrice,");
    buffer.append("ProductQuantity,");
    buffer.append("ProductFee,");
    buffer.append("DenizenScale,");
    buffer.append("DenizenPrice,");
    buffer.append("DenizenQuantity,");
    buffer.append("DenizenFee,");
    buffer.append("UnDenizenScale,");
    buffer.append("UnDenizenPrice,");
    buffer.append("UnDenizenQuantity,");
    buffer.append("UnDenizenFee,");
    buffer.append("IndustryScale,");
    buffer.append("IndustryPrice,");
    buffer.append("IndustryQuantity,");
    buffer.append("IndustryFee,");
    buffer.append("BizScale,");
    buffer.append("BizPrice,");
    buffer.append("BizQuantity,");
    buffer.append("BizFee,");
    buffer.append("PowerRateFee,");
    buffer.append("UpCompany,");
    buffer.append("PowerFee,");
    buffer.append("InputDate,");
    buffer.append("Kv,");
    buffer.append("Wholesaletype,");
    buffer.append("WorkNum,");
    buffer.append("UnWorkNum,");
    buffer.append("OtherSurcharge,");
    buffer.append("DifferenceQuantity,");
    buffer.append("UnTransLoss,");
    buffer.append("UnLineLoss ");
    buffer.append("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);
    ResultSet resultSet = dbManager.executePreparedQuery();
    LwWholeSaleSummaryDto lwWholeSaleSummaryDto = null;
    if (resultSet.next()) {
      lwWholeSaleSummaryDto = new LwWholeSaleSummaryDto();
      lwWholeSaleSummaryDto.setLineCode(dbManager.getString(resultSet, 1));
      lwWholeSaleSummaryDto.setStatMonth(dbManager.getString(resultSet, 2));
      lwWholeSaleSummaryDto.setPowerClass(dbManager.getString(resultSet, 3));
      lwWholeSaleSummaryDto.setElectricQuantity(dbManager.getDouble(resultSet, 4));
      lwWholeSaleSummaryDto.setPointerQuantity(dbManager.getDouble(resultSet, 5));
      lwWholeSaleSummaryDto.setSanXiaFee(dbManager.getDouble(resultSet, 6));
      lwWholeSaleSummaryDto.setSurcharge(dbManager.getDouble(resultSet, 7));
      lwWholeSaleSummaryDto.setSumFee(dbManager.getDouble(resultSet, 8));
      lwWholeSaleSummaryDto.setValidStatus(dbManager.getString(resultSet, 9));
      lwWholeSaleSummaryDto.setFlag(dbManager.getString(resultSet, 10));
      lwWholeSaleSummaryDto.setRemark(dbManager.getString(resultSet, 11));
      lwWholeSaleSummaryDto.setTransLoss(dbManager.getDouble(resultSet, 12));
      lwWholeSaleSummaryDto.setLineLoss(dbManager.getDouble(resultSet, 13));
      lwWholeSaleSummaryDto.setUnPointerQuantity(dbManager.getDouble(resultSet, 14));
      lwWholeSaleSummaryDto.setRateCode(dbManager.getDouble(resultSet, 15));
      lwWholeSaleSummaryDto.setAdjustRate(dbManager.getDouble(resultSet, 16));
      lwWholeSaleSummaryDto.setFarmUseScale(dbManager.getDouble(resultSet, 17));
      lwWholeSaleSummaryDto.setFarmUsePrice(dbManager.getDouble(resultSet, 18));
      lwWholeSaleSummaryDto.setFarmUseQuantity(dbManager.getDouble(resultSet, 19));
      lwWholeSaleSummaryDto.setFarmUseFee(dbManager.getDouble(resultSet, 20));
      lwWholeSaleSummaryDto.setProductScale(dbManager.getDouble(resultSet, 21));
      lwWholeSaleSummaryDto.setProductPrice(dbManager.getDouble(resultSet, 22));
      lwWholeSaleSummaryDto.setProductQuantity(dbManager.getDouble(resultSet, 23));
      lwWholeSaleSummaryDto.setProductFee(dbManager.getDouble(resultSet, 24));
      lwWholeSaleSummaryDto.setDenizenScale(dbManager.getDouble(resultSet, 25));
      lwWholeSaleSummaryDto.setDenizenPrice(dbManager.getDouble(resultSet, 26));
      lwWholeSaleSummaryDto.setDenizenQuantity(dbManager.getDouble(resultSet, 27));
      lwWholeSaleSummaryDto.setDenizenFee(dbManager.getDouble(resultSet, 28));
      lwWholeSaleSummaryDto.setUnDenizenScale(dbManager.getDouble(resultSet, 29));
      lwWholeSaleSummaryDto.setUnDenizenPrice(dbManager.getDouble(resultSet, 30));
      lwWholeSaleSummaryDto.setUnDenizenQuantity(dbManager.getDouble(resultSet, 31));
      lwWholeSaleSummaryDto.setUnDenizenFee(dbManager.getDouble(resultSet, 32));
      lwWholeSaleSummaryDto.setIndustryScale(dbManager.getDouble(resultSet, 33));
      lwWholeSaleSummaryDto.setIndustryPrice(dbManager.getDouble(resultSet, 34));
      lwWholeSaleSummaryDto.setIndustryQuantity(dbManager.getDouble(resultSet, 35));
      lwWholeSaleSummaryDto.setIndustryFee(dbManager.getDouble(resultSet, 36));
      lwWholeSaleSummaryDto.setBizScale(dbManager.getDouble(resultSet, 37));
      lwWholeSaleSummaryDto.setBizPrice(dbManager.getDouble(resultSet, 38));
      lwWholeSaleSummaryDto.setBizQuantity(dbManager.getDouble(resultSet, 39));
      lwWholeSaleSummaryDto.setBizFee(dbManager.getDouble(resultSet, 40));
      lwWholeSaleSummaryDto.setPowerRateFee(dbManager.getDouble(resultSet, 41));
      lwWholeSaleSummaryDto.setUpCompany(dbManager.getString(resultSet, 42));
      lwWholeSaleSummaryDto.setPowerFee(dbManager.getDouble(resultSet, 43));
      lwWholeSaleSummaryDto.setInputDate(dbManager.getString(resultSet, 44));
      lwWholeSaleSummaryDto.setKv(dbManager.getString(resultSet, 45));
      lwWholeSaleSummaryDto.setWholesaletype(dbManager.getString(resultSet, 46));
      lwWholeSaleSummaryDto.setWorkNum(dbManager.getDouble(resultSet, 47));
      lwWholeSaleSummaryDto.setUnWorkNum(dbManager.getDouble(resultSet, 48));
      lwWholeSaleSummaryDto.setOtherSurcharge(dbManager.getDouble(resultSet, 49));
      lwWholeSaleSummaryDto.setDifferenceQuantity(dbManager.getString(resultSet, 50));
      lwWholeSaleSummaryDto.setUnTransLoss(dbManager.getDouble(resultSet, 51));
      lwWholeSaleSummaryDto.setUnLineLoss(dbManager.getDouble(resultSet, 52));
    }
    resultSet.close();
    return lwWholeSaleSummaryDto;
  }

  /**
   * 按条件查询多条数据
   *
   * @param conditions 查询条件
   * @param pageNo 页号
   * @param rowsPerPage 每页的行数
   * @return Collection
   * @throws Exception
   */
  public Collection findByConditions(String conditions, int pageNo, int rowsPerPage)
      throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    // 拼SQL语句
    buffer.append("SELECT ");
    buffer.append("LineCode,");
    buffer.append("StatMonth,");
    buffer.append("PowerClass,");
    buffer.append("ElectricQuantity,");
    buffer.append("PointerQuantity,");
    buffer.append("SanXiaFee,");
    buffer.append("Surcharge,");
    buffer.append("SumFee,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark,");
    buffer.append("TransLoss,");
    buffer.append("LineLoss,");
    buffer.append("UnPointerQuantity,");
    buffer.append("RateCode,");
    buffer.append("AdjustRate,");
    buffer.append("FarmUseScale,");
    buffer.append("FarmUsePrice,");
    buffer.append("FarmUseQuantity,");
    buffer.append("FarmUseFee,");
    buffer.append("ProductScale,");
    buffer.append("ProductPrice,");
    buffer.append("ProductQuantity,");
    buffer.append("ProductFee,");
    buffer.append("DenizenScale,");
    buffer.append("DenizenPrice,");
    buffer.append("DenizenQuantity,");
    buffer.append("DenizenFee,");
    buffer.append("UnDenizenScale,");
    buffer.append("UnDenizenPrice,");
    buffer.append("UnDenizenQuantity,");
    buffer.append("UnDenizenFee,");
    buffer.append("IndustryScale,");
    buffer.append("IndustryPrice,");
    buffer.append("IndustryQuantity,");
    buffer.append("IndustryFee,");
    buffer.append("BizScale,");
    buffer.append("BizPrice,");
    buffer.append("BizQuantity,");
    buffer.append("BizFee,");
    buffer.append("PowerRateFee,");
    buffer.append("UpCompany,");
    buffer.append("PowerFee,");
    buffer.append("InputDate,");
    buffer.append("Kv,");
    buffer.append("Wholesaletype,");
    buffer.append("WorkNum,");
    buffer.append("UnWorkNum,");
    buffer.append("OtherSurcharge,");
    buffer.append("DifferenceQuantity,");
    buffer.append("UnTransLoss,");
    buffer.append("UnLineLoss ");
    buffer.append("FROM LwWholeSaleSummary WHERE ");
    buffer.append(conditions);
    boolean supportPaging = false; // 数据库是否支持分页
    if (pageNo > 0) {
      // 对Oracle优化
      if (dbManager
          .getConnection()
          .getMetaData()
          .getDatabaseProductName()
          .equalsIgnoreCase("Oracle")) {
        buffer.insert(0, "SELECT * FROM ( SELECT row_.*, rownum rownum_ FROM (");
        buffer.append(
            ") row_ WHERE rownum <= "
                + rowsPerPage * pageNo
                + ") WHERE rownum_ > "
                + rowsPerPage * (pageNo - 1));
        supportPaging = true;
      } else if (dbManager
          .getConnection()
          .getMetaData()
          .getDatabaseProductName()
          .equalsIgnoreCase("DB2")) {
        String sql = buffer.toString();
        buffer.setLength(0);
        buffer.append("select * from ( select rownumber() over(");
        int orderByIndex = sql.toLowerCase().indexOf("order by");
        if (orderByIndex > 0) {
          buffer.append(sql.substring(orderByIndex));
        }
        buffer.append(") as rownumber_,");
        buffer.append(sql.substring(6));
        buffer.append(" ) as temp_ where rownumber_");
        buffer.append(
            " between " + (rowsPerPage * (pageNo - 1) + 1) + " and " + rowsPerPage * pageNo);
        supportPaging = true;
      }
    }
    if (logger.isDebugEnabled()) {
      logger.debug(buffer.toString());
    }
    ResultSet resultSet = dbManager.executeQuery(buffer.toString());
    int count = 0;
    if (supportPaging == false && pageNo > 1) {
      dbManager.locate(resultSet, rowsPerPage * (pageNo - 1));
    }

    // 定义返回结果集合
    Collection collection = new ArrayList(rowsPerPage);
    LwWholeSaleSummaryDto lwWholeSaleSummaryDto = null;
    while (resultSet.next()) {
      if (supportPaging == false && pageNo > 0) {
        count++;
        if (count > rowsPerPage) {
          break;
        }
      }

      lwWholeSaleSummaryDto = new LwWholeSaleSummaryDto();
      lwWholeSaleSummaryDto.setLineCode(dbManager.getString(resultSet, "LineCode"));
      lwWholeSaleSummaryDto.setStatMonth(dbManager.getString(resultSet, "StatMonth"));
      lwWholeSaleSummaryDto.setPowerClass(dbManager.getString(resultSet, "PowerClass"));
      lwWholeSaleSummaryDto.setElectricQuantity(dbManager.getDouble(resultSet, "ElectricQuantity"));
      lwWholeSaleSummaryDto.setPointerQuantity(dbManager.getDouble(resultSet, "PointerQuantity"));
      lwWholeSaleSummaryDto.setSanXiaFee(dbManager.getDouble(resultSet, "SanXiaFee"));
      lwWholeSaleSummaryDto.setSurcharge(dbManager.getDouble(resultSet, "Surcharge"));
      lwWholeSaleSummaryDto.setSumFee(dbManager.getDouble(resultSet, "SumFee"));
      lwWholeSaleSummaryDto.setValidStatus(dbManager.getString(resultSet, "ValidStatus"));
      lwWholeSaleSummaryDto.setFlag(dbManager.getString(resultSet, "Flag"));
      lwWholeSaleSummaryDto.setRemark(dbManager.getString(resultSet, "Remark"));
      lwWholeSaleSummaryDto.setTransLoss(dbManager.getDouble(resultSet, "TransLoss"));
      lwWholeSaleSummaryDto.setLineLoss(dbManager.getDouble(resultSet, "LineLoss"));
      lwWholeSaleSummaryDto.setUnPointerQuantity(
          dbManager.getDouble(resultSet, "UnPointerQuantity"));
      lwWholeSaleSummaryDto.setRateCode(dbManager.getDouble(resultSet, "RateCode"));
      lwWholeSaleSummaryDto.setAdjustRate(dbManager.getDouble(resultSet, "AdjustRate"));
      lwWholeSaleSummaryDto.setFarmUseScale(dbManager.getDouble(resultSet, "FarmUseScale"));
      lwWholeSaleSummaryDto.setFarmUsePrice(dbManager.getDouble(resultSet, "FarmUsePrice"));
      lwWholeSaleSummaryDto.setFarmUseQuantity(dbManager.getDouble(resultSet, "FarmUseQuantity"));
      lwWholeSaleSummaryDto.setFarmUseFee(dbManager.getDouble(resultSet, "FarmUseFee"));
      lwWholeSaleSummaryDto.setProductScale(dbManager.getDouble(resultSet, "ProductScale"));
      lwWholeSaleSummaryDto.setProductPrice(dbManager.getDouble(resultSet, "ProductPrice"));
      lwWholeSaleSummaryDto.setProductQuantity(dbManager.getDouble(resultSet, "ProductQuantity"));
      lwWholeSaleSummaryDto.setProductFee(dbManager.getDouble(resultSet, "ProductFee"));
      lwWholeSaleSummaryDto.setDenizenScale(dbManager.getDouble(resultSet, "DenizenScale"));
      lwWholeSaleSummaryDto.setDenizenPrice(dbManager.getDouble(resultSet, "DenizenPrice"));
      lwWholeSaleSummaryDto.setDenizenQuantity(dbManager.getDouble(resultSet, "DenizenQuantity"));
      lwWholeSaleSummaryDto.setDenizenFee(dbManager.getDouble(resultSet, "DenizenFee"));
      lwWholeSaleSummaryDto.setUnDenizenScale(dbManager.getDouble(resultSet, "UnDenizenScale"));
      lwWholeSaleSummaryDto.setUnDenizenPrice(dbManager.getDouble(resultSet, "UnDenizenPrice"));
      lwWholeSaleSummaryDto.setUnDenizenQuantity(
          dbManager.getDouble(resultSet, "UnDenizenQuantity"));
      lwWholeSaleSummaryDto.setUnDenizenFee(dbManager.getDouble(resultSet, "UnDenizenFee"));
      lwWholeSaleSummaryDto.setIndustryScale(dbManager.getDouble(resultSet, "IndustryScale"));
      lwWholeSaleSummaryDto.setIndustryPrice(dbManager.getDouble(resultSet, "IndustryPrice"));
      lwWholeSaleSummaryDto.setIndustryQuantity(dbManager.getDouble(resultSet, "IndustryQuantity"));
      lwWholeSaleSummaryDto.setIndustryFee(dbManager.getDouble(resultSet, "IndustryFee"));
      lwWholeSaleSummaryDto.setBizScale(dbManager.getDouble(resultSet, "BizScale"));
      lwWholeSaleSummaryDto.setBizPrice(dbManager.getDouble(resultSet, "BizPrice"));
      lwWholeSaleSummaryDto.setBizQuantity(dbManager.getDouble(resultSet, "BizQuantity"));
      lwWholeSaleSummaryDto.setBizFee(dbManager.getDouble(resultSet, "BizFee"));
      lwWholeSaleSummaryDto.setPowerRateFee(dbManager.getDouble(resultSet, "PowerRateFee"));
      lwWholeSaleSummaryDto.setUpCompany(dbManager.getString(resultSet, "UpCompany"));
      lwWholeSaleSummaryDto.setPowerFee(dbManager.getDouble(resultSet, "PowerFee"));
      lwWholeSaleSummaryDto.setInputDate(dbManager.getString(resultSet, "InputDate"));
      lwWholeSaleSummaryDto.setKv(dbManager.getString(resultSet, "Kv"));
      lwWholeSaleSummaryDto.setWholesaletype(dbManager.getString(resultSet, "Wholesaletype"));
      lwWholeSaleSummaryDto.setWorkNum(dbManager.getDouble(resultSet, "WorkNum"));
      lwWholeSaleSummaryDto.setUnWorkNum(dbManager.getDouble(resultSet, "UnWorkNum"));
      lwWholeSaleSummaryDto.setOtherSurcharge(dbManager.getDouble(resultSet, "OtherSurcharge"));
      lwWholeSaleSummaryDto.setDifferenceQuantity(
          dbManager.getString(resultSet, "DifferenceQuantity"));
      lwWholeSaleSummaryDto.setUnTransLoss(dbManager.getDouble(resultSet, "UnTransLoss"));
      lwWholeSaleSummaryDto.setUnLineLoss(dbManager.getDouble(resultSet, "UnLineLoss"));
      collection.add(lwWholeSaleSummaryDto);
    }
    resultSet.close();
    return collection;
  }

  /**
   * 按条件查询多条数据
   *
   * @param conditions 查询条件
   * @return Collection
   * @throws Exception
   */
  public Collection findByConditions(String conditions) throws Exception {
    return findByConditions(conditions, 0, 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;
  }

  /**
   * 查询满足模糊查询条件的记录数
   *
   * @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;
  }
}
Exemplo n.º 6
0
/** Implements the "get status table" command */
public class AddAuConfigure extends AuActivityBase {

  private static String NAME = "AddAuConfigure";
  private static Logger log = Logger.getLogger(NAME);

  public AddAuConfigure() {
    super();
  }

  /**
   * Populate the response body
   *
   * @return true on success
   */
  public boolean doRemoteSetupAndVerification() throws IOException {

    /*
     * Stop if any required parameters are missing (error)
     */
    if (!verifyMinimumParameters()) {
      throw new ResponseException("Missing required parameters");
    }
    /*
     * Initial page setup
     */
    return commandSetup();
  }

  /**
   * Populate the response body
   *
   * @return true on success
   */
  public boolean doCommand() throws IOException {
    Element infoElement;

    /*
     * Return disk space
     */
    infoElement = getXmlUtils().createElement(getResponseRoot(), AP_E_INFO);
    renderDiskXml(infoElement);

    /*
     * No further action if this isn't a create command (success)
     */
    if (!isCreateCommand()) {
      return true;
    }
    /*
     * Stop if any required parameters are missing (error)
     */
    if (!verifyTarget() || !verifyMinimumParameters() || !verifyDefiningParameters()) {
      throw new ResponseException("Missing required parameters");
    }
    /*
     * Create the AU
     */
    if (!commandSetup()) {
      return false;
    }
    return createAu();
  }

  /*
   * "Helpers"
   */

  /**
   * Did the client provide the minimal parameters required?
   *
   * @return true If so
   */
  private boolean verifyMinimumParameters() {
    int count = 0;

    if (!StringUtil.isNullString(getParameter(AP_E_PUBLICATION))) count++;
    if (!StringUtil.isNullString(getParameter(AP_E_CLASSNAME))) count++;
    if (!StringUtil.isNullString(getParameter(AP_E_PLUGIN))) count++;

    return (count > 0);
  }

  /**
   * A target system is required to create an AU - was it provided?
   *
   * @return true If at least one target was specified
   */
  private boolean verifyTarget() {
    if (!isCreateCommand()) {
      return true;
    }

    return !StringUtil.isNullString(getParameter(AP_E_TARGET));
  }

  /**
   * Are all of the "defining parameters" required to create an AU available?
   *
   * @return true If so
   */
  private boolean verifyDefiningParameters() {
    KeyedList parameters;
    int size;

    if (!isCreateCommand()) {
      return true;
    }

    parameters = ParseUtils.getDynamicFields(getXmlUtils(), getRequestDocument(), AP_MD_AUDEFINING);
    size = parameters.size();

    for (int i = 0; i < size; i++) {
      if (StringUtil.isNullString((String) parameters.getValue(i))) {
        return false;
      }
    }
    return true;
  }

  /**
   * "Create" command?
   *
   * @return true If so...
   */
  private boolean isCreateCommand() {
    return "create".equalsIgnoreCase(getParameter(AP_E_ACTION));
  }

  /** Query the daemon for information required to set up this command */
  private boolean commandSetup() {

    Configuration configuration = null;
    Collection noEditKeys = null;
    String key;
    String value;

    /*
     * Configure a well known publication?
     */
    if ((value = getParameter(AP_E_PUBLICATION)) != null) {
      PluginProxy plugin = getTitlePlugin(value);

      /*
       * Set plugin and Title configuration information
       */
      if (plugin == null) {
        String message = "Unknown Publication:" + value;

        log.warning(message);
        return error(message);
      }

      setPlugin(plugin);
      setTitleConfig(plugin.getTitleConfig(value));

      configuration = getTitleConfig().getConfig();
      noEditKeys = getNoEditKeys();

    } else {
      /*
       * Lookup by Plugin or Class name - set the plugin
       *
       * NB: As of 23-Feb-04, this is not supported from AddAuPage.java.  See
       *     AddAuWithCompleteFunctionalityPage.java for full support.
       */
      if ((value = getParameter(AP_E_PLUGIN)) != null) {
        key = RemoteApi.pluginKeyFromId(value);

      } else if ((value = getParameter(AP_E_CLASSNAME)) != null) {
        key = RemoteApi.pluginKeyFromId(value);

      } else {
        return error("Supply a Publication, Plugin, or Class name");
      }

      if (StringUtil.isNullString(key)) {
        return error("Supply a valid Publication, Plugin, or Class name");
      }

      if (!pluginLoaded(key)) {
        return error("Plugin is not loaded: " + key);
      }

      setPlugin(getPluginProxy(key));
    }

    /*
     * Finally, return an XML rendition of the Plugin and AU key set up
     */
    generateSetupXml(configuration, noEditKeys);
    return true;
  }

  /**
   * Create an Archival Unit
   *
   * @return true If successful
   */
  private boolean createAu() {

    Configuration config = getAuConfigFromForm();

    AuProxy au;
    Element element;

    try {
      au = getRemoteApi().createAndSaveAuConfiguration(getPlugin(), config);

    } catch (ArchivalUnit.ConfigurationException exception) {
      return error("Configuration failed: " + exception.getMessage());

    } catch (IOException exception) {
      return error("Unable to save configuration: " + exception.getMessage());
    }
    /*
     * Successful creation - add the AU name and ID to the response document
     */
    element = getXmlUtils().createElement(getResponseRoot(), AP_E_AU);
    XmlUtils.addText(element, au.getName());

    element = getXmlUtils().createElement(getResponseRoot(), AP_E_AUID);
    XmlUtils.addText(element, au.getAuId());

    return true;
  }
}
Exemplo n.º 7
0
/** The Class MappingUtils. */
public class MappingUtils {
  private static Logger _logger = Logger.getLogger(MappingUtils.class);

  private String serviceUrl = null;
  private LexBIGService lbSvc = null;

  public MappingUtils(LexBIGService lbSvc) {
    this.lbSvc = lbSvc;
  }

  public void setServiceUrl(String serviceUrl) {
    this.serviceUrl = serviceUrl;
  }

  public List<MappingSortOption> createMappingSortOption(int sortBy) {
    List<MappingSortOption> list = new ArrayList<MappingSortOption>();
    MappingSortOption option = null;
    QualifierSortOption qualifierOption = null;
    switch (sortBy) {
      case 1:
        option = new MappingSortOption(MappingSortOptionName.SOURCE_CODE, Direction.ASC);
        list.add(option);
        option =
            new MappingSortOption(MappingSortOptionName.SOURCE_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        qualifierOption = new QualifierSortOption(Direction.ASC, "rel");
        list.add(qualifierOption);
        qualifierOption = new QualifierSortOption(Direction.DESC, "score");
        list.add(qualifierOption);
        option = new MappingSortOption(MappingSortOptionName.TARGET_CODE, Direction.ASC);
        list.add(option);
        option =
            new MappingSortOption(MappingSortOptionName.TARGET_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        break;

      case 2:
        option =
            new MappingSortOption(MappingSortOptionName.SOURCE_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        option = new MappingSortOption(MappingSortOptionName.SOURCE_CODE, Direction.ASC);
        list.add(option);
        qualifierOption = new QualifierSortOption(Direction.ASC, "rel");
        list.add(qualifierOption);
        qualifierOption = new QualifierSortOption(Direction.DESC, "score");
        list.add(qualifierOption);
        option = new MappingSortOption(MappingSortOptionName.TARGET_CODE, Direction.ASC);
        list.add(option);
        option =
            new MappingSortOption(MappingSortOptionName.TARGET_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        break;

        // to be modified
      case 3:
        option =
            new MappingSortOption(MappingSortOptionName.SOURCE_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        option = new MappingSortOption(MappingSortOptionName.SOURCE_CODE, Direction.ASC);
        list.add(option);
        qualifierOption = new QualifierSortOption(Direction.ASC, "rel");
        list.add(qualifierOption);
        qualifierOption = new QualifierSortOption(Direction.DESC, "score");
        list.add(qualifierOption);
        option = new MappingSortOption(MappingSortOptionName.TARGET_CODE, Direction.ASC);
        list.add(option);
        option =
            new MappingSortOption(MappingSortOptionName.TARGET_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        break;

      case 4:
        qualifierOption = new QualifierSortOption(Direction.ASC, "rel");
        list.add(qualifierOption);
        qualifierOption = new QualifierSortOption(Direction.DESC, "score");
        list.add(qualifierOption);
        option = new MappingSortOption(MappingSortOptionName.SOURCE_CODE, Direction.ASC);
        list.add(option);
        option =
            new MappingSortOption(MappingSortOptionName.SOURCE_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        option = new MappingSortOption(MappingSortOptionName.TARGET_CODE, Direction.ASC);
        list.add(option);
        option =
            new MappingSortOption(MappingSortOptionName.TARGET_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        break;

      case 5:
        qualifierOption = new QualifierSortOption(Direction.DESC, "score");
        list.add(qualifierOption);
        option = new MappingSortOption(MappingSortOptionName.SOURCE_CODE, Direction.ASC);
        list.add(option);
        option =
            new MappingSortOption(MappingSortOptionName.SOURCE_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        qualifierOption = new QualifierSortOption(Direction.ASC, "rel");
        list.add(qualifierOption);
        option = new MappingSortOption(MappingSortOptionName.TARGET_CODE, Direction.ASC);
        list.add(option);
        option =
            new MappingSortOption(MappingSortOptionName.TARGET_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        break;

      case 6:
        option = new MappingSortOption(MappingSortOptionName.TARGET_CODE, Direction.ASC);
        list.add(option);
        option =
            new MappingSortOption(MappingSortOptionName.TARGET_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        option = new MappingSortOption(MappingSortOptionName.SOURCE_CODE, Direction.ASC);
        list.add(option);
        option =
            new MappingSortOption(MappingSortOptionName.SOURCE_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        qualifierOption = new QualifierSortOption(Direction.ASC, "rel");
        list.add(qualifierOption);
        qualifierOption = new QualifierSortOption(Direction.DESC, "score");
        list.add(qualifierOption);
        break;

      case 7:
        option =
            new MappingSortOption(MappingSortOptionName.TARGET_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        option = new MappingSortOption(MappingSortOptionName.TARGET_CODE, Direction.ASC);
        list.add(option);
        option = new MappingSortOption(MappingSortOptionName.SOURCE_CODE, Direction.ASC);
        list.add(option);
        option =
            new MappingSortOption(MappingSortOptionName.SOURCE_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        qualifierOption = new QualifierSortOption(Direction.ASC, "rel");
        list.add(qualifierOption);
        qualifierOption = new QualifierSortOption(Direction.DESC, "score");
        list.add(qualifierOption);
        break;

        // to be modified
      case 8:
        // option = new MappingSortOption(MappingSortOptionName.TARGET_NAMESPACE, Direction.ASC);
        // list.add(option);
        option =
            new MappingSortOption(MappingSortOptionName.TARGET_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        option = new MappingSortOption(MappingSortOptionName.TARGET_CODE, Direction.ASC);
        list.add(option);
        option = new MappingSortOption(MappingSortOptionName.SOURCE_CODE, Direction.ASC);
        list.add(option);
        option =
            new MappingSortOption(MappingSortOptionName.SOURCE_ENTITY_DESCRIPTION, Direction.ASC);
        list.add(option);
        qualifierOption = new QualifierSortOption(Direction.ASC, "rel");
        list.add(qualifierOption);
        qualifierOption = new QualifierSortOption(Direction.DESC, "score");
        list.add(qualifierOption);
        break;

      default:
        return createMappingSortOption(1);
    }
    return list;
  }

  public ResolvedConceptReferencesIterator getMappingDataIterator(String scheme, String version) {
    return getMappingDataIterator(scheme, version, MappingData.COL_SOURCE_CODE);
  }

  public ResolvedConceptReferencesIterator getMappingDataIterator(
      String scheme, String version, int sortBy) {
    List<MappingSortOption> sortOptionList = createMappingSortOption(sortBy);
    return getMappingDataIterator(scheme, version, sortOptionList);
  }

  public ResolvedConceptReferencesIterator getMappingDataIterator(
      String scheme, String version, List<MappingSortOption> sortOptionList) {
    CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
    if (version != null) {
      versionOrTag.setVersion(version);
    }
    String relationsContainerName = null;
    try {

      CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag);
      if (cs == null) return null;

      java.util.Enumeration<? extends Relations> relations = cs.enumerateRelations();
      while (relations.hasMoreElements()) {
        Relations relation = (Relations) relations.nextElement();
        Boolean isMapping = relation.getIsMapping();
        if (isMapping != null && isMapping.equals(Boolean.TRUE)) {
          relationsContainerName = relation.getContainerName();
          break;
        }
      }
      if (relationsContainerName == null) {
        return null;
      }

      MappingExtension mappingExtension =
          (MappingExtension) lbSvc.getGenericExtension("MappingExtension");

      ResolvedConceptReferencesIterator itr =
          mappingExtension.resolveMapping(
              scheme, versionOrTag, relationsContainerName, sortOptionList);

      return itr;

    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public NameAndValueList getMappingAssociationNames(String scheme, String version) {
    CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
    if (version != null) {
      csvt.setVersion(version);
    }
    NameAndValueList navList = new NameAndValueList();
    try {
      CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
      Relations[] relations = cs.getRelations();
      for (int i = 0; i < relations.length; i++) {
        Relations relation = relations[i];
        Boolean isMapping = relation.isIsMapping();
        if (isMapping != null && isMapping.equals(Boolean.TRUE)) {
          AssociationPredicate[] associationPredicates = relation.getAssociationPredicate();
          for (int j = 0; j < associationPredicates.length; j++) {
            AssociationPredicate associationPredicate = associationPredicates[j];
            String name = associationPredicate.getAssociationName();
            NameAndValue vNameAndValue = new NameAndValue();
            vNameAndValue.setName(name);
            navList.addNameAndValue(vNameAndValue);
          }
          return navList;
        } else {
          return null;
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public Vector getMappingCodingSchemesEntityParticipatesIn(String code, String namespace) {
    Vector v = new Vector();
    try {
      MappingExtension mappingExtension =
          (MappingExtension) lbSvc.getGenericExtension("MappingExtension");

      AbsoluteCodingSchemeVersionReferenceList mappingSchemes =
          mappingExtension.getMappingCodingSchemesEntityParticipatesIn(code, namespace);

      // output is all of the mapping ontologies that this code participates in.
      for (AbsoluteCodingSchemeVersionReference ref :
          mappingSchemes.getAbsoluteCodingSchemeVersionReference()) {
        v.add(ref.getCodingSchemeURN() + "|" + ref.getCodingSchemeVersion());
      }

    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return v;
  }
}
Exemplo n.º 8
0
/**
 * This is a step of the item submission processes. The upload stages allow the user to upload files
 * into the submission. The form is optimized for one file, but allows the user to upload more if
 * needed.
 *
 * <p>The form is broken up into three sections:
 *
 * <p>Part A: Ask the user to upload a file Part B: List previously uploaded files Part C: The
 * standard action bar
 *
 * @author Scott Phillips
 * @author Tim Donohue (updated for Configurable Submission)
 */
public class UploadStep extends AbstractSubmissionStep {
  private static Logger log = Logger.getLogger(UploadStep.class);

  /** Language Strings for Uploading * */
  protected static final Message T_head = message("xmlui.Submission.submit.UploadStep.head");

  protected static final Message T_file = message("xmlui.Submission.submit.UploadStep.file");
  protected static final Message T_file_help =
      message("xmlui.Submission.submit.UploadStep.file_help");
  protected static final Message T_file_error =
      message("xmlui.Submission.submit.UploadStep.file_error");
  protected static final Message T_upload_error =
      message("xmlui.Submission.submit.UploadStep.upload_error");

  protected static final Message T_virus_checker_error =
      message("xmlui.Submission.submit.UploadStep.virus_checker_error");
  protected static final Message T_virus_error =
      message("xmlui.Submission.submit.UploadStep.virus_error");

  protected static final Message T_description =
      message("xmlui.Submission.submit.UploadStep.description");
  protected static final Message T_description_help =
      message("xmlui.Submission.submit.UploadStep.description_help");
  protected static final Message T_submit_upload =
      message("xmlui.Submission.submit.UploadStep.submit_upload");
  protected static final Message T_head2 = message("xmlui.Submission.submit.UploadStep.head2");
  protected static final Message T_column0 = message("xmlui.Submission.submit.UploadStep.column0");
  protected static final Message T_column1 = message("xmlui.Submission.submit.UploadStep.column1");
  protected static final Message T_column2 = message("xmlui.Submission.submit.UploadStep.column2");
  protected static final Message T_column3 = message("xmlui.Submission.submit.UploadStep.column3");
  protected static final Message T_column4 = message("xmlui.Submission.submit.UploadStep.column4");
  protected static final Message T_column5 = message("xmlui.Submission.submit.UploadStep.column5");
  protected static final Message T_column6 = message("xmlui.Submission.submit.UploadStep.column6");
  protected static final Message T_unknown_name =
      message("xmlui.Submission.submit.UploadStep.unknown_name");
  protected static final Message T_unknown_format =
      message("xmlui.Submission.submit.UploadStep.unknown_format");
  protected static final Message T_supported =
      message("xmlui.Submission.submit.UploadStep.supported");
  protected static final Message T_known = message("xmlui.Submission.submit.UploadStep.known");
  protected static final Message T_unsupported =
      message("xmlui.Submission.submit.UploadStep.unsupported");
  protected static final Message T_submit_edit =
      message("xmlui.Submission.submit.UploadStep.submit_edit");
  protected static final Message T_checksum =
      message("xmlui.Submission.submit.UploadStep.checksum");
  protected static final Message T_submit_remove =
      message("xmlui.Submission.submit.UploadStep.submit_remove");
  protected static final Message T_rioxx_version =
      message("xmlui.Submission.submit.UploadStep.rioxx_version");

  protected static final Message T_sherpa_consult =
      message("xmlui.aspect.sherpa.submission.consult");

  protected static final Message T_sherpa_title = message("xmlui.aspect.sherpa.submission.title");

  protected static final Message T_sherpa_journal =
      message("xmlui.aspect.sherpa.submission.journal");

  protected static final Message T_sherpa_publisher =
      message("xmlui.aspect.sherpa.submission.publisher");

  protected static final Message T_sherpa_colour = message("xmlui.aspect.sherpa.submission.colour");

  protected static final Message T_sherpa_more = message("xmlui.aspect.sherpa.submission.more");

  /** Global reference to edit file page (this is used when a user requests to edit a bitstream) */
  private EditFileStep editFile = null;

  /** Establish our required parameters, abstractStep will enforce these. */
  public UploadStep() {
    this.requireSubmission = true;
    this.requireStep = true;
  }

  /** Check if user has requested to edit information about an uploaded file */
  public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters)
      throws ProcessingException, SAXException, IOException {
    super.setup(resolver, objectModel, src, parameters);

    // If this page for editing an uploaded file's information
    // was requested, then we need to load EditFileStep instead!
    if (this.errorFlag == org.dspace.submit.step.UploadStep.STATUS_EDIT_BITSTREAM) {
      this.editFile = new EditFileStep();
      this.editFile.setup(resolver, objectModel, src, parameters);
    } else {
      this.editFile = null;
    }
  }

  public void addBody(Body body)
      throws SAXException, WingException, UIException, SQLException, IOException,
          AuthorizeException {
    // If we are actually editing information of an uploaded file,
    // then display that body instead!
    if (this.editFile != null) {
      editFile.addBody(body);
      return;
    }

    // Get a list of all files in the original bundle
    Item item = submission.getItem();
    Collection collection = submission.getCollection();
    String actionURL =
        contextPath + "/handle/" + collection.getHandle() + "/submit/" + knot.getId() + ".continue";
    boolean disableFileEditing =
        (submissionInfo.isInWorkflow())
            && !ConfigurationManager.getBooleanProperty("workflow", "reviewer.file-edit");
    Bundle[] bundles = item.getBundles("ORIGINAL");
    Bitstream[] bitstreams = new Bitstream[0];
    if (bundles.length > 0) {
      bitstreams = bundles[0].getBitstreams();
    }

    // Part A:
    //  First ask the user if they would like to upload a new file (may be the first one)
    Division div =
        body.addInteractiveDivision(
            "submit-upload", actionURL, Division.METHOD_MULTIPART, "primary submission");
    div.setHead(T_submission_head);
    addSubmissionProgressList(div);

    List upload = null;
    if (!disableFileEditing) {
      // Only add the upload capabilities for new item submissions
      upload = div.addList("submit-upload-new", List.TYPE_FORM);
      upload.setHead(T_head);
      addRioxxVersionSection(upload, item);

      File file = upload.addItem().addFile("file");
      file.setLabel(T_file);
      file.setHelp(T_file_help);
      file.setRequired();

      // if no files found error was thrown by processing class, display it!
      if (this.errorFlag == org.dspace.submit.step.UploadStep.STATUS_NO_FILES_ERROR) {
        file.addError(T_file_error);
      }

      // if an upload error was thrown by processing class, display it!
      if (this.errorFlag == org.dspace.submit.step.UploadStep.STATUS_UPLOAD_ERROR) {
        file.addError(T_upload_error);
      }

      // if virus checking was attempted and failed in error then let the user know
      if (this.errorFlag == org.dspace.submit.step.UploadStep.STATUS_VIRUS_CHECKER_UNAVAILABLE) {
        file.addError(T_virus_checker_error);
      }

      // if virus checking was attempted and a virus found then let the user know
      if (this.errorFlag == org.dspace.submit.step.UploadStep.STATUS_CONTAINS_VIRUS) {
        file.addError(T_virus_error);
      }

      Text description = upload.addItem().addText("description");
      description.setLabel(T_description);
      description.setHelp(T_description_help);

      Button uploadSubmit = upload.addItem().addButton("submit_upload");
      uploadSubmit.setValue(T_submit_upload);
    }

    make_sherpaRomeo_submission(item, div);

    // Part B:
    //  If the user has already uploaded files provide a list for the user.
    if (bitstreams.length > 0 || disableFileEditing) {
      Table summary = div.addTable("submit-upload-summary", (bitstreams.length * 2) + 2, 7);
      summary.setHead(T_head2);

      Row header = summary.addRow(Row.ROLE_HEADER);
      header.addCellContent(T_column0); // primary bitstream
      header.addCellContent(T_column1); // select checkbox
      header.addCellContent(T_column2); // file name
      header.addCellContent(T_column3); // size
      header.addCellContent(T_column4); // description
      header.addCellContent(T_column5); // format
      header.addCellContent(T_column6); // edit button

      for (Bitstream bitstream : bitstreams) {
        int id = bitstream.getID();
        String name = bitstream.getName();
        String url = makeBitstreamLink(item, bitstream);
        long bytes = bitstream.getSize();
        String desc = bitstream.getDescription();
        String algorithm = bitstream.getChecksumAlgorithm();
        String checksum = bitstream.getChecksum();

        Row row = summary.addRow();

        // Add radio-button to select this as the primary bitstream
        Radio primary = row.addCell().addRadio("primary_bitstream_id");
        primary.addOption(String.valueOf(id));

        // If this bitstream is already marked as the primary bitstream
        // mark it as such.
        if (bundles[0].getPrimaryBitstreamID() == id) {
          primary.setOptionSelected(String.valueOf(id));
        }

        if (!disableFileEditing) {
          // Workflow users can not remove files.
          CheckBox remove = row.addCell().addCheckBox("remove");
          remove.setLabel("remove");
          remove.addOption(id);
        } else {
          row.addCell();
        }

        row.addCell().addXref(url, name);
        row.addCellContent(bytes + " bytes");
        if (desc == null || desc.length() == 0) {
          row.addCellContent(T_unknown_name);
        } else {
          row.addCellContent(desc);
        }

        BitstreamFormat format = bitstream.getFormat();
        if (format == null) {
          row.addCellContent(T_unknown_format);
        } else {
          int support = format.getSupportLevel();
          Cell cell = row.addCell();
          cell.addContent(format.getMIMEType());
          cell.addContent(" ");
          switch (support) {
            case 1:
              cell.addContent(T_supported);
              break;
            case 2:
              cell.addContent(T_known);
              break;
            case 3:
              cell.addContent(T_unsupported);
              break;
          }
        }

        Button edit = row.addCell().addButton("submit_edit_" + id);
        edit.setValue(T_submit_edit);

        Row checksumRow = summary.addRow();
        checksumRow.addCell();
        Cell checksumCell = checksumRow.addCell(null, null, 0, 6, null);
        checksumCell.addHighlight("bold").addContent(T_checksum);
        checksumCell.addContent(" ");
        checksumCell.addContent(algorithm + ":" + checksum);
      }

      if (!disableFileEditing) {
        // Workflow users can not remove files.
        Row actionRow = summary.addRow();
        actionRow.addCell();
        Button removeSeleceted =
            actionRow.addCell(null, null, 0, 6, null).addButton("submit_remove_selected");
        removeSeleceted.setValue(T_submit_remove);
      }

      upload = div.addList("submit-upload-new-part2", List.TYPE_FORM);
    }

    // Part C:
    // add standard control/paging buttons
    addControlButtons(upload);
  }

  /** Sherpa romeo submission support */
  public void make_sherpaRomeo_submission(Item item, Division divIn) throws WingException {

    if (ConfigurationManager.getBooleanProperty(
        "webui.submission.sherparomeo-policy-enabled", true)) {

      SHERPASubmitService sherpaSubmitService =
          new DSpace().getSingletonService(SHERPASubmitService.class);

      if (sherpaSubmitService.hasISSNs(context, item)) {
        List div = divIn.addList("submit-upload-new", List.TYPE_FORM);
        div.setHead(T_sherpa_title);

        // Since sherpa web service doesn't work reliable with more than 1 issn, perform the service
        // for each issn
        Set<String> issns = sherpaSubmitService.getISSNs(context, item);
        Iterator<String> issnsIterator = issns.iterator();

        int i = 0;
        while (issnsIterator.hasNext()) {
          SHERPAResponse shresp =
              sherpaSubmitService.searchRelatedJournalsByISSN(issnsIterator.next());
          java.util.List<SHERPAJournal> journals = shresp.getJournals();
          java.util.List<SHERPAPublisher> publishers = shresp.getPublishers();

          if (CollectionUtils.isNotEmpty(journals)) {
            for (SHERPAJournal journ : journals) {
              SHERPAPublisher pub = publishers.get(0);

              List sherpaList = div.addList("sherpaList" + (i + 1), "simple", "sherpaList");
              sherpaList
                  .addItem()
                  .addFigure(
                      contextPath + "/static/images/" + (i == 0 ? "romeosmall" : "clear") + ".gif",
                      "http://www.sherpa.ac.uk/romeo/",
                      "sherpaLogo");

              sherpaList.addItem().addHighlight("sherpaBold").addContent(T_sherpa_journal);
              sherpaList.addItem(journ.getTitle() + " (" + journ.getIssn() + ")");

              sherpaList.addItem().addHighlight("sherpaBold").addContent(T_sherpa_publisher);
              sherpaList.addItemXref(pub.getHomeurl(), pub.getName());

              sherpaList.addItem().addHighlight("sherpaBold").addContent(T_sherpa_colour);
              sherpaList
                  .addItem()
                  .addHighlight("sherpaStyle " + pub.getRomeocolour())
                  .addContent(message("xmlui.aspect.sherpa.submission." + pub.getRomeocolour()));
              sherpaList
                  .addItem()
                  .addXref(
                      "http://www.sherpa.ac.uk/romeo/search.php?issn=" + journ.getIssn(),
                      T_sherpa_more,
                      "sherpaMoreInfo");

              i = i + 1;
            }
          }
        }

        List sherpaList = div.addList("sherpaListEnd", "simple", "sherpaList");
        sherpaList.addItem(T_sherpa_consult);
      }
    }
  }

  /**
   * Each submission step must define its own information to be reviewed during the final
   * Review/Verify Step in the submission process.
   *
   * <p>The information to review should be tacked onto the passed in List object.
   *
   * <p>NOTE: To remain consistent across all Steps, you should first add a sub-List object (with
   * this step's name as the heading), by using a call to reviewList.addList(). This sublist is the
   * list you return from this method!
   *
   * @param reviewList The List to which all reviewable information should be added
   * @return The new sub-List object created by this step, which contains all the reviewable
   *     information. If this step has nothing to review, then return null!
   */
  public List addReviewSection(List reviewList)
      throws SAXException, WingException, UIException, SQLException, IOException,
          AuthorizeException {
    // Create a new list section for this step (and set its heading)
    List uploadSection = reviewList.addList("submit-review-" + this.stepAndPage, List.TYPE_FORM);
    uploadSection.setHead(T_head);

    // Review all uploaded files
    Item item = submission.getItem();
    Bundle[] bundles = item.getBundles("ORIGINAL");
    Bitstream[] bitstreams = new Bitstream[0];
    if (bundles.length > 0) {
      bitstreams = bundles[0].getBitstreams();
    }

    for (Bitstream bitstream : bitstreams) {
      BitstreamFormat bitstreamFormat = bitstream.getFormat();

      String name = bitstream.getName();
      String url = makeBitstreamLink(item, bitstream);
      String format = bitstreamFormat.getShortDescription();
      Message support = ReviewStep.T_unknown;
      if (bitstreamFormat.getSupportLevel() == BitstreamFormat.KNOWN) {
        support = T_known;
      } else if (bitstreamFormat.getSupportLevel() == BitstreamFormat.SUPPORTED) {
        support = T_supported;
      }

      org.dspace.app.xmlui.wing.element.Item file = uploadSection.addItem();
      file.addXref(url, name);
      file.addContent(" - " + format + " ");
      file.addContent(support);
    }

    // return this new "upload" section
    return uploadSection;
  }

  /**
   * Returns canonical link to a bitstream in the item.
   *
   * @param item The DSpace Item that the bitstream is part of
   * @param bitstream The bitstream to link to
   * @returns a String link to the bitstream
   */
  private String makeBitstreamLink(Item item, Bitstream bitstream) {
    String name = bitstream.getName();
    StringBuilder result = new StringBuilder(contextPath);
    result.append("/bitstream/item/").append(String.valueOf(item.getID()));
    // append name although it isn't strictly necessary
    try {
      if (name != null) {
        result.append("/").append(Util.encodeBitstreamName(name, "UTF-8"));
      }
    } catch (UnsupportedEncodingException uee) {
      // just ignore it, we don't have to have a pretty
      // name on the end of the url because the sequence id will
      // locate it. However it means that links in this file might
      // not work....
    }
    result.append("?sequence=").append(String.valueOf(bitstream.getSequenceID()));
    return result.toString();
  }

  public void addRioxxVersionSection(List upload, Item item) throws WingException {
    String version = item.getMetadata("rioxxterms.version");

    if (StringUtils.isNotBlank(version) && !"NA".equals(version)) {
      try {
        DCInputsReader a = new DCInputsReader();
        java.util.List<String> pairs = a.getPairs("rioxxterms_version");
        int humanReadable = pairs.indexOf(version) - 1;
        version = pairs.get(humanReadable);
      } catch (DCInputsReaderException e) {
        log.error(e.getMessage(), e);
      }
      upload
          .addItem("upload-rioxx-version-warning", "upload-rioxx-version-warning")
          .addContent(T_rioxx_version.parameterize(version));
    }
  }
}
Exemplo n.º 9
0
/**
 * ★★★★★警告:本文件不允许手工修改!!!请使用JToolpad生成!<br>
 * 这是LineLoss-线损信息表的数据访问对象基类<br>
 */
public class DBLineLossBase {
  /** 资源管理类的实例,处理数据库操作. */
  protected DBManager dbManager = null;

  private static Logger logger = Logger.getLogger(DBLineLossBase.class);

  /**
   * 构造函数
   *
   * @param dbManager 资源管理类
   */
  public DBLineLossBase(DBManager dbManager) {
    this.dbManager = dbManager;
  }

  /**
   * 插入一条数据
   *
   * @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();
  }

  /**
   * 采用批方式插入多条数据
   *
   * @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();
  }

  /**
   * 按主键删除一条数据
   *
   * @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();
  }

  /**
   * 按主键更新一条数据(主键本身无法变更)
   *
   * @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();
  }

  /**
   * 按主键查找一条数据
   *
   * @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;
  }

  /**
   * 按条件查询多条数据
   *
   * @param conditions 查询条件
   * @param pageNo 页号
   * @param rowsPerPage 每页的行数
   * @return Collection
   * @throws Exception
   */
  public Collection findByConditions(String conditions, int pageNo, int rowsPerPage)
      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 WHERE ");
    buffer.append(conditions);
    boolean supportPaging = false; // 数据库是否支持分页
    if (pageNo > 0) {
      // 对Oracle优化
      if (dbManager
          .getConnection()
          .getMetaData()
          .getDatabaseProductName()
          .equalsIgnoreCase("Oracle")) {
        buffer.insert(0, "SELECT * FROM ( SELECT row_.*, rownum rownum_ FROM (");
        buffer.append(
            ") row_ WHERE rownum <= "
                + rowsPerPage * pageNo
                + ") WHERE rownum_ > "
                + rowsPerPage * (pageNo - 1));
        supportPaging = true;
      } else if (dbManager
          .getConnection()
          .getMetaData()
          .getDatabaseProductName()
          .equalsIgnoreCase("DB2")) {
        String sql = buffer.toString();
        buffer.setLength(0);
        buffer.append("select * from ( select rownumber() over(");
        int orderByIndex = sql.toLowerCase().indexOf("order by");
        if (orderByIndex > 0) {
          buffer.append(sql.substring(orderByIndex));
        }
        buffer.append(") as rownumber_,");
        buffer.append(sql.substring(6));
        buffer.append(" ) as temp_ where rownumber_");
        buffer.append(
            " between " + (rowsPerPage * (pageNo - 1) + 1) + " and " + rowsPerPage * pageNo);
        supportPaging = true;
      }
    }
    if (logger.isDebugEnabled()) {
      logger.debug(buffer.toString());
    }
    ResultSet resultSet = dbManager.executeQuery(buffer.toString());
    int count = 0;
    if (supportPaging == false && pageNo > 1) {
      dbManager.locate(resultSet, rowsPerPage * (pageNo - 1));
    }

    // 定义返回结果集合
    Collection collection = new ArrayList(rowsPerPage);
    LineLossDto lineLossDto = null;
    while (resultSet.next()) {
      if (supportPaging == false && pageNo > 0) {
        count++;
        if (count > rowsPerPage) {
          break;
        }
      }

      lineLossDto = new LineLossDto();
      lineLossDto.setLineCode(dbManager.getString(resultSet, "LineCode"));
      lineLossDto.setR(dbManager.getDouble(resultSet, "R"));
      lineLossDto.setLineLong(dbManager.getDouble(resultSet, "LineLong"));
      lineLossDto.setVolt(dbManager.getDouble(resultSet, "Volt"));
      lineLossDto.setT(dbManager.getDouble(resultSet, "T"));
      lineLossDto.setValidStatus(dbManager.getString(resultSet, "ValidStatus"));
      lineLossDto.setFlag(dbManager.getString(resultSet, "Flag"));
      lineLossDto.setRemark(dbManager.getString(resultSet, "Remark"));
      collection.add(lineLossDto);
    }
    resultSet.close();
    return collection;
  }

  /**
   * 按条件查询多条数据
   *
   * @param conditions 查询条件
   * @return Collection
   * @throws Exception
   */
  public Collection findByConditions(String conditions) throws Exception {
    return findByConditions(conditions, 0, 0);
  }

  /**
   * 按条件删除数据
   *
   * @param conditions 查询条件
   * @return 删除的行数
   * @throws Exception
   */
  public int deleteByConditions(String conditions) throws Exception {
    StringBuffer buffer = new StringBuffer(100);
    buffer.append("DELETE FROM LineLoss WHERE ");
    buffer.append(conditions);
    if (logger.isDebugEnabled()) {
      logger.debug(buffer.toString());
    }
    int count = dbManager.executeUpdate(buffer.toString());
    return count;
  }

  /**
   * 查询满足模糊查询条件的记录数
   *
   * @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 LineLoss 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;
  }
}
Exemplo n.º 10
0
/**
 * ★★★★★警告:本文件不允许手工修改!!!请使用JToolpad生成!<br>
 * 这是LWTownIndicator-直供乡电表指针记录表的数据访问对象基类<br>
 */
public class DBLwTownIndicatorBase {
  /** 资源管理类的实例,处理数据库操作. */
  protected DBManager dbManager = null;

  private static Logger logger = Logger.getLogger(DBLwTownIndicatorBase.class);

  /**
   * 构造函数
   *
   * @param dbManager 资源管理类
   */
  public DBLwTownIndicatorBase(DBManager dbManager) {
    this.dbManager = dbManager;
  }

  /**
   * 插入一条数据
   *
   * @param lwTownIndicatorDto lwTownIndicatorDto
   * @throws Exception
   */
  public void insert(LwTownIndicatorDto lwTownIndicatorDto) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    buffer.append("INSERT INTO LwTownIndicator (");
    buffer.append("UserNo,");
    buffer.append("UserName,");
    buffer.append("Address,");
    buffer.append("ReadDate,");
    buffer.append("StatMonth,");
    buffer.append("ThisWorkNum,");
    buffer.append("MidWorkNum,");
    buffer.append("LastWorkNum,");
    buffer.append("Rate,");
    buffer.append("ReadQuantity,");
    buffer.append("ExcepQuantity,");
    buffer.append("ChgAmmeterQuantity,");
    buffer.append("CompensateQuantity,");
    buffer.append("AppendCalQuantity,");
    buffer.append("TranferLossQuantity,");
    buffer.append("PeoplePrice,");
    buffer.append("NotPeoplePrice,");
    buffer.append("FarmPrice,");
    buffer.append("ProducePrice,");
    buffer.append("BusinessPrice,");
    buffer.append("Voltlevel,");
    buffer.append("IndustryPrice,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark,");
    buffer.append("InputDate ");
    buffer.append(") ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append(buffer.toString());
      debugBuffer.append("VALUES(");
      debugBuffer.append("'").append(lwTownIndicatorDto.getUserNo()).append("',");
      debugBuffer.append("'").append(lwTownIndicatorDto.getUserName()).append("',");
      debugBuffer.append("'").append(lwTownIndicatorDto.getAddress()).append("',");
      debugBuffer.append("'").append(lwTownIndicatorDto.getReadDate()).append("',");
      debugBuffer.append("'").append(lwTownIndicatorDto.getStatMonth()).append("',");
      debugBuffer.append("").append(lwTownIndicatorDto.getThisWorkNum()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getMidWorkNum()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getLastWorkNum()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getRate()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getReadQuantity()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getExcepQuantity()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getChgAmmeterQuantity()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getCompensateQuantity()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getAppendCalQuantity()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getTranferLossQuantity()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getPeoplePrice()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getNotPeoplePrice()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getFarmPrice()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getProducePrice()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getBusinessPrice()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getVoltlevel()).append(",");
      debugBuffer.append("").append(lwTownIndicatorDto.getIndustryPrice()).append(",");
      debugBuffer.append("'").append(lwTownIndicatorDto.getValidStatus()).append("',");
      debugBuffer.append("'").append(lwTownIndicatorDto.getFlag()).append("',");
      debugBuffer.append("'").append(lwTownIndicatorDto.getRemark()).append("',");
      debugBuffer.append("'").append(lwTownIndicatorDto.getInputDate()).append("')");
      logger.debug(debugBuffer.toString());
    }

    buffer.append("VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
    dbManager.prepareStatement(buffer.toString());
    dbManager.setString(1, lwTownIndicatorDto.getUserNo());
    dbManager.setString(2, lwTownIndicatorDto.getUserName());
    dbManager.setString(3, lwTownIndicatorDto.getAddress());
    dbManager.setString(4, lwTownIndicatorDto.getReadDate());
    dbManager.setString(5, lwTownIndicatorDto.getStatMonth());
    dbManager.setDouble(6, lwTownIndicatorDto.getThisWorkNum());
    dbManager.setDouble(7, lwTownIndicatorDto.getMidWorkNum());
    dbManager.setDouble(8, lwTownIndicatorDto.getLastWorkNum());
    dbManager.setDouble(9, lwTownIndicatorDto.getRate());
    dbManager.setDouble(10, lwTownIndicatorDto.getReadQuantity());
    dbManager.setDouble(11, lwTownIndicatorDto.getExcepQuantity());
    dbManager.setDouble(12, lwTownIndicatorDto.getChgAmmeterQuantity());
    dbManager.setDouble(13, lwTownIndicatorDto.getCompensateQuantity());
    dbManager.setLong(14, lwTownIndicatorDto.getAppendCalQuantity());
    dbManager.setLong(15, lwTownIndicatorDto.getTranferLossQuantity());
    dbManager.setDouble(16, lwTownIndicatorDto.getPeoplePrice());
    dbManager.setDouble(17, lwTownIndicatorDto.getNotPeoplePrice());
    dbManager.setDouble(18, lwTownIndicatorDto.getFarmPrice());
    dbManager.setDouble(19, lwTownIndicatorDto.getProducePrice());
    dbManager.setDouble(20, lwTownIndicatorDto.getBusinessPrice());
    dbManager.setInt(21, lwTownIndicatorDto.getVoltlevel());
    dbManager.setDouble(22, lwTownIndicatorDto.getIndustryPrice());
    dbManager.setString(23, lwTownIndicatorDto.getValidStatus());
    dbManager.setString(24, lwTownIndicatorDto.getFlag());
    dbManager.setString(25, lwTownIndicatorDto.getRemark());
    dbManager.setString(26, lwTownIndicatorDto.getInputDate());
    dbManager.executePreparedUpdate();
  }

  /**
   * 采用批方式插入多条数据
   *
   * @param collection collection
   * @throws Exception
   */
  public void insertAll(Collection collection) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    buffer.append("INSERT INTO LwTownIndicator (");
    buffer.append("UserNo,");
    buffer.append("UserName,");
    buffer.append("Address,");
    buffer.append("ReadDate,");
    buffer.append("StatMonth,");
    buffer.append("ThisWorkNum,");
    buffer.append("MidWorkNum,");
    buffer.append("LastWorkNum,");
    buffer.append("Rate,");
    buffer.append("ReadQuantity,");
    buffer.append("ExcepQuantity,");
    buffer.append("ChgAmmeterQuantity,");
    buffer.append("CompensateQuantity,");
    buffer.append("AppendCalQuantity,");
    buffer.append("TranferLossQuantity,");
    buffer.append("PeoplePrice,");
    buffer.append("NotPeoplePrice,");
    buffer.append("FarmPrice,");
    buffer.append("ProducePrice,");
    buffer.append("BusinessPrice,");
    buffer.append("Voltlevel,");
    buffer.append("IndustryPrice,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark,");
    buffer.append("InputDate ");
    buffer.append(") ");
    buffer.append("VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
    if (logger.isDebugEnabled()) {
      logger.debug(buffer.toString());
    }
    dbManager.prepareStatement(buffer.toString());
    for (Iterator i = collection.iterator(); i.hasNext(); ) {
      LwTownIndicatorDto lwTownIndicatorDto = (LwTownIndicatorDto) i.next();
      dbManager.setString(1, lwTownIndicatorDto.getUserNo());
      dbManager.setString(2, lwTownIndicatorDto.getUserName());
      dbManager.setString(3, lwTownIndicatorDto.getAddress());
      dbManager.setString(4, lwTownIndicatorDto.getReadDate());
      dbManager.setString(5, lwTownIndicatorDto.getStatMonth());
      dbManager.setDouble(6, lwTownIndicatorDto.getThisWorkNum());
      dbManager.setDouble(7, lwTownIndicatorDto.getMidWorkNum());
      dbManager.setDouble(8, lwTownIndicatorDto.getLastWorkNum());
      dbManager.setDouble(9, lwTownIndicatorDto.getRate());
      dbManager.setDouble(10, lwTownIndicatorDto.getReadQuantity());
      dbManager.setDouble(11, lwTownIndicatorDto.getExcepQuantity());
      dbManager.setDouble(12, lwTownIndicatorDto.getChgAmmeterQuantity());
      dbManager.setDouble(13, lwTownIndicatorDto.getCompensateQuantity());
      dbManager.setLong(14, lwTownIndicatorDto.getAppendCalQuantity());
      dbManager.setLong(15, lwTownIndicatorDto.getTranferLossQuantity());
      dbManager.setDouble(16, lwTownIndicatorDto.getPeoplePrice());
      dbManager.setDouble(17, lwTownIndicatorDto.getNotPeoplePrice());
      dbManager.setDouble(18, lwTownIndicatorDto.getFarmPrice());
      dbManager.setDouble(19, lwTownIndicatorDto.getProducePrice());
      dbManager.setDouble(20, lwTownIndicatorDto.getBusinessPrice());
      dbManager.setInt(21, lwTownIndicatorDto.getVoltlevel());
      dbManager.setDouble(22, lwTownIndicatorDto.getIndustryPrice());
      dbManager.setString(23, lwTownIndicatorDto.getValidStatus());
      dbManager.setString(24, lwTownIndicatorDto.getFlag());
      dbManager.setString(25, lwTownIndicatorDto.getRemark());
      dbManager.setString(26, lwTownIndicatorDto.getInputDate());
      dbManager.addBatch();
    }
    dbManager.executePreparedUpdateBatch();
  }

  /**
   * 按主键删除一条数据
   *
   * @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();
  }

  /**
   * 按主键更新一条数据(主键本身无法变更)
   *
   * @param lwTownIndicatorDto lwTownIndicatorDto
   * @throws Exception
   */
  public void update(LwTownIndicatorDto lwTownIndicatorDto) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    buffer.append("UPDATE LwTownIndicator SET ");
    buffer.append("UserName = ?, ");
    buffer.append("Address = ?, ");
    buffer.append("ReadDate = ?, ");
    buffer.append("ThisWorkNum = ?, ");
    buffer.append("MidWorkNum = ?, ");
    buffer.append("LastWorkNum = ?, ");
    buffer.append("Rate = ?, ");
    buffer.append("ReadQuantity = ?, ");
    buffer.append("ExcepQuantity = ?, ");
    buffer.append("ChgAmmeterQuantity = ?, ");
    buffer.append("CompensateQuantity = ?, ");
    buffer.append("AppendCalQuantity = ?, ");
    buffer.append("TranferLossQuantity = ?, ");
    buffer.append("PeoplePrice = ?, ");
    buffer.append("NotPeoplePrice = ?, ");
    buffer.append("FarmPrice = ?, ");
    buffer.append("ProducePrice = ?, ");
    buffer.append("BusinessPrice = ?, ");
    buffer.append("Voltlevel = ?, ");
    buffer.append("IndustryPrice = ?, ");
    buffer.append("ValidStatus = ?, ");
    buffer.append("Flag = ?, ");
    buffer.append("Remark = ?, ");
    buffer.append("InputDate = ? ");
    if (logger.isDebugEnabled()) {
      StringBuffer debugBuffer = new StringBuffer(buffer.length() * 4);
      debugBuffer.append("UPDATE LwTownIndicator SET ");
      debugBuffer.append("UserName = '******', ");
      debugBuffer.append("Address = '" + lwTownIndicatorDto.getAddress() + "', ");
      debugBuffer.append("ReadDate = '" + lwTownIndicatorDto.getReadDate() + "', ");
      debugBuffer.append("ThisWorkNum = " + lwTownIndicatorDto.getThisWorkNum() + ", ");
      debugBuffer.append("MidWorkNum = " + lwTownIndicatorDto.getMidWorkNum() + ", ");
      debugBuffer.append("LastWorkNum = " + lwTownIndicatorDto.getLastWorkNum() + ", ");
      debugBuffer.append("Rate = " + lwTownIndicatorDto.getRate() + ", ");
      debugBuffer.append("ReadQuantity = " + lwTownIndicatorDto.getReadQuantity() + ", ");
      debugBuffer.append("ExcepQuantity = " + lwTownIndicatorDto.getExcepQuantity() + ", ");
      debugBuffer.append(
          "ChgAmmeterQuantity = " + lwTownIndicatorDto.getChgAmmeterQuantity() + ", ");
      debugBuffer.append(
          "CompensateQuantity = " + lwTownIndicatorDto.getCompensateQuantity() + ", ");
      debugBuffer.append("AppendCalQuantity = " + lwTownIndicatorDto.getAppendCalQuantity() + ", ");
      debugBuffer.append(
          "TranferLossQuantity = " + lwTownIndicatorDto.getTranferLossQuantity() + ", ");
      debugBuffer.append("PeoplePrice = " + lwTownIndicatorDto.getPeoplePrice() + ", ");
      debugBuffer.append("NotPeoplePrice = " + lwTownIndicatorDto.getNotPeoplePrice() + ", ");
      debugBuffer.append("FarmPrice = " + lwTownIndicatorDto.getFarmPrice() + ", ");
      debugBuffer.append("ProducePrice = " + lwTownIndicatorDto.getProducePrice() + ", ");
      debugBuffer.append("BusinessPrice = " + lwTownIndicatorDto.getBusinessPrice() + ", ");
      debugBuffer.append("Voltlevel = " + lwTownIndicatorDto.getVoltlevel() + ", ");
      debugBuffer.append("IndustryPrice = " + lwTownIndicatorDto.getIndustryPrice() + ", ");
      debugBuffer.append("ValidStatus = '" + lwTownIndicatorDto.getValidStatus() + "', ");
      debugBuffer.append("Flag = '" + lwTownIndicatorDto.getFlag() + "', ");
      debugBuffer.append("Remark = '" + lwTownIndicatorDto.getRemark() + "', ");
      debugBuffer.append("InputDate = '" + lwTownIndicatorDto.getInputDate() + "' ");
      debugBuffer.append("WHERE ");
      debugBuffer
          .append("UserNo=")
          .append("'")
          .append(lwTownIndicatorDto.getUserNo())
          .append("' AND ");
      debugBuffer
          .append("StatMonth=")
          .append("'")
          .append(lwTownIndicatorDto.getStatMonth())
          .append("'");
      logger.debug(debugBuffer.toString());
    }

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

    dbManager.prepareStatement(buffer.toString());
    // 设置更新字段;
    dbManager.setString(1, lwTownIndicatorDto.getUserName());
    dbManager.setString(2, lwTownIndicatorDto.getAddress());
    dbManager.setString(3, lwTownIndicatorDto.getReadDate());
    dbManager.setDouble(4, lwTownIndicatorDto.getThisWorkNum());
    dbManager.setDouble(5, lwTownIndicatorDto.getMidWorkNum());
    dbManager.setDouble(6, lwTownIndicatorDto.getLastWorkNum());
    dbManager.setDouble(7, lwTownIndicatorDto.getRate());
    dbManager.setDouble(8, lwTownIndicatorDto.getReadQuantity());
    dbManager.setDouble(9, lwTownIndicatorDto.getExcepQuantity());
    dbManager.setDouble(10, lwTownIndicatorDto.getChgAmmeterQuantity());
    dbManager.setDouble(11, lwTownIndicatorDto.getCompensateQuantity());
    dbManager.setLong(12, lwTownIndicatorDto.getAppendCalQuantity());
    dbManager.setLong(13, lwTownIndicatorDto.getTranferLossQuantity());
    dbManager.setDouble(14, lwTownIndicatorDto.getPeoplePrice());
    dbManager.setDouble(15, lwTownIndicatorDto.getNotPeoplePrice());
    dbManager.setDouble(16, lwTownIndicatorDto.getFarmPrice());
    dbManager.setDouble(17, lwTownIndicatorDto.getProducePrice());
    dbManager.setDouble(18, lwTownIndicatorDto.getBusinessPrice());
    dbManager.setInt(19, lwTownIndicatorDto.getVoltlevel());
    dbManager.setDouble(20, lwTownIndicatorDto.getIndustryPrice());
    dbManager.setString(21, lwTownIndicatorDto.getValidStatus());
    dbManager.setString(22, lwTownIndicatorDto.getFlag());
    dbManager.setString(23, lwTownIndicatorDto.getRemark());
    dbManager.setString(24, lwTownIndicatorDto.getInputDate());
    // 设置条件字段;
    dbManager.setString(25, lwTownIndicatorDto.getUserNo());
    dbManager.setString(26, lwTownIndicatorDto.getStatMonth());
    dbManager.executePreparedUpdate();
  }

  /**
   * 按主键查找一条数据
   *
   * @param userNo 户号
   * @param statMonth 账期
   * @return LwTownIndicatorDto
   * @throws Exception
   */
  public LwTownIndicatorDto findByPrimaryKey(String userNo, String statMonth) throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    // 拼SQL语句
    buffer.append("SELECT ");
    buffer.append("UserNo,");
    buffer.append("UserName,");
    buffer.append("Address,");
    buffer.append("ReadDate,");
    buffer.append("StatMonth,");
    buffer.append("ThisWorkNum,");
    buffer.append("MidWorkNum,");
    buffer.append("LastWorkNum,");
    buffer.append("Rate,");
    buffer.append("ReadQuantity,");
    buffer.append("ExcepQuantity,");
    buffer.append("ChgAmmeterQuantity,");
    buffer.append("CompensateQuantity,");
    buffer.append("AppendCalQuantity,");
    buffer.append("TranferLossQuantity,");
    buffer.append("PeoplePrice,");
    buffer.append("NotPeoplePrice,");
    buffer.append("FarmPrice,");
    buffer.append("ProducePrice,");
    buffer.append("BusinessPrice,");
    buffer.append("Voltlevel,");
    buffer.append("IndustryPrice,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark,");
    buffer.append("InputDate ");
    buffer.append("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);
    ResultSet resultSet = dbManager.executePreparedQuery();
    LwTownIndicatorDto lwTownIndicatorDto = null;
    if (resultSet.next()) {
      lwTownIndicatorDto = new LwTownIndicatorDto();
      lwTownIndicatorDto.setUserNo(dbManager.getString(resultSet, 1));
      lwTownIndicatorDto.setUserName(dbManager.getString(resultSet, 2));
      lwTownIndicatorDto.setAddress(dbManager.getString(resultSet, 3));
      lwTownIndicatorDto.setReadDate(dbManager.getString(resultSet, 4));
      lwTownIndicatorDto.setStatMonth(dbManager.getString(resultSet, 5));
      lwTownIndicatorDto.setThisWorkNum(dbManager.getDouble(resultSet, 6));
      lwTownIndicatorDto.setMidWorkNum(dbManager.getDouble(resultSet, 7));
      lwTownIndicatorDto.setLastWorkNum(dbManager.getDouble(resultSet, 8));
      lwTownIndicatorDto.setRate(dbManager.getDouble(resultSet, 9));
      lwTownIndicatorDto.setReadQuantity(dbManager.getDouble(resultSet, 10));
      lwTownIndicatorDto.setExcepQuantity(dbManager.getDouble(resultSet, 11));
      lwTownIndicatorDto.setChgAmmeterQuantity(dbManager.getDouble(resultSet, 12));
      lwTownIndicatorDto.setCompensateQuantity(dbManager.getDouble(resultSet, 13));
      lwTownIndicatorDto.setAppendCalQuantity(dbManager.getLong(resultSet, 14));
      lwTownIndicatorDto.setTranferLossQuantity(dbManager.getLong(resultSet, 15));
      lwTownIndicatorDto.setPeoplePrice(dbManager.getDouble(resultSet, 16));
      lwTownIndicatorDto.setNotPeoplePrice(dbManager.getDouble(resultSet, 17));
      lwTownIndicatorDto.setFarmPrice(dbManager.getDouble(resultSet, 18));
      lwTownIndicatorDto.setProducePrice(dbManager.getDouble(resultSet, 19));
      lwTownIndicatorDto.setBusinessPrice(dbManager.getDouble(resultSet, 20));
      lwTownIndicatorDto.setVoltlevel(dbManager.getInt(resultSet, 21));
      lwTownIndicatorDto.setIndustryPrice(dbManager.getDouble(resultSet, 22));
      lwTownIndicatorDto.setValidStatus(dbManager.getString(resultSet, 23));
      lwTownIndicatorDto.setFlag(dbManager.getString(resultSet, 24));
      lwTownIndicatorDto.setRemark(dbManager.getString(resultSet, 25));
      lwTownIndicatorDto.setInputDate(dbManager.getString(resultSet, 26));
    }
    resultSet.close();
    return lwTownIndicatorDto;
  }

  /**
   * 按条件查询多条数据
   *
   * @param conditions 查询条件
   * @param pageNo 页号
   * @param rowsPerPage 每页的行数
   * @return Collection
   * @throws Exception
   */
  public Collection findByConditions(String conditions, int pageNo, int rowsPerPage)
      throws Exception {
    StringBuffer buffer = new StringBuffer(200);
    // 拼SQL语句
    buffer.append("SELECT ");
    buffer.append("UserNo,");
    buffer.append("UserName,");
    buffer.append("Address,");
    buffer.append("ReadDate,");
    buffer.append("StatMonth,");
    buffer.append("ThisWorkNum,");
    buffer.append("MidWorkNum,");
    buffer.append("LastWorkNum,");
    buffer.append("Rate,");
    buffer.append("ReadQuantity,");
    buffer.append("ExcepQuantity,");
    buffer.append("ChgAmmeterQuantity,");
    buffer.append("CompensateQuantity,");
    buffer.append("AppendCalQuantity,");
    buffer.append("TranferLossQuantity,");
    buffer.append("PeoplePrice,");
    buffer.append("NotPeoplePrice,");
    buffer.append("FarmPrice,");
    buffer.append("ProducePrice,");
    buffer.append("BusinessPrice,");
    buffer.append("Voltlevel,");
    buffer.append("IndustryPrice,");
    buffer.append("ValidStatus,");
    buffer.append("Flag,");
    buffer.append("Remark,");
    buffer.append("InputDate ");
    buffer.append("FROM LwTownIndicator WHERE ");
    buffer.append(conditions);
    boolean supportPaging = false; // 数据库是否支持分页
    if (pageNo > 0) {
      // 对Oracle优化
      if (dbManager
          .getConnection()
          .getMetaData()
          .getDatabaseProductName()
          .equalsIgnoreCase("Oracle")) {
        buffer.insert(0, "SELECT * FROM ( SELECT row_.*, rownum rownum_ FROM (");
        buffer.append(
            ") row_ WHERE rownum <= "
                + rowsPerPage * pageNo
                + ") WHERE rownum_ > "
                + rowsPerPage * (pageNo - 1));
        supportPaging = true;
      } else if (dbManager
          .getConnection()
          .getMetaData()
          .getDatabaseProductName()
          .equalsIgnoreCase("DB2")) {
        String sql = buffer.toString();
        buffer.setLength(0);
        buffer.append("select * from ( select rownumber() over(");
        int orderByIndex = sql.toLowerCase().indexOf("order by");
        if (orderByIndex > 0) {
          buffer.append(sql.substring(orderByIndex));
        }
        buffer.append(") as rownumber_,");
        buffer.append(sql.substring(6));
        buffer.append(" ) as temp_ where rownumber_");
        buffer.append(
            " between " + (rowsPerPage * (pageNo - 1) + 1) + " and " + rowsPerPage * pageNo);
        supportPaging = true;
      }
    }
    if (true) {
      logger.debug(buffer.toString());
    }
    ResultSet resultSet = dbManager.executeQuery(buffer.toString());
    int count = 0;
    if (supportPaging == false && pageNo > 1) {
      dbManager.locate(resultSet, rowsPerPage * (pageNo - 1));
    }

    // 定义返回结果集合
    Collection collection = new ArrayList(rowsPerPage);
    LwTownIndicatorDto lwTownIndicatorDto = null;
    while (resultSet.next()) {
      if (supportPaging == false && pageNo > 0) {
        count++;
        if (count > rowsPerPage) {
          break;
        }
      }

      lwTownIndicatorDto = new LwTownIndicatorDto();
      lwTownIndicatorDto.setUserNo(dbManager.getString(resultSet, "UserNo"));
      lwTownIndicatorDto.setUserName(dbManager.getString(resultSet, "UserName"));
      lwTownIndicatorDto.setAddress(dbManager.getString(resultSet, "Address"));
      lwTownIndicatorDto.setReadDate(dbManager.getString(resultSet, "ReadDate"));
      lwTownIndicatorDto.setStatMonth(dbManager.getString(resultSet, "StatMonth"));
      lwTownIndicatorDto.setThisWorkNum(dbManager.getDouble(resultSet, "ThisWorkNum"));
      lwTownIndicatorDto.setMidWorkNum(dbManager.getDouble(resultSet, "MidWorkNum"));
      lwTownIndicatorDto.setLastWorkNum(dbManager.getDouble(resultSet, "LastWorkNum"));
      lwTownIndicatorDto.setRate(dbManager.getDouble(resultSet, "Rate"));
      lwTownIndicatorDto.setReadQuantity(dbManager.getDouble(resultSet, "ReadQuantity"));
      lwTownIndicatorDto.setExcepQuantity(dbManager.getDouble(resultSet, "ExcepQuantity"));
      lwTownIndicatorDto.setChgAmmeterQuantity(
          dbManager.getDouble(resultSet, "ChgAmmeterQuantity"));
      lwTownIndicatorDto.setCompensateQuantity(
          dbManager.getDouble(resultSet, "CompensateQuantity"));
      lwTownIndicatorDto.setAppendCalQuantity(dbManager.getLong(resultSet, "AppendCalQuantity"));
      lwTownIndicatorDto.setTranferLossQuantity(
          dbManager.getLong(resultSet, "TranferLossQuantity"));
      lwTownIndicatorDto.setPeoplePrice(dbManager.getDouble(resultSet, "PeoplePrice"));
      lwTownIndicatorDto.setNotPeoplePrice(dbManager.getDouble(resultSet, "NotPeoplePrice"));
      lwTownIndicatorDto.setFarmPrice(dbManager.getDouble(resultSet, "FarmPrice"));
      lwTownIndicatorDto.setProducePrice(dbManager.getDouble(resultSet, "ProducePrice"));
      lwTownIndicatorDto.setBusinessPrice(dbManager.getDouble(resultSet, "BusinessPrice"));
      lwTownIndicatorDto.setVoltlevel(dbManager.getInt(resultSet, "Voltlevel"));
      lwTownIndicatorDto.setIndustryPrice(dbManager.getDouble(resultSet, "IndustryPrice"));
      lwTownIndicatorDto.setValidStatus(dbManager.getString(resultSet, "ValidStatus"));
      lwTownIndicatorDto.setFlag(dbManager.getString(resultSet, "Flag"));
      lwTownIndicatorDto.setRemark(dbManager.getString(resultSet, "Remark"));
      lwTownIndicatorDto.setInputDate(dbManager.getString(resultSet, "InputDate"));
      collection.add(lwTownIndicatorDto);
    }
    resultSet.close();
    return collection;
  }

  /**
   * 按条件查询多条数据
   *
   * @param conditions 查询条件
   * @return Collection
   * @throws Exception
   */
  public Collection findByConditions(String conditions) throws Exception {
    return findByConditions(conditions, 0, 0);
  }

  /**
   * 按条件删除数据
   *
   * @param conditions 查询条件
   * @return 删除的行数
   * @throws Exception
   */
  public int deleteByConditions(String conditions) throws Exception {
    StringBuffer buffer = new StringBuffer(100);
    buffer.append("DELETE FROM LwTownIndicator WHERE ");
    buffer.append(conditions);
    if (logger.isDebugEnabled()) {
      logger.debug(buffer.toString());
    }
    int count = dbManager.executeUpdate(buffer.toString());
    return count;
  }

  /**
   * 查询满足模糊查询条件的记录数
   *
   * @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 LwTownIndicator 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;
  }
}
Exemplo n.º 11
0
/** Servlet implementation class Feedback */
public class Feedback extends HttpServlet {
  private static final long serialVersionUID = 1L;
  private static Logger logger = Logger.getLogger(Feedback.class);
  Connection conn = null;
  PreparedStatement pstmt = null;
  String name = null;
  String email = null;
  String comment = null;

  /** @see HttpServlet#HttpServlet() */
  public Feedback() {
    super();
    // TODO Auto-generated constructor stub
  }

  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();
    }
  }

  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    try {
      processData(request, response);
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  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;
  }

  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    try {
      processData(request, response);
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
Exemplo n.º 12
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();
    }
  }
Exemplo n.º 13
0
public class LibRt {
  public static String CfgEncodingDflt =
      "ISO-8859-1"; // U: si no especificamos, un archivo a string se lee con este encoding

  public static final Logger logger = Logger.getLogger("rt");
  public static final String EOL = "\n";
  public static final int BUFF_SZ = 8192;

  public static java.util.Hashtable state =
      new java.util
          .Hashtable(); // U: accesible desde javascript para mantener estado entre llamadas AUNQUE
                        // los scripts se ejecuten de cero en cada thread

  public static boolean IsLogInitialized = false;

  public static void logInit(boolean force) throws IOException {
    if (!IsLogInitialized || force) {
      LogManager.getLogManager()
          .readConfiguration(
              LibRt.class.getClassLoader().getResourceAsStream("cfg.logging.properties"));
      String logFile = System.getProperty("CfgLog");
      if (logFile != null) {
        LogManager.getLogManager().readConfiguration(new FileInputStream(logFile));
      }
      try {
        LogLvlMax = Integer.parseInt(System.getProperty("LogLvlMax", LogLvlMax + ""));
      } catch (Exception ex) {
      }
      ; // XXX: mostrar mensaje?
    }
  }

  // Primitiva de log
  public static int LogLvlMax = 9; // DFLT

  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) : ""));
    }
  }

  public static void logmex(String t, int lvl, String msg, Object o, Exception ex) {
    StringBuilder sb = new StringBuilder();
    StackTraceElement se[] = ex.getStackTrace();
    for (int i = 0; i < se.length; i++) {
      sb.append(se[i].getMethodName() + "@" + se[i].getFileName() + "@" + se[i].getLineNumber());
      sb.append(" > ");
    }
    logm(t, lvl, msg + " EXCEPTION " + ex + " " + sb.toString(), o);
  }

  // ***************************************************************************
  // S: enc/base64

  public static String enc_base64(String data) throws UnsupportedEncodingException {
    return enc_base64(data.getBytes("UTF-8"));
  }

  public static String enc_base64(byte[] data) throws UnsupportedEncodingException {
    return DatatypeConverter.printBase64Binary(data);
  }

  public static String enc_base64_r_str(String encoded) throws UnsupportedEncodingException {
    return new String(enc_base64_r(encoded), "UTF-8");
  }

  public static byte[] enc_base64_r(String encoded) throws UnsupportedEncodingException {
    return DatatypeConverter.parseBase64Binary(encoded);
  }

  // ***************************************************************************
  // S: ser/json
  static final Gson gson = new Gson(); // A: encapsulamos
  // XXX: mejor usar Jackson? cual usan otros proyectos de EM? Por que?

  public static String ser_json(Object o) {
    String s = "";
    try {
      s = gson.toJson(o);
    } catch (Exception ex) {
      s = o + "";
    }
    return s;
  }

  // ***************************************************************************
  // S: ser/csv

  public static int serRsCsvToFile(
      ResultSet resultset, String[] columnNames, String path, int maxRows, String separator) {
    Writer writer;
    try {
      writer = fileWriter(path);
    } catch (UnsupportedEncodingException e) {
      logm("ERR", 0, "FILE WRITER CSV OUTPUT OPEN unsupported encondig", path);
      return -1;
    } catch (FileNotFoundException e) {
      logm("ERR", 0, "FILE WRITER CSV OUTPUT OPEN file not found", path);
      return -1;
    } catch (IOException e) {
      logm("ERR", 0, "FILE WRITER CSV OUTPUT OPEN file not found", path);
      return -1;
    }
    // A: writer escribe en el archivo especificado
    return serRsCsvToWriter(resultset, columnNames, writer, maxRows, separator);
  }

  public static int serDiccCsvToWriter(String str, String path, int maxRows, String separator) {
    Writer writer;
    try {
      writer = fileWriterAppend(path, false, null);
      logm("DBG", 9, "ABRE WRITER", null);
    } catch (UnsupportedEncodingException e) {
      logm("ERR", 0, "FILE WRITER CSV OUTPUT OPEN unsupported encondig", path);
      return -1;
    } catch (FileNotFoundException e) {
      logm("ERR", 0, "FILE WRITER CSV OUTPUT OPEN file not found", path);
      return -1;
    } catch (IOException e) {
      logm("ERR", 0, "FILE WRITER CSV OUTPUT OPEN file not found", path);
      return -1;
    }
    // A: writer escribe en el archivo especificado
    return serDiccCsvToWriter(str, writer, maxRows, separator);
  }

  public static String[] dbRsColumnNames(ResultSet resultset) throws SQLException {
    java.util.Vector<String> rv = new java.util.Vector<String>();
    if (resultset != null) {
      logm("DBG", 9, "ColumnCount=0 Calculando cantidad columnas desde metadata", null);
      ResultSetMetaData md = resultset.getMetaData();
      int columnCount = md.getColumnCount();
      logm("DBG", 9, "ColumnCount", columnCount);
      for (int i = 1; i <= columnCount; i++) {
        rv.add(md.getColumnName(i).toLowerCase());
      }
    }
    String[] r = rv.toArray(new String[0]);
    logm("DBG", 9, "DB dbRsColumnNames", r);
    return r;
  }

  public static int serRsCsvToWriter(
      ResultSet resultset, String[] columnNames, Writer writer, int maxRows, String separator) {
    int counter = 0;
    if (resultset != null) {
      if (columnNames == null) {
        try {
          logm("NFO", 9, "CSV titulos, obteniendo desde metadata", null);
          columnNames = dbRsColumnNames(resultset);
        } catch (SQLException e) {
          logmex("ERR", 1, "CSV titulos, obteniendo desde metadata", null, e);
          return -1;
        }
      }
      logm("DBG", 7, "CSV titulos", columnNames);
      // A: columnCount tiene el valor especificado o el default

      int columnCount = columnNames.length;
      // Itero el resultset escribiendo el output
      try {
        // XXX:OPCION escape separator si aparece en un valor?

        logm("DBG", 4, "ESCRIBIENDO ARCHIVO", resultset);

        for (int i = 0; i < columnCount - 1; i++) {
          logm("DBG", 9, "ESCRIBE COL: ", columnNames[i]);
          writer.write(columnNames[i]);
          writer.write(separator);
        }

        writer.write(columnNames[columnCount - 1]);
        writer.write(EOL);

        logm("DBG", 4, "SE ESCRIBIO LINEA DE COLUMNAS", null);
        logm("DBG", 4, "COUNTER", counter);
        logm("DBG", 4, "MAXROWS", maxRows);
        // A: escribi los nombres de las columnas

        boolean hasNext = resultset.next();

        logm("DBG", 4, "NEXT", hasNext);

        while ((counter < maxRows || maxRows < 0) && hasNext) {

          logm("DBG", 4, "Escribiendo fila :", counter);

          String buf;
          for (int i = 1; i < columnCount; i++) {

            if ((buf = resultset.getString(i)) != null) {
              writer.write(buf);
            }

            logm("DBG", 9, "STR", buf);

            writer.write(separator);
          }
          if ((buf = resultset.getString(columnCount)) != null) {
            writer.write(buf);
          }

          logm("DBG", 9, "STR", buf);

          writer.write(EOL);
          counter++;
          // XXX:loguear un cartelito ej. cada 1000
          hasNext = resultset.next();
        }

        logm("DBG", 2, "termino de escribir lineas", null);

      } catch (SQLException s) {
        logmex("ERR", 0, "DB leyendo resultset para CSV", null, s);
        return -1;
      } catch (IOException e) {
        logmex("ERR", 0, "FILE WRITER CSV OUTPUT writing", null, e);
        return -1;
      }
    } else {
      logm("NFO", 3, "DB FILE CSV RESULTSET IS NULL, was expected?", null);
    }
    try {
      writer.close();
    } catch (IOException e) {
      logmex("ERR", 0, "FILE WRITER CSV OUTPUT closing", null, e);
      return -1;
    }
    return counter;
  }

  @SuppressWarnings("unchecked")
  public static int serDiccCsvToWriter(String csv, Writer writer, int maxRows, String separator) {
    int counter = 0;

    if (csv != null) {
      try {
        writer.write(csv);
        writer.write(EOL);

      } catch (IOException e) {
        logmex("ERR", 0, "FILE WRITER CSV OUTPUT writing", null, e);
        return -1;
      }
    } else {
      logm("NFO", 3, "DB FILE CSV RESULTSET IS NULL, was expected?", null);
    }

    return counter;
  }

  public static int serDiccGroupByToWriter(
      ResultSet rs,
      Writer writer,
      int maxRows,
      String idPor,
      String[] idAcumulados,
      String campoAcumuladoNombre) {
    int rowsCount = 0;

    try {

      ArrayList<String> acumulado = null;
      String idActual = null;
      StringBuilder reg = null;
      reg = new StringBuilder();
      String value = "";

      if (rs != null) {
        ResultSetMetaData rsm = rs.getMetaData();
        int countCol = rsm.getColumnCount();
        String name = "";
        for (int i = 1; i <= countCol; i++) {
          name = rsm.getColumnName(i);
          reg.append(name.toLowerCase()).append("\t");
        }
        reg.append(campoAcumuladoNombre);

        writer.write(reg.toString() + EOL);

        while (rs.next()) {
          if (idActual == null) {
            reg = new StringBuilder();
            acumulado = new ArrayList<String>();
            idActual = rs.getString(idPor);

            for (int i = 1; i <= countCol; i++) {
              reg.append(rs.getString(i)).append("\t");
            }

            for (String id : idAcumulados) {
              value = rs.getString(id);
              if (!rs.wasNull()) {
                acumulado.add(rs.getString(id));
              }
            }

          } else {

            if (idActual.equals(rs.getString(idPor))) {
              for (String id : idAcumulados) {
                value = rs.getString(id);
                if (!rs.wasNull()) {
                  acumulado.add(rs.getString(id));
                }
              }
            } else {
              if (acumulado.size() > 0) {
                for (String str : acumulado) {
                  reg.append(str).append(",");
                }
                reg.deleteCharAt(reg.length() - 1);
              }
              reg.append(EOL);

              writer.write(reg.toString());
              rowsCount++;
              if (maxRows == rowsCount) {
                break;
              }

              idActual = rs.getString(idPor);
              reg = new StringBuilder();
              acumulado = new ArrayList<String>();

              for (int i = 1; i <= countCol; i++) {
                reg.append(rs.getString(i)).append("\t");
              }

              for (String id : idAcumulados) {
                value = rs.getString(id);
                if (!rs.wasNull()) {
                  acumulado.add(rs.getString(id));
                }
              }
            }
          }
        }

        if (acumulado.size() > 0) {
          for (String str : acumulado) {
            reg.append(str).append(",");
          }
          reg.deleteCharAt(reg.length() - 1);
        }
        reg.append(EOL);

        writer.write(reg.toString());
        rowsCount++;
      }
    } catch (SQLException e) {
      logm("ERR", 1, "Error al escribir registros", e);
    } catch (IOException e) {
      logm("ERR", 1, "Error al escribir registros", e);
    }
    return rowsCount;
  }

  public static void closeWriterAppend(Writer writer) {
    try {
      writer.close();
    } catch (IOException e) {
      logmex("ERR", 0, "FILE WRITER CSV OUTPUT closing", null, e);
    }
  }

  // ***************************************************************************
  // S: db
  public static int dbRsColumnCount(ResultSet rs) throws SQLException {
    return rs.getMetaData().getColumnCount();
  }

  // ***************************************************************************
  // S: digest
  public static MessageDigest digestCalc(String algorithm) throws NoSuchAlgorithmException {
    return MessageDigest.getInstance(algorithm);
  }

  public static String digestHexStr(MessageDigest digestCalc) {
    return (new HexBinaryAdapter()).marshal(digestCalc.digest());
  }

  public static String digest(String data, String algorithm) throws NoSuchAlgorithmException {
    MessageDigest calc = digestCalc(algorithm);
    calc.update(data.getBytes());
    return digestHexStr(calc);
  }

  // ***************************************************************************
  // S: file
  public static Writer fileWriter(String path)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return fileWriter(path, false, null);
  }

  public static Writer fileWriter(String path, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return streamWriter(new FileOutputStream(path), zip, digestCalc);
  }

  public static Writer fileWriterAppend(String path, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return streamWriter(new FileOutputStream(path, true), zip, digestCalc);
  }

  public static OutputStream streamForOutput_file(
      String path, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return streamForOutput(new FileOutputStream(path), zip, digestCalc);
  }

  public static OutputStream streamForOutput(OutputStream os, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    OutputStream dos = digestCalc != null ? new DigestOutputStream(os, digestCalc) : os;
    OutputStream zos = zip ? new GZIPOutputStream(dos) : dos;
    return zos;
  }

  public static Writer streamWriter(OutputStream os, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return new BufferedWriter(
        new OutputStreamWriter(streamForOutput(os, zip, digestCalc), "utf-8"));
  }

  public static InputStream streamForInput_file(String path, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return streamForInput(new FileInputStream(path), zip, digestCalc);
  }

  public static Reader fileReader(String path, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return streamReader(new FileInputStream(path), zip, digestCalc);
  }

  public static InputStream streamForInput(InputStream fis, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    InputStream dis = digestCalc != null ? new DigestInputStream(fis, digestCalc) : fis;
    InputStream zis = zip ? new GZIPInputStream(dis) : dis;
    return zis;
  }

  public static Reader streamReader(InputStream fis, boolean zip, MessageDigest digestCalc)
      throws UnsupportedEncodingException, FileNotFoundException, IOException {
    return new BufferedReader(
        new InputStreamReader(streamForInput(fis, zip, digestCalc))); // , "utf-8"));
  }

  public static int pipe_stream(InputStream is, OutputStream os, boolean wantsKeepOpen)
      throws IOException { // U: copia de un stream al otro
    int cnt = 0;
    int n;
    byte[] buffer = new byte[BUFF_SZ];
    while ((n = is.read(buffer)) > -1) {
      cnt += n;
      os.write(buffer, 0, n);
    }
    if (!wantsKeepOpen) {
      is.close();
      os.close();
    }
    return cnt;
  }

  public static String get_stream(Reader isr) throws IOException {
    char[] buffer = new char[BUFF_SZ];
    StringBuilder out = new StringBuilder();
    logm("DBG", 9, "STREAM GET", isr + "");
    for (; ; ) {
      int rsz = isr.read(buffer, 0, buffer.length);
      logm("DBG", 9, "STREAM GET READ", rsz);
      if (rsz < 0) break;
      out.append(buffer, 0, rsz);
    }
    String s = out.toString();
    logm("DBG", 9, "STREAM GET RESULT", s);
    return s;
  }

  public static String get_stream(InputStream is) throws IOException {
    return get_stream(is, CfgEncodingDflt);
  }

  public static String get_stream(InputStream is, String encoding) throws IOException {
    if (encoding == null) {
      encoding = CfgEncodingDflt;
    }
    byte[] buffer = new byte[BUFF_SZ];
    StringBuilder out = new StringBuilder();
    logm("DBG", 9, "STREAM GET", is + "");
    for (; ; ) {
      int rsz = is.read(buffer, 0, buffer.length);
      logm("DBG", 9, "STREAM GET READ", rsz);
      if (rsz < 0) break;
      out.append(new String(buffer, 0, rsz, encoding));
    }
    String s = out.toString();
    logm("DBG", 9, "STREAM GET RESULT", s);
    return s;
  }

  public static void set_stream(OutputStream os, String data, String encoding) throws IOException {
    os.write(data.getBytes(encoding));
    os.close();
  }

  public static void set_stream(Writer os, String data) throws IOException {
    os.write(data);
    os.close();
  }

  public static String get_file(
      String path, boolean gzip, MessageDigest digestCalc, String encoding)
      throws UnsupportedEncodingException, IOException {
    try {
      return get_stream(streamForInput_file(path, gzip, digestCalc));
    } catch (FileNotFoundException ex) {
      return "";
    }
  }

  public static String get_resource(String path) throws IOException {
    java.io.InputStream srcs = null;
    try {
      srcs = LibRt.class.getResourceAsStream(path);
      return get_stream(srcs);
    } catch (IOException ex) {
      LibRt.logmex("DBG", 9, "RT GET_RESOURCE", path, ex);
      throw (ex);
    }
  }

  public static String get_resourceOrFile(
      String path, boolean gzip, MessageDigest digestCalc, String encoding)
      throws UnsupportedEncodingException, IOException {
    try {
      return get_resource(path);
    } catch (IOException ex) {
      return get_file(path, gzip, digestCalc, encoding);
    }
  }

  public static void set_file(
      String path, String data, boolean gzip, MessageDigest digestCalc, String encoding)
      throws UnsupportedEncodingException, IOException {
    set_stream(streamForOutput_file(path, gzip, digestCalc), data, CfgEncodingDflt);
  }

  public static String[] get_filelist(String path, boolean nodirs, boolean nofiles) {
    File folder = new File(path);
    if (folder.isDirectory()) {
      File[] listOfFiles = folder.listFiles();
      java.util.Vector<String> r = new java.util.Vector<String>();
      for (int i = 0; listOfFiles != null && i < listOfFiles.length; i++) {
        if ((listOfFiles[i].isFile() && !nofiles) || (listOfFiles[i].isDirectory() && !nodirs)) {
          r.add(listOfFiles[i].getName());
        }
      }
      return r.toArray(new String[0]);
    } else {
      return null; // A: no existe o no es directorio
    }
  }

  public static FileLock lock_file(String path) throws IOException, FileNotFoundException {
    RandomAccessFile file = new RandomAccessFile(path, "rw");
    FileChannel fileChannel = file.getChannel();
    return fileChannel.tryLock();
  }

  public static boolean unlock_file(FileLock fileLock) throws IOException, FileNotFoundException {
    if (fileLock != null) {
      fileLock.release();
      return true;
    }
    return false;
  }

  public static String temp_filePath(String namePattern, String ext)
      throws IOException, FileNotFoundException {
    File temp = File.createTempFile("temp-file-name", ".tmp");
    return temp.getAbsolutePath();
  }

  // ***************************************************************************
  // S File: scp = copiar sobre ssh
  public static void set_file_scp(
      String srcFilePath,
      String dstUrl,
      String dstFilePath,
      String dstUser,
      String dstPass,
      String keyFilePath)
      throws SshException {
    // SEE:
    // http://code.google.com/p/securechannelfacade/source/browse/trunk/src/main/java/org/rev6/scf/SshConnection.java?r=12
    SshConnection sshCx = null;
    String[] nameAndPort = dstUrl.split(":");
    int dstPort = nameAndPort.length > 1 ? Integer.parseInt(nameAndPort[1]) : 22;
    try {
      if (keyFilePath == null) {
        sshCx = new SshConnection(nameAndPort[0], dstUser, dstPass);
        logm(
            "DBG",
            7,
            "NET SSH CONNECT TO {HOST: '"
                + nameAndPort[0]
                + "', PORT:"
                + dstPort
                + ", USER:'******', auth: '"
                + "pass"
                + "'}",
            null);
      } else {
        sshCx = new SshConnection(nameAndPort[0], dstUser, new File(keyFilePath));
        logm(
            "DBG",
            7,
            "NET SSH CONNECT TO {HOST: '"
                + nameAndPort[0]
                + "', PORT:"
                + dstPort
                + ", USER:'******', auth: 'key', keyfile: '"
                + keyFilePath
                + "'}",
            null);
      }

      sshCx.setPort(dstPort);
      sshCx.connect();
      ScpFile scpFile = new ScpFile(new File(srcFilePath), dstFilePath);
      sshCx.executeTask(new ScpUpload(scpFile));
    } finally {
      if (sshCx != null) {
        sshCx.disconnect();
      }
    }
  }

  public static void set_file_scp_pass(
      String srcFilePath, String dstUrl, String dstFilePath, String dstUser, String dstPass)
      throws SshException {
    set_file_scp(srcFilePath, dstUrl, dstFilePath, dstUser, dstPass, null);
  }

  public static void set_file_scp_key(
      String srcFilePath, String dstUrl, String dstFilePath, String dstUser, String keyFilePath)
      throws SshException {
    set_file_scp(srcFilePath, dstUrl, dstFilePath, dstUser, null, keyFilePath);
  }

  // ***************************************************************************
  // S: net/http
  public static HttpURLConnection httpCx(String url, String method, String usr, String pass)
      throws MalformedURLException, IOException, ProtocolException {
    // NB:https requiere HAVA_HOME para encontrar los certificados!
    URL obj = new URL(url);
    HttpURLConnection cx = (HttpURLConnection) obj.openConnection();
    cx.setRequestMethod(method);
    if (usr != "") {
      String basicAuth = "Basic " + new String(enc_base64(usr + ":" + pass));
      cx.setRequestProperty("Authorization", basicAuth);
    }
    // A: parameters set

    return cx;
  }

  public static void httpWrite(HttpURLConnection cx, String data)
      throws IOException, ProtocolException {
    cx.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(cx.getOutputStream());
    wr.writeBytes(data);
    wr.flush();
    wr.close();
  }

  public static String httpRead(HttpURLConnection cx)
      throws UnsupportedEncodingException, IOException {
    // int responseCode = con.getResponseCode();
    return get_stream(cx.getInputStream());
  }

  public static String get_http(String url, String method, String data, String usr, String pass)
      throws IOException, ProtocolException, UnsupportedEncodingException {
    HttpURLConnection cx = httpCx(url, method, usr, pass);
    if (data != null) {
      httpWrite(cx, data);
    }
    return httpRead(cx);
  }

  // ****************************************************************************
  // S: Javascript
  public static LibRtJs JsImpl =
      System.getProperty("jsImpl", "RHINO").equals("JDK") ? new LibRtJsJdk() : new LibRtJsRhino();

  public static LibRtJs jsEval(String js, String srcDesc, LibRtJs jsEnv, String[] args)
      throws Exception {
    logm("DBG", 9, "RT JS EVAL START PATH=" + srcDesc + " SRC", js);
    return JsImpl.jsEval(js, srcDesc, jsEnv, args);
  }

  public static Object jsCall(String funName, LibRtJs jsEnv, Object[] args)
      throws IOException, Exception {
    logm("DBG", 5, "RT JS CALL TRY", funName);
    return JsImpl.jsCall(funName, jsEnv, args);
  }

  public static LibRtJs jsLoad(String path, LibRtJs jsEnv, String[] args)
      throws IOException, Exception {
    logm("DBG", 5, "RT JS LOAD TRY", path);
    return JsImpl.jsLoad(path, jsEnv, args);
  }

  public static LibRtJs jsLoadAlone(
      String path,
      Hashtable<String, Object>
          env) { // U: ejecutar un script en un contexto separado (no comparte variables salvo las
                 // que le pasemos en el hashtable)
    return JsImpl.jsLoadAlone(path, env);
  }

  // ****************************************************************************
  // S: paths

  public static String runtimePath()
      throws java.net.URISyntaxException,
          java.net.MalformedURLException { // U: para cargar librerias y assets, etc.
    // SEE: http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file
    URL url = LibRt.class.getResource(LibRt.class.getSimpleName() + ".class");
    logm("DBG", 1, "RT runtimePath URL", url);
    URL urlOk = (url.getProtocol() == "jar" ? new URL(url.getPath()) : url);
    logm("DBG", 1, "RT runtimePath URL OK", urlOk);
    return new File(urlOk.toURI()).getParentFile().getPath();
  }

  // ****************************************************************************
  // S: main
  public static void init() throws Exception {
    logInit(false);
  }

  public static void main(String[] args) throws Exception {
    init();
    String mainPath = args.length > 0 ? args[0] : "0inicio.js";
    try {
      jsLoad("librt.js", null, args);
      jsLoad(mainPath, null, args);
    } catch (Exception ex) {
      ex.printStackTrace();
      logmex("ERR", 1, "RT RUNNING SCRIPTS", null, ex);
    }
  }

  private static Class<?> getClassFromJar(String pathToJar, String pkg, String classToGet)
      throws IOException, ClassNotFoundException, SecurityException, InstantiationException,
          IllegalAccessException, NoSuchMethodException, IllegalArgumentException,
          InvocationTargetException {

    JarFile jarFile = new JarFile(pathToJar);
    Enumeration e = jarFile.entries();

    URL[] urls = {new URL("jar:file:" + pathToJar + "!/")};
    ClassLoader cl = URLClassLoader.newInstance(urls);

    Class<?> c = Class.forName(pkg + "." + classToGet, true, cl);

    return c;
  }

  public static void executeMethodClass(
      String pathToJar,
      String pkg,
      String classToGet,
      String methodName,
      String pathToFile,
      long logIdSyncMin,
      long logIdSyncMax)
      throws IOException, ClassNotFoundException, SecurityException, InstantiationException,
          IllegalAccessException, NoSuchMethodException, IllegalArgumentException,
          InvocationTargetException {
    Class<?> c = getClassFromJar(pathToJar, pkg, classToGet);
    Method method = c.getDeclaredMethod(methodName, String.class, long.class, long.class);
    method.invoke(null, pathToFile, logIdSyncMin, logIdSyncMax);
  }
}
/** Manages databases in a local environment, e.g. for PHP dynamic database lookup. */
public class DatabaseManager {
  protected static final Logger log = Logger.getLogger(DatabaseManager.class.getName());
  private static final L10N L = new L10N(DatabaseManager.class);

  private static final EnvironmentLocal<DatabaseManager> _localManager =
      new EnvironmentLocal<DatabaseManager>();

  private final HashMap<String, DBPool> _databaseMap = new HashMap<String, DBPool>();

  private final ArrayList<Driver> _driverList = new ArrayList<Driver>();

  private int _gId;

  /** The manager is never instantiated. */
  private DatabaseManager() {
    initDriverList();
  }

  /** Returns the database manager for the local environment. */
  private static DatabaseManager getLocalManager() {
    synchronized (_localManager) {
      DatabaseManager manager = _localManager.getLevel();

      if (manager == null) {
        manager = new DatabaseManager();

        _localManager.set(manager);
      }

      return manager;
    }
  }

  /** Returns a matching dbpool. */
  public static DataSource findDatabase(String url) throws SQLException {
    String driver = findDriverByUrl(url);

    return getLocalManager().findDatabaseImpl(url, driver);
  }

  /** Returns a matching dbpool. */
  public static DataSource findDatabase(String url, String driver) throws SQLException {
    return getLocalManager().findDatabaseImpl(url, driver);
  }

  /** Looks up the local database, creating if necessary. */
  private DataSource findDatabaseImpl(String url, String driverName) throws SQLException {
    try {
      synchronized (_databaseMap) {
        DBPool db = _databaseMap.get(url);

        if (db == null) {
          db = new DBPool();

          db.setVar(url + "-" + _gId++);

          DriverConfig driver = db.createDriver();

          ClassLoader loader = Thread.currentThread().getContextClassLoader();

          Class driverClass = Class.forName(driverName, false, loader);

          driver.setType(driverClass);
          driver.setURL(url);

          db.init();

          _databaseMap.put(url, db);
        }

        return db;
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (SQLException e) {
      throw e;
    } catch (Exception e) {
      throw ConfigException.create(e);
    }
  }

  public static String findDriverByUrl(String url) {
    return getLocalManager().findDriverByUrlImpl(url);
  }

  private String findDriverByUrlImpl(String url) {
    for (int i = 0; i < _driverList.size(); i++) {
      try {
        Driver driver = (Driver) _driverList.get(i);

        if (driver.acceptsURL(url)) return driver.getClass().getName();
      } catch (Exception e) {
        log.log(Level.FINE, e.toString(), e);
      }
    }

    return null;
  }

  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);
    }
  }

  static class DatabaseKey {
    private String _url;
    private String _catalog;

    DatabaseKey(String url, String catalog) {
      _url = url;
      _catalog = catalog;
    }

    public int hashCode() {
      int hash = 37;

      hash = 65521 * hash + _url.hashCode();

      if (_catalog != null) hash = 65521 * hash + _catalog.hashCode();

      return hash;
    }

    public boolean equals(Object o) {
      if (!(o instanceof DatabaseKey)) return false;

      DatabaseKey key = (DatabaseKey) o;

      if (!_url.equals(key._url)) return false;

      return (_catalog == key._catalog || _catalog != null && _catalog.equals(key._catalog));
    }
  }
}