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

📄 davrepository.java

📁 这是linux下ssl vpn的实现程序
💻 JAVA
字号:
/* ========================================================================== *
 * Copyright (C) 2004-2005 Pier Fumagalli <http://www.betaversion.org/~pier/> *
 *                            All rights reserved.                            *
 * ========================================================================== *
 *                                                                            *
 * Licensed under the  Apache License, Version 2.0  (the "License").  You may *
 * not use this file except in compliance with the License.  You may obtain a *
 * copy of the License at <http://www.apache.org/licenses/LICENSE-2.0>.       *
 *                                                                            *
 * Unless  required  by applicable  law or  agreed  to  in writing,  software *
 * distributed under the License is distributed on an  "AS IS" BASIS, WITHOUT *
 * WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied.  See the *
 * License for the  specific language  governing permissions  and limitations *
 * under the License.                                                         *
 *                                                                            *
 * ========================================================================== */
package com.sslexplorer.vfs.webdav;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileSystemManager;
import org.apache.commons.vfs.VFS;

import com.sslexplorer.boot.Util;
import com.sslexplorer.core.BundleActionMessage;
import com.sslexplorer.core.CoreServlet;
import com.sslexplorer.policyframework.PolicyConstants;
import com.sslexplorer.policyframework.PolicyDatabase;
import com.sslexplorer.security.SessionInfo;
import com.sslexplorer.security.SystemDatabase;
import com.sslexplorer.vfs.NetworkPlace;
import com.sslexplorer.vfs.NetworkPlaceItem;

/**
 * <p>
 * A simple class representing a {@link File} based WebDAV repository.
 * </p>
 * 
 * @author <a href="http://www.betaversion.org/~pier/">Pier Fumagalli</a>
 */
public class DAVRepository {

    final static Log log = LogFactory.getLog(DAVRepository.class);

    /**
     * <p>
     * The {@link Set} of all configured {@link DAVListener}s.
     * </p>
     */
    private Set listeners = new HashSet();

    /**
     * <p>
     * The {@link FileSystemManager} used to retrieve resources
     * </p>
     */
    private FileSystemManager fsManager;

    /**
     * <p>
     * The {@link DAVStore} implementations being managed by the repository
     * </p>
     */
    private Map stores;

    private static DAVRepository instance;

    
    public static DAVRepository getInstance() throws DAVBundleActionMessageException {
    	return instance==null ? instance = new DAVRepository() : instance;
    }
    
    public DAVRepository() throws DAVBundleActionMessageException {
        try {
            fsManager = VFS.getManager();
        } catch (FileSystemException e1) {
            throw new DAVBundleActionMessageException(new BundleActionMessage("vfs", "vfs.fsManager.failed", e1.getMessage()));
        }
        try {
            stores = DAVStoreManager.getInstance().createStores(this);
        } catch (Exception e) {
            log.error(e);
            throw new DAVBundleActionMessageException(new BundleActionMessage("vfs", "vfs.store.creation.failed"));
        }
    }

    /**
     * <p>
     * Return the {@link DAVResource} associated with a {@link DAVResource}.
     * </p>
     * 
     * @param path an absolute or relative {@link String} identifying the
     *        resource.
     * @param transaction the {@link DAVTransaction} object that initiated this
     *        request
     * @return a <b>non-null</b> {@link DAVResource} instance.
     * @throws IOException
     */
    public DAVResource getResource(String path, DAVTransaction transaction) throws DAVBundleActionMessageException, IOException {

        if (path == null) {
            log.error("Cannot list store root.");
            throw new DAVBundleActionMessageException(new BundleActionMessage("vfs", "vfs.store.root", path));
        }
        
        path = DAVUtilities.stripLeadingSlash(path);
        if(path.startsWith("fs")) {
            path= DAVUtilities.stripLeadingSlash(path.substring(2));
        }

        String storeName = path;
        DAVStore store;
        String mountName = null;
        DAVMount mount;

        // Extract the store
        int idx = path.indexOf('/');
        if (idx != -1) {
            storeName = storeName.substring(0, idx);
            path = path.substring(idx + 1);
        } else {
            path = "";
        }

        if (storeName.equals("")) {
            return getRepositoryResource();
        } else {
            store = (DAVStore) stores.get(storeName);
            if (store == null) {
                log.error("No store named \"" + storeName + "\".");
                throw new DAVException(404, "No store named \"" + storeName + "\".");
            }
        }

        // Extract the mount
        mountName = path;
        idx = path.indexOf('/', 1);
        if (idx != -1) {
            mountName = mountName.substring(0, idx);
            path = path.substring(idx + 1);
        } else {
            path = "";
        }
        if (mountName.length() == 0) {
            return store.getStoreResource(transaction);
        }

        //
        try {
            mount = store.getMountFromString(mountName, transaction.getSessionInfo());
        }
        catch(Exception e) {
            log.error("Failed to get mount.", e);
            mount = null;
        }
        if (mount == null || mount.equals("")) {
            log.error("No mount named \"" + mountName + "\" for store \"" + storeName + "\".");
            throw new DAVException(404, "No mount named \"" + mountName + "\" for store \"" + storeName + "\".");
        }

        
        path = DAVUtilities.stripTrailingSlash(path);


        return mount.getResource(path, transaction);
    }

    /**
     * <p>
     * Add a new {@link DAVListener} to the list of instances notified by this
     * {@link DAVStoreRepository}.
     * </p>
     */
    public void addListener(DAVListener listener) {
        if (listener != null)
            this.listeners.add(listener);
    }

    /**
     * <p>
     * Remove a {@link DAVListener} from the list of instances notified by this
     * {@link DAVStoreRepository}.
     * </p>
     */
    public void removeListener(DAVListener listener) {
        if (listener != null)
            this.listeners.remove(listener);
    }

    /**
     * <p>
     * Notify all configured {@link DAVListener}s of an event.
     * </p>
     */
    protected void notify(DAVResource resource, int event) {
        if (resource == null)
            throw new NullPointerException("Null resource");
        if (resource.getMount().getStore().getRepository() != this)
            throw new IllegalArgumentException("Invalid resource");

        Iterator iterator = this.listeners.iterator();
        while (iterator.hasNext())
            try {
                ((DAVListener) iterator.next()).notify(resource, event);
            } catch (RuntimeException exception) {
                // Swallow any RuntimeException thrown by listeners.
            }
    }

    public FileSystemManager getFileSystemManager() {
        return fsManager;
    }

    public DAVResource getRepositoryResource() {
        try {
            return new RepositoryResource(new URI(""));
        }
        catch(Exception e) {
            // shouldn't happen
            return null;
        }
    }

    public NetworkPlace createNetworkPlaceAndRegister(String scheme, String shortName, String description, String uri, boolean readOnly,
                    boolean allowResursive, boolean noDelete, boolean showHidden, SessionInfo info, int parentResourcePermission)
                    throws DAVBundleActionMessageException, Exception {
        SystemDatabase sdb = CoreServlet.getServlet().getSystemDatabase();
        NetworkPlace np = sdb.createNetworkPlace(scheme, shortName, description, uri, readOnly, allowResursive, noDelete, showHidden,
                        parentResourcePermission);
//        registerMountWithStore(np, info);
        return np;
    }

    public List refreshNetworkMounts(SessionInfo session) throws DAVBundleActionMessageException, Exception {

        List networkPlaceItems = new ArrayList();
        SystemDatabase sdb = CoreServlet.getServlet().getSystemDatabase();
        PolicyDatabase pdb = CoreServlet.getServlet().getPolicyDatabase();
        List granted = pdb.getGrantedResourcesOfType(session.getUser(), PolicyConstants.NETWORK_PLACE_RESOURCE_TYPE);
        for (Iterator i = granted.iterator(); i.hasNext();) {
            Integer r = (Integer) i.next();
            try {
                NetworkPlace np = sdb.getNetworkPlace(r.intValue());
                DAVStore store = getStore(np.getScheme());
                if(store == null) {
                    throw new Exception("No stored for network place URI " + np.getUri());
                }
                DAVMount mount = store.getMountFromString(np.getResourceName(), session);
                if (np.getType() != NetworkPlace.TYPE_HIDDEN && mount != null) {
                    NetworkPlaceItem npi = new NetworkPlaceItem(np, mount.getMountString(), CoreServlet.getServlet()
                                    .getPolicyDatabase().getPoliciesAttachedToResource(np), np.sessionPasswordRequired(session));
                    networkPlaceItems.add(npi);
                }
            } catch (Exception e) {
                log.warn("Failed to register mount " + r.intValue() + " with store.", e);
            }
        }
        return networkPlaceItems;
    }

    /**
     * Get a store that will handle a given a scheme. 
     * 
     * @param scheme
     * @return store
     */
    public DAVStore getStore(String scheme) {
        for(Iterator i = stores.values().iterator(); i.hasNext(); ) {
            DAVStore s = (DAVStore)i.next();
            if(s.willHandle(scheme)) {
                return s;
            }
        }
        return null;
    }

    public String validateUserEnteredPath(String path) throws DAVBundleActionMessageException {

        Iterator itr = stores.values().iterator();
        if (itr != null) {
            while (itr.hasNext()) {
                DAVStore store = (DAVStore) itr.next();
                try {
                    return store.validateUserEnteredPath(path);
                }
                catch(Exception e) {                    
                	if (log.isDebugEnabled())
                		log.debug("Store " + store.getName() + " didn't format path, can't be this one.");
                }
            }
        }
        throw new DAVBundleActionMessageException(new BundleActionMessage("vfs", "vfs.path.unformatable", path));
    }
    
    class RepositoryResource extends AbstractDAVResource {

        public RepositoryResource(URI relativeUri) {
            super(relativeUri, true, "", null);
        }

        public Iterator getChildren() {
            List l = new ArrayList();
            for(Iterator i = stores.values().iterator(); i.hasNext(); ) {
                l.add(((DAVStore)i.next()).getStoreResource(getTransaction()));
            }
            return l.iterator();
        }
        
    }
}

⌨️ 快捷键说明

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