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

📄 cmsdbaccess.java

📁 cms是开源的框架
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
/*
* File   : $Source: /usr/local/cvs/opencms/src-modules/com/opencms/defaults/master/genericsql/CmsDbAccess.java,v $
* Date   : $Date: 2005/06/27 23:22:23 $
* Version: $Revision: 1.7 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (C) 2001  The OpenCms Group
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* For further information about OpenCms, please see the
* OpenCms Website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package com.opencms.defaults.master.genericsql;

import org.opencms.db.CmsDbUtil;
import org.opencms.db.CmsPublishedResource;
import org.opencms.db.CmsUserSettings;
import org.opencms.file.CmsGroup;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsUser;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.security.CmsSecurityException;
import org.opencms.setup.CmsSetupDb;
import org.opencms.util.CmsUUID;

import com.opencms.defaults.master.CmsMasterContent;
import com.opencms.defaults.master.CmsMasterDataSet;
import com.opencms.defaults.master.CmsMasterMedia;
import com.opencms.legacy.CmsLegacyException;
import com.opencms.legacy.CmsLegacySecurityException;

import java.io.ByteArrayInputStream;
import java.lang.reflect.Constructor;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

/**
 * This class provides methods to access the database in a generic way.
 * 
 * @deprecated Will not be supported past the OpenCms 6 release.
 */
public class CmsDbAccess {

    /** The root channel of the module */
    protected String m_rootChannel = "/";

    /** TODO: delete this after successful change of dbpool */
    private String m_poolUrl;

    /** 'Constants' file. */
    protected com.opencms.defaults.master.genericsql.CmsSqlManager m_sqlManager;

    /**
     * Public empty constructor, call "init(String)" on this class afterwards.
     * This allows more flexible custom module development.<p>
     */
    public CmsDbAccess() {}

    /**
     * Constructs a new DbAccessObject and calls init(String) with the given String.<p>
     * @param dbPool the pool to access resources.
     */
    public CmsDbAccess(String dbPool) {
        init(dbPool);
    }

    /**
     * Initializes the SqlManager with the used pool.<p>
     */
    public com.opencms.defaults.master.genericsql.CmsSqlManager init(String dbPool) {
        m_sqlManager = initQueries(dbPool, getClass());
        m_poolUrl = dbPool;
        
        return m_sqlManager;
    }

    /**
     * Retrieve the correct instance of the queries holder.
     * This method should be overloaded if other query strings should be used.<p>
     */
    public com.opencms.defaults.master.genericsql.CmsSqlManager initQueries(String dbPoolUrl, Class currentClass) {
        return new com.opencms.defaults.master.genericsql.CmsSqlManager(dbPoolUrl, currentClass);
    }

    /**
     * Checks if the master module table is available by performing
     * a simple query on it.<p>
     * 
     * @return true if the query was successfully performed, false otherwise
     */
    public boolean checkTables() {
        PreparedStatement stmt = null;
        Connection conn = null;
        try {
            conn = m_sqlManager.getConnection();
            stmt = m_sqlManager.getPreparedStatement(conn, "check_module_master");
            stmt.executeQuery();
            return true;                
                
        } catch (SQLException exc) {
            return false;
            
        } finally {
            m_sqlManager.closeAll(null, conn, stmt, null);
        }
    }

    /**
     * Performs an update script on a database.<p>
     * 
     * @param updateScript the script
     * @param replacers parameter/values to replace within the script
     * @throws CmsException if something goes wrong
     */
    public void updateDatabase(String updateScript, Map replacers) throws CmsException {
        CmsSetupDb setup = new CmsSetupDb(""); /* TODO: add base path, even if not needed */
        Connection conn = null;
        
        try {
            conn = m_sqlManager.getConnection();
            setup.setConnection(conn);
            setup.updateDatabase(updateScript, replacers, true);
            
            Vector errors = setup.getErrors();
            if (!errors.isEmpty()) {
                StringBuffer errorMessages = new StringBuffer();
                for (Iterator i = errors.iterator(); i.hasNext();) {
                    errorMessages.append((String)i.next());
                    errorMessages.append("\n");
                }
                throw new CmsLegacyException(errorMessages.toString(), CmsLegacyException.C_SQL_ERROR);
            }
        } catch (SQLException exc) {
            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
        } finally {
            m_sqlManager.closeAll(null, conn, null, null);
        }
    }
    
    /**
     * Set the root channel of the content.<p>
     * 
     * @param newRootChannel the new value for the rootChannel.
     */
    public void setRootChannel(String newRootChannel) {
        m_rootChannel = newRootChannel;
    }

    /**
     * Get the root channel of the content.<p>
     * 
     * @return String the root channel.
     */
    public String getRootChannel() {
        return m_rootChannel;
    }

    /**
     * Inserts a new single row in the database with the dataset.<p>
     * 
     * @param cms the CmsObject to get access to cms resources.
     * @param content the CmsMasterContent to write to the database.
     * @param dataset the set of data for this contentdefinition.
     * @throws CmsException if somethong goes wrong
     */
    public void insert(CmsObject cms, CmsMasterContent content, CmsMasterDataSet dataset) throws CmsException {
        if (isOnlineProject(cms)) {
            // this is the onlineproject - don't write into this project directly
            throw new CmsSecurityException(Messages.get().container(Messages.ERR_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT_0));
        }
       
        if (dataset.m_masterId == null || CmsUUID.getNullUUID().equals(dataset.m_masterId)) {
            // create a new master ID
            dataset.m_masterId = new CmsUUID();
        }
        
        int projectId = cms.getRequestContext().currentProject().getId();
        long currentTime = new java.util.Date().getTime();
        
        CmsUUID currentUserId = cms.getRequestContext().currentUser().getId();        
        dataset.m_userId = currentUserId;

        CmsUUID defaultGroupId = CmsUUID.getNullUUID();
        String defaultGroupName = null;
        
        try {
            defaultGroupName = (String)cms.getRequestContext().currentUser().getAdditionalInfo(
                CmsUserSettings.ADDITIONAL_INFO_DEFAULTGROUP);
            
            if (defaultGroupName == null || "".equalsIgnoreCase(defaultGroupName)) {
                if (CmsLog.getLog(this).isWarnEnabled()) {
                    CmsLog.getLog(this).warn(
                        "Error reading default group of user "
                        + cms.getRequestContext().currentUser().getName()
                        + ", using group "
                        + OpenCms.getDefaultUsers().getGroupUsers()
                        + " instead");
                }
                
                defaultGroupName = OpenCms.getDefaultUsers().getGroupUsers();
            }
            
            CmsGroup defaultGroup = cms.readGroup(defaultGroupName);
            defaultGroupId = defaultGroup.getId();
        } catch (CmsException e) {
            if (CmsLog.getLog(this).isErrorEnabled()) {
                CmsLog.getLog(this).error(
                    "Error reading default group "
                        + defaultGroupName
                        + " of user "
                        + cms.getRequestContext().currentUser().getName(),
                    e);
            }

            defaultGroupId = CmsUUID.getNullUUID();
        }
        
        dataset.m_groupId = defaultGroupId;

        dataset.m_projectId = projectId;
        dataset.m_lockedInProject = projectId;
        dataset.m_state = CmsResource.STATE_NEW;
        dataset.m_lockedBy = currentUserId;
        dataset.m_lastModifiedBy = currentUserId;
        dataset.m_dateCreated = currentTime;
        dataset.m_dateLastModified = currentTime;

        PreparedStatement stmt = null;
        Connection conn = null;
        try {
            conn = m_sqlManager.getConnection();
            stmt = m_sqlManager.getPreparedStatement(conn, "insert_offline");
            sqlFillValues(stmt, content.getSubId(), dataset);
            stmt.executeUpdate();
            // after inserting the row, we have to update media and channel tables
            updateMedia(dataset.m_masterId, dataset.m_mediaToAdd, new Vector(), new Vector());
            updateChannels(cms, dataset.m_masterId, dataset.m_channelToAdd, dataset.m_channelToDelete);
        } catch (SQLException exc) {
            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
        } finally {
            m_sqlManager.closeAll(null, conn, stmt, null);
        }
    }

    /**
     * Inserts a new row in the database with the copied dataset.<p>
     * 
     * @param cms the CmsObject to get access to cms resources.
     * @param content the CmsMasterContent to write to the database.
     * @param dataset the set of data for this contentdefinition.
     * @param mediaToAdd a Vector of media to add.
     * @param channelToAdd a Vector of channels to add.
     * @return CmsUUID The uuid of the new content definition
     * @throws CmsException in case something goes wrong
     */
    public CmsUUID copy(CmsObject cms, CmsMasterContent content, CmsMasterDataSet dataset, Vector mediaToAdd, Vector channelToAdd) throws CmsException {
        if (isOnlineProject(cms)) {
            // this is the onlineproject - don't write into this project directly
            throw new CmsSecurityException(Messages.get().container(Messages.ERR_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT_0));
        }
        if (dataset.m_versionId != CmsDbUtil.UNKNOWN_ID) {
            // this is not the online row - it was read from history
            // don't write it!
            throw new CmsLegacySecurityException("Can't update a cd with a backup cd ", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
        }

⌨️ 快捷键说明

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