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

📄 cmssynchronize.java

📁 找了很久才找到到源代码
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/*
 * File   : $Source: /usr/local/cvs/opencms/src/org/opencms/synchronize/CmsSynchronize.java,v $
 * Date   : $Date: 2007-08-13 16:30:16 $
 * Version: $Revision: 1.66 $
 *
 * This library is part of OpenCms -
 * the Open Source Content Management System
 *
 * Copyright (c) 2002 - 2007 Alkacon Software GmbH (http://www.alkacon.com)
 *
 * 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 Alkacon Software GmbH, please see the
 * company website: http://www.alkacon.com
 *
 * For further information about OpenCms, please see the
 * project 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 org.opencms.synchronize;

import org.opencms.db.CmsDbIoException;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.types.CmsResourceTypeFolder;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.report.I_CmsReport;
import org.opencms.util.CmsFileUtil;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.logging.Log;

/**
 * Contains all methods to synchronize the VFS with the "real" FS.<p>
 *
 * @author Michael Emmerich 
 * 
 * @version $Revision: 1.66 $ 
 * 
 * @since 6.0.0 
 */
public class CmsSynchronize {

    /** Flag to import a deleted resource in the VFS. */
    static final int DELETE_VFS = 3;

    /** Flag to export a resource from the VFS to the FS. */
    static final int EXPORT_VFS = 1;

    /** Filname of the synclist file on the server FS. */
    static final String SYNCLIST_FILENAME = "#synclist.txt";

    /** Flag to import a resource from the FS to the VFS. */
    static final int UPDATE_VFS = 2;

    /** The log object for this class. */
    private static final Log LOG = CmsLog.getLog(CmsSynchronize.class);

    /** List to store all file modification interface implementations. */
    private static List m_synchronizeModifications = new ArrayList();

    /** The CmsObject. */
    private CmsObject m_cms;

    /** Counter for logging. */
    private int m_count;

    /** The path in the "real" file system where the resources have to be synchronized to. */
    private String m_destinationPathInRfs;

    /** Hashmap for the new synchronisation list of the current sync process. */
    private HashMap m_newSyncList;

    /** The report to write the output to. */
    private I_CmsReport m_report;

    /** Hashmap for the synchronisation list of the last sync process. */
    private HashMap m_syncList;

    /**
     * Creates a new CmsSynchronize object which automatically start the 
     * synchronisation process.<p>
     *
     * @param cms the current CmsObject
     * @param settings the synchonization settings to use
     * @param report the report to write the output to
     * 
     * @throws CmsException if something goes wrong
     * @throws CmsSynchronizeException if the synchronization process cannot be started
     */
    public CmsSynchronize(CmsObject cms, CmsSynchronizeSettings settings, I_CmsReport report)
    throws CmsSynchronizeException, CmsException {

        // TODO: initialize the list of file modifiaction interface implementations

        // do the synchronization only if the synchonization folders in the VFS
        // and the FS are valid
        if ((settings != null) && (settings.isSyncEnabled())) {

            // create an independent copy of the provided user context
            m_cms = OpenCms.initCmsObject(cms);
            // set site to root site
            m_cms.getRequestContext().setSiteRoot("/");

            m_report = report;
            m_count = 1;

            // get the destination folder
            m_destinationPathInRfs = settings.getDestinationPathInRfs();

            // check if target folder exists and is writeable
            File destinationFolder = new File(m_destinationPathInRfs);
            if (!destinationFolder.exists() || !destinationFolder.isDirectory()) {
                // destination folder does not exist
                throw new CmsSynchronizeException(Messages.get().container(
                    Messages.ERR_RFS_DESTINATION_NOT_THERE_1,
                    m_destinationPathInRfs));
            }
            if (!destinationFolder.canWrite()) {
                // destination folder can't be written to
                throw new CmsSynchronizeException(Messages.get().container(
                    Messages.ERR_RFS_DESTINATION_NO_WRITE_1,
                    m_destinationPathInRfs));
            }

            // create the sync list for this run
            m_syncList = readSyncList();
            m_newSyncList = new HashMap();

            Iterator i = settings.getSourceListInVfs().iterator();
            while (i.hasNext()) {
                // iterate all source folders
                String sourcePathInVfs = (String)i.next();
                String destPath = m_destinationPathInRfs + sourcePathInVfs.replace('/', File.separatorChar);

                report.println(org.opencms.workplace.threads.Messages.get().container(
                    org.opencms.workplace.threads.Messages.RPT_SYNCHRONIZE_FOLDERS_2,
                    sourcePathInVfs,
                    destPath), I_CmsReport.FORMAT_HEADLINE);
                // synchronice the VFS and the RFS
                syncVfsToRfs(sourcePathInVfs);
            }

            // remove files from the RFS
            removeFromRfs(m_destinationPathInRfs);
            i = settings.getSourceListInVfs().iterator();

            while (i.hasNext()) {
                // add new files from the RFS
                copyFromRfs((String)i.next());
            }

            // write the sync list
            writeSyncList();

            // free mem
            m_syncList = null;
            m_newSyncList = null;
            m_cms = null;
        } else {
            throw new CmsSynchronizeException(Messages.get().container(Messages.ERR_INIT_SYNC_0));
        }
    }

    /**
     * Copys all resources from the FS which are not existing in the VFS yet. <p>
     * 
     * @param folder the folder in the VFS to be synchronized with the FS
     * @throws CmsException if something goes wrong
     */
    private void copyFromRfs(String folder) throws CmsException {

        // get the corresponding folder in the FS
        File[] res;
        File fsFile = getFileInRfs(folder);
        // first of all, test if this folder existis in the VFS. If not, create it
        try {
            m_cms.readFolder(translate(folder), CmsResourceFilter.IGNORE_EXPIRATION);
        } catch (CmsException e) {
            // the folder could not be read, so create it
            String foldername = translate(folder);
            m_report.print(org.opencms.report.Messages.get().container(
                org.opencms.report.Messages.RPT_SUCCESSION_1,
                String.valueOf(m_count++)), I_CmsReport.FORMAT_NOTE);
            m_report.print(Messages.get().container(Messages.RPT_IMPORT_FOLDER_0), I_CmsReport.FORMAT_NOTE);
            m_report.print(org.opencms.report.Messages.get().container(
                org.opencms.report.Messages.RPT_ARGUMENT_1,
                fsFile.getAbsolutePath().replace('\\', '/')));
            m_report.print(Messages.get().container(Messages.RPT_FROM_FS_TO_0), I_CmsReport.FORMAT_NOTE);
            m_report.print(org.opencms.report.Messages.get().container(
                org.opencms.report.Messages.RPT_ARGUMENT_1,
                foldername));
            m_report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));

            CmsResource newFolder = m_cms.createResource(foldername, CmsResourceTypeFolder.RESOURCE_TYPE_ID);
            // now check if there is some external method to be called which 
            // should modify the imported resource in the VFS
            Iterator i = m_synchronizeModifications.iterator();
            while (i.hasNext()) {
                try {
                    ((I_CmsSynchronizeModification)i.next()).modifyVfs(m_cms, newFolder, fsFile);
                } catch (CmsSynchronizeException e1) {
                    break;
                }
            }
            // we have to read the new resource again, to get the correct timestamp
            newFolder = m_cms.readFolder(foldername, CmsResourceFilter.IGNORE_EXPIRATION);
            String resourcename = m_cms.getSitePath(newFolder);
            // add the folder to the sync list
            CmsSynchronizeList sync = new CmsSynchronizeList(
                folder,
                resourcename,
                newFolder.getDateLastModified(),
                fsFile.lastModified());
            m_newSyncList.put(resourcename, sync);

            m_report.println(
                org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
                I_CmsReport.FORMAT_OK);
        }
        // since the check has been done on folder basis, this must be a folder
        if (fsFile.isDirectory()) {
            // get all resources in this folder
            res = fsFile.listFiles();

            // now loop through all resources
            for (int i = 0; i < res.length; i++) {
                // get the relative filename
                String resname = res[i].getAbsolutePath();
                resname = resname.substring(m_destinationPathInRfs.length());
                // translate the folder seperator if nescessary
                resname = resname.replace(File.separatorChar, '/');
                // now check if this resource was already processed, by looking 
                // up the new sync list
                if (res[i].isFile()) {
                    if (!m_newSyncList.containsKey(translate(resname))) {
                        // this file does not exist in the VFS, so import it
                        importToVfs(res[i], resname, folder);
                    }
                } else {
                    // do a recursion if the current resource is a folder
                    copyFromRfs(resname + "/");
                }
            }
        }
    }

    /**
     * Creates a new file on the server FS.<p>
     *
     * @param newFile the file that has to be created
     * @throws CmsException if something goes wrong
     */
    private void createNewLocalFile(File newFile) throws CmsException {

        if (newFile.exists()) {
            throw new CmsSynchronizeException(Messages.get().container(Messages.ERR_EXISTENT_FILE_1, newFile.getPath()));
        }
        FileOutputStream fOut = null;
        try {
            File parentFolder = new File(newFile.getPath().replace('/', File.separatorChar).substring(
                0,
                newFile.getPath().lastIndexOf(File.separator)));
            parentFolder.mkdirs();
            if (parentFolder.exists()) {
                fOut = new FileOutputStream(newFile);
            } else {
                throw new CmsSynchronizeException(
                    Messages.get().container(Messages.ERR_CREATE_DIR_1, newFile.getPath()));
            }
        } catch (IOException e) {
            throw new CmsSynchronizeException(Messages.get().container(
                Messages.ERR_CREATE_FILE_1,
                this.getClass().getName(),
                newFile.getPath()), e);
        } finally {
            if (fOut != null) {
                try {
                    fOut.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    }

    /**
     * Deletes a resource in the VFS and updates the synchronisation lists.<p>
     * 
     * @param res The resource to be deleted
     * 
     * @throws CmsException if something goes wrong
     */
    private void deleteFromVfs(CmsResource res) throws CmsException {

        String resourcename = m_cms.getSitePath(res);

        m_report.print(org.opencms.report.Messages.get().container(
            org.opencms.report.Messages.RPT_SUCCESSION_1,
            String.valueOf(m_count++)), I_CmsReport.FORMAT_NOTE);
        if (res.isFile()) {
            m_report.print(Messages.get().container(Messages.RPT_DEL_FILE_0), I_CmsReport.FORMAT_NOTE);
        } else {
            m_report.print(Messages.get().container(Messages.RPT_DEL_FOLDER_0), I_CmsReport.FORMAT_NOTE);
        }
        m_report.print(org.opencms.report.Messages.get().container(
            org.opencms.report.Messages.RPT_ARGUMENT_1,
            resourcename));
        m_report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));

        // lock the file in the VFS, so that it can be updated
        m_cms.lockResource(resourcename);
        m_cms.deleteResource(resourcename, CmsResource.DELETE_PRESERVE_SIBLINGS);
        // Remove it from the sync list
        m_syncList.remove(translate(resourcename));

        m_report.println(

⌨️ 快捷键说明

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