⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cmssetupdb.java

📁 找了很久才找到到源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        columnName = column == null ? null : column.toUpperCase();
        result = hasTableOrColumnCaseSensitive(tableName, columnName);

        if (!result) {
            tableName = table == null ? null : table.toLowerCase();
            columnName = column == null ? null : column.toLowerCase();
            result = result || hasTableOrColumnCaseSensitive(tableName, columnName);
        }

        return result;
    }

    /**
     * Checks if the given table, column or combination of both is available in the database in a case sensitive way.<P>
     * 
     * @param table the sought table
     * @param column the sought column
     * 
     * @return true if the requested table/column is available, false if not
     */
    public boolean hasTableOrColumnCaseSensitive(String table, String column) {

        boolean result = false;
        ResultSet set = null;

        try {
            if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(column)) {
                // Check if the column is given
                set = m_con.getMetaData().getColumns(null, null, table, column);
                if (set.next()) {
                    String colname = set.getString("COLUMN_NAME");
                    if (colname.equalsIgnoreCase(column)) {
                        result = true; // The column is available
                    }
                }
            } else if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(table)) {
                // Check the table 
                set = m_con.getMetaData().getTables(null, null, table, null);
                if (set.next()) {
                    String tablename = set.getString("TABLE_NAME");
                    if (tablename.equalsIgnoreCase(table)) {
                        result = true;
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            result = false;
        } finally {
            try {
                if (set != null) {
                    set.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * Checks if internal errors occurred.<p>
     * 
     * @return true if internal errors occurred
     */
    public boolean noErrors() {

        return m_errors.isEmpty();
    }

    /**
     * Sets a new internal connection to the database.<p>
     * 
     * @param conn the connection to use
     */
    public void setConnection(Connection conn) {

        m_con = conn;
    }

    /**
     * Creates a new internal connection to the database.<p>
     * 
     * @param DbDriver JDBC driver class name
     * @param DbConStr JDBC connect URL
     * @param DbConStrParams JDBC connect URL params, or null
     * @param DbUser JDBC database user
     * @param DbPwd JDBC database password
     */
    public void setConnection(String DbDriver, String DbConStr, String DbConStrParams, String DbUser, String DbPwd) {

        String jdbcUrl = DbConStr;
        try {
            if (DbConStrParams != null) {
                jdbcUrl += DbConStrParams;
            }
            Class.forName(DbDriver).newInstance();
            m_con = DriverManager.getConnection(jdbcUrl, DbUser, DbPwd);

            System.out.print("OpenCms setup connection established: " + m_con);
            System.out.println(" [autocommit: " + m_con.getAutoCommit() + "]");

        } catch (ClassNotFoundException e) {
            System.out.println("Class not found exception: " + e);
            m_errors.addElement(Messages.get().getBundle().key(Messages.ERR_LOAD_JDBC_DRIVER_1, DbDriver));
            m_errors.addElement(CmsException.getStackTraceAsString(e));
        } catch (Exception e) {
            System.out.println("Exception: " + e);
            m_errors.addElement(Messages.get().getBundle().key(Messages.ERR_DB_CONNECT_1, DbConStr));
            m_errors.addElement(CmsException.getStackTraceAsString(e));
        }
    }

    /**
     * Calls an update script.<p>
     * 
     * @param updateScript the update script code
     * @param replacers the replacers to use in the script code
     */
    public void updateDatabase(String updateScript, Map replacers) {

        StringReader reader = new StringReader(updateScript);
        executeSql(reader, replacers, true);
    }

    /**
     * Calls an update script.<p>
     * 
     * @param updateScript the update script code
     * @param replacers the replacers to use in the script code
     * @param abortOnError indicates if the script is aborted if an error occurs
     */
    public void updateDatabase(String updateScript, Map replacers, boolean abortOnError) {

        StringReader reader = new StringReader(updateScript);
        executeSql(reader, replacers, abortOnError);
    }

    /**
     * Creates and executes a database statment from a String.<p>
     * 
     * @param query the query to execute
     * @param replacer the replacements to perform in the script
     * @param params the list of parameters for the statement
     * 
     * @return the result set of the query 
     * 
     * @throws SQLException if something goes wrong
     */
    public int updateSqlStatement(String query, Map replacer, List params) throws SQLException {

        String queryToExecute = query;
        // Check if a map of replacements is given
        if (replacer != null) {
            queryToExecute = replaceTokens(query, replacer);
        }

        int result;
        PreparedStatement stmt = null;
        stmt = m_con.prepareStatement(queryToExecute);
        try {
            // Check the params
            if (params != null) {
                for (int i = 0; i < params.size(); i++) {
                    Object item = params.get(i);

                    // Check if the parameter is a string
                    if (item instanceof String) {
                        stmt.setString(i + 1, (String)item);
                    }
                    if (item instanceof Integer) {
                        Integer number = (Integer)item;
                        stmt.setInt(i + 1, number.intValue());
                    }
                    if (item instanceof Long) {
                        Long longNumber = (Long)item;
                        stmt.setLong(i + 1, longNumber.longValue());
                    }

                    // If item is none of types above set the statement to use the bytes
                    if (!(item instanceof Integer) && !(item instanceof String) && !(item instanceof Long)) {
                        try {
                            stmt.setBytes(i + 1, CmsDataTypeUtil.dataSerialize(item));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            if (!queryToExecute.startsWith("UPDATE CMS_ONLINE_STRUCTURE SET STRUCTURE_VERSION")
                && !queryToExecute.startsWith("UPDATE CMS_OFFLINE_STRUCTURE SET STRUCTURE_VERSION")) {
                System.out.println("executing query: " + queryToExecute);
                if ((params != null) && !params.isEmpty()) {
                    System.out.println("params: " + params);
                }
            }
            result = stmt.executeUpdate();
        } finally {
            stmt.close();
        }

        return result;
    }

    /**
     * @see java.lang.Object#finalize()
     */
    protected void finalize() throws Throwable {

        try {
            closeConnection();
        } catch (Throwable t) {
            // ignore
        }
        super.finalize();
    }

    /**
     * Internal method to parse and execute a setup script.<p>
     * 
     * @param inputReader an input stream reader on the setup script
     * @param replacers the replacements to perform in the script
     * @param abortOnError if a error occurs this flag indicates if to continue or to abort
     */
    private void executeSql(Reader inputReader, Map replacers, boolean abortOnError) {

        String statement = "";
        LineNumberReader reader = null;
        String line = null;

        // parse the setup script 
        try {
            reader = new LineNumberReader(inputReader);

            while (true) {
                line = reader.readLine();
                if (line == null) {
                    break;
                }
                StringTokenizer st = new StringTokenizer(line);

                while (st.hasMoreTokens()) {
                    String currentToken = st.nextToken();

                    // comment! Skip rest of the line
                    if (currentToken.startsWith("#")) {
                        break;
                    }

                    // not to be executed
                    if (currentToken.startsWith("prompt")) {
                        break;
                    }

                    // add token to query 
                    statement += " " + currentToken;

                    // query complete (terminated by ';') 
                    if (currentToken.endsWith(";")) {
                        // cut of ';' at the end 
                        statement = statement.substring(0, (statement.length() - 1));

                        // normal statement, execute it
                        try {
                            if (replacers != null) {
                                statement = replaceTokens(statement, replacers);
                                executeStatement(statement);
                            } else {
                                executeStatement(statement);
                            }
                        } catch (SQLException e) {
                            if (!abortOnError) {
                                if (m_errorLogging) {
                                    m_errors.addElement("Error executing SQL statement: " + statement);
                                    m_errors.addElement(CmsException.getStackTraceAsString(e));
                                }
                            } else {
                                throw e;
                            }
                        }

                        // reset
                        statement = "";
                    }
                }

                statement += " \n";
            }
        } catch (SQLException e) {
            if (m_errorLogging) {
                m_errors.addElement("Error executing SQL statement: " + statement);
                m_errors.addElement(CmsException.getStackTraceAsString(e));
            }
        } catch (Exception e) {
            if (m_errorLogging) {
                m_errors.addElement("Error parsing database setup SQL script in line: " + line);
                m_errors.addElement(CmsException.getStackTraceAsString(e));
            }
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                // noop
            }
        }
    }

    /**
     * Internal method to parse and execute a setup script.<p>
     * 
     * @param databaseKey the database variant of the script
     * @param sqlScript the name of the script
     * @param replacers the replacements to perform in the script
     * @param abortOnError if a error occurs this flag indicates if to continue or to abort
     */
    private void executeSql(String databaseKey, String sqlScript, Map replacers, boolean abortOnError) {

        String filename = null;
        try {
            filename = m_basePath
                + "setup"
                + File.separator
                + "database"
                + File.separator
                + databaseKey
                + File.separator
                + sqlScript;
            executeSql(new FileReader(filename), replacers, abortOnError);
        } catch (FileNotFoundException e) {
            if (m_errorLogging) {
                m_errors.addElement("Database setup SQL script not found: " + filename);
                m_errors.addElement(CmsException.getStackTraceAsString(e));
            }
        }
    }

    /**
     * Creates and executes a database statment from a String.<p>
     * 
     * @param statement the database statement
     * 
     * @throws SQLException if something goes wrong
     */
    private void executeStatement(String statement) throws SQLException {

        Statement stmt = null;

        try {
            stmt = m_con.createStatement();
            stmt.execute(statement);
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
    }

    /**
     * Replaces tokens "${xxx}" in a specified SQL query.<p>
     * 
     * @param sql a SQL query
     * @param replacers a Map with values keyed by "${xxx}" tokens
     * @return the SQl query with all "${xxx}" tokens replaced
     */
    private String replaceTokens(String sql, Map replacers) {

        Iterator keys = replacers.entrySet().iterator();
        while (keys.hasNext()) {
            Map.Entry entry = (Map.Entry)keys.next();

            String key = (String)entry.getKey();
            String value = (String)entry.getValue();

            sql = CmsStringUtil.substitute(sql, key, value);
        }

        return sql;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -