-
-
diff --git a/source/java/org/alfresco/filesys/avm/AVMContext.java b/source/java/org/alfresco/filesys/avm/AVMContext.java
deleted file mode 100644
index e32a0d49af..0000000000
--- a/source/java/org/alfresco/filesys/avm/AVMContext.java
+++ /dev/null
@@ -1,667 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see .
- */
-
-package org.alfresco.filesys.avm;
-
-import java.util.StringTokenizer;
-
-import org.alfresco.error.AlfrescoRuntimeException;
-import org.alfresco.filesys.alfresco.AlfrescoContext;
-import org.alfresco.filesys.alfresco.AlfrescoDiskDriver;
-import org.alfresco.filesys.alfresco.IOControlHandler;
-import org.alfresco.jlan.server.filesys.DiskInterface;
-import org.alfresco.jlan.server.filesys.FileName;
-import org.alfresco.jlan.server.filesys.FileSystem;
-import org.alfresco.jlan.server.filesys.NotifyChange;
-import org.alfresco.jlan.server.filesys.cache.FileState;
-import org.alfresco.jlan.server.filesys.cache.FileStateCache;
-import org.alfresco.jlan.util.StringList;
-import org.alfresco.repo.avm.CreateStoreCallback;
-import org.alfresco.repo.avm.CreateVersionCallback;
-import org.alfresco.repo.avm.PurgeStoreCallback;
-import org.alfresco.repo.avm.PurgeVersionCallback;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * AVM Filesystem Context Class
- *
- * Contains per filesystem context.
- *
- * @author GKSpencer
- */
-public class AVMContext extends AlfrescoContext
- implements CreateStoreCallback, PurgeStoreCallback, CreateVersionCallback, PurgeVersionCallback {
-
- // Logging
-
- private static final Log logger = LogFactory.getLog(AVMContext.class);
-
- // Constants
- //
- // Version id that indicates the head version
-
- public static final int VERSION_HEAD = -1;
-
- // Store types to show in the virtualization view
-
- public static final int ShowNormalStores = 0x0001;
- public static final int ShowSiteStores = 0x0002;
- public static final int ShowStagingStores = 0x0004;
- public static final int ShowAuthorStores = 0x0008;
- public static final int ShowPreviewStores = 0x0010;
-
- // Store, root path and version
-
- private String m_storePath;
- private int m_version = VERSION_HEAD;
-
- // Flag to indicate if the virtualization view is enabled
- //
- // The first set of folders then map to the stores and the second layer map to the versions with
- // paths below.
-
- private boolean m_virtualView;
-
- // Virtualization view filtering options
-
- private int m_showOptions = ShowStagingStores + ShowAuthorStores;
-
- // List of newly created store names that need adding into the virtualization view
-
- private StringList m_newStores;
- private Object m_newStoresLock;
-
- // Allow admin user to write to web project staging stores
-
- private boolean m_allowAdminStagingWrites;
-
- // Auto create the store if it doesn't exist?
-
- private boolean m_createStore;
-
- /**
- * Default constructor allowing initialization by container.
- */
- public AVMContext()
- {
- }
-
- /**
- * Class constructor
- *
- *
Construct a context for a normal view onto a single store/version within AVM.
- *
- * @param filesysName String
- * @param storePath String
- * @param version int
- */
- public AVMContext( String filesysName, String storePath, int version)
- {
- setDeviceName(filesysName);
-
- // Set the store root path
- setStorePath(storePath);
-
- // Set the store version to use
- setVersion(version);
- }
-
- /**
- * Class constructor
- *
- *
Construct a context for a virtualization view onto all stores/versions within AVM.
- *
- * @param filesysName String
- * @param showOptions int
- * @param avmDriver AVMDiskDriver
- */
- public AVMContext( String filesysName, int showOptions, AVMDiskDriver avmDriver)
- {
- setDeviceName(filesysName);
-
- // Enable the virtualization view
- setVirtualView(true);
- setShowOptions(showOptions);
- }
-
- public void setStorePath(String path)
- {
- this.m_storePath = path;
- }
-
- public void setVersion(int version)
- {
- this.m_version = version;
- }
-
- public void setShowOptions(int showOptions)
- {
- this.m_showOptions = showOptions;
- }
-
- public void setStores(String showAttr)
- {
- if ( showAttr != null)
- {
- // Split the show options string
-
- StringTokenizer tokens = new StringTokenizer( showAttr, ",");
- StringList optList = new StringList();
-
- while ( tokens.hasMoreTokens())
- optList.addString( tokens.nextToken().trim().toLowerCase());
-
- // Build the show options mask
-
- this.m_showOptions = 0;
-
- if ( optList.containsString("normal"))
- this.m_showOptions += ShowNormalStores;
-
- if ( optList.containsString("site"))
- this.m_showOptions += ShowSiteStores;
-
- if ( optList.containsString("author"))
- this.m_showOptions += ShowAuthorStores;
-
- if ( optList.containsString("preview"))
- this.m_showOptions += ShowPreviewStores;
-
- if ( optList.containsString("staging"))
- this.m_showOptions += ShowStagingStores;
- }
- }
-
- public void setVirtualView(boolean isVirtualView)
- {
- this.m_virtualView = isVirtualView;
- }
-
- public boolean getCreateStore()
- {
- return m_createStore;
- }
-
- public void setCreateStore(boolean createStore)
- {
- m_createStore = createStore;
- }
-
-
- @Override
- public void initialize(AlfrescoDiskDriver filesysDriver)
- {
- if (m_virtualView)
- {
- // A context for a view onto all stores/versions within AVM.
- m_newStoresLock = new Object();
- m_newStores = new StringList();
-
- setShareName("VirtualView");
- }
- else
- {
- if (m_storePath == null
- || m_storePath.length() == 0)
- throw new AlfrescoRuntimeException("Device missing init value: storePath");
-
- // A context for a normal view onto a single store/version within AVM.
- if (m_storePath.endsWith("/"))
- m_storePath = m_storePath.substring(0, m_storePath.length() - 1);
-
- // Range check the version id
- if (m_version < 0 && m_version != AVMContext.VERSION_HEAD)
- throw new AlfrescoRuntimeException("Invalid store version id specified, " + m_version);
-
- setShareName(m_storePath + "(" + m_version + ")");
- }
- super.initialize(filesysDriver);
- }
-
- /**
- * Return the filesystem type, either FileSystem.TypeFAT or FileSystem.TypeNTFS.
- *
- * @return String
- */
- public String getFilesystemType()
- {
- return FileSystem.TypeNTFS;
- }
-
- /**
- * Return the store path
- *
- * @return String
- */
- public final String getStorePath()
- {
- return m_storePath;
- }
-
- /**
- * Return the version
- *
- * @return int
- */
- public final int isVersion()
- {
- return m_version;
- }
-
- /**
- * Check if the virtualization view is enabled
- *
- * @return boolean
- */
- public final boolean isVirtualizationView()
- {
- return m_virtualView;
- }
-
- /**
- * Check if the admin user is allowed to write to web project staging stores
- *
- * @return boolean
- */
- public final boolean allowAdminStagingWrites() {
- return m_allowAdminStagingWrites;
- }
-
- /**
- * Set the admin web project staging store writeable status
- *
- * @param writeable boolean
- */
- public final void setAllowAdminStagingWrites(boolean writeable) {
- m_allowAdminStagingWrites = writeable;
- }
-
- /**
- * Check if there are any new stores queued for adding to the virtualization view
- *
- * @return boolean
- */
- protected final boolean hasNewStoresQueued() {
- if ( m_newStores == null || m_newStores.numberOfStrings() == 0)
- return false;
- return true;
- }
-
- /**
- * Return the new stores queue, and reset the current queue
- *
- * @return StringList
- */
- protected StringList getNewStoresQueue() {
-
- StringList storesQueue = null;
-
- synchronized ( m_newStoresLock) {
- storesQueue = m_newStores;
- m_newStores = new StringList();
- }
-
- return storesQueue;
- }
-
- /**
- * Check if normal stores should be shown in the virtualization view
- *
- * @return boolean
- */
- public final boolean showNormalStores()
- {
- return (m_showOptions & ShowNormalStores) != 0 ? true : false;
- }
-
- /**
- * Check if site data stores should be shown in the virtualization view
- *
- * @return boolean
- */
- public final boolean showSiteStores()
- {
- return (m_showOptions & ShowSiteStores) != 0 ? true : false;
- }
-
- /**
- * Check if author stores should be shown in the virtualization view
- *
- * @return boolean
- */
- public final boolean showAuthorStores()
- {
- return (m_showOptions & ShowAuthorStores) != 0 ? true : false;
- }
-
- /**
- * Check if preview stores should be shown in the virtualization view
- *
- * @return boolean
- */
- public final boolean showPreviewStores()
- {
- return (m_showOptions & ShowPreviewStores) != 0 ? true : false;
- }
-
- /**
- * Check if staging stores should be shown in the virtualization view
- *
- * @return boolean
- */
- public final boolean showStagingStores()
- {
- return (m_showOptions & ShowStagingStores) != 0 ? true : false;
- }
-
- /**
- * Check if the specified store type should be visible
- *
- * @param storeType int
- * @return boolean
- */
- public final boolean showStoreType(int storeType)
- {
- boolean showStore = false;
-
- switch (storeType)
- {
- case StoreType.Normal:
- showStore = showNormalStores();
- break;
- case StoreType.SiteStore:
- showStore = showSiteStores();
- break;
- case StoreType.WebAuthorMain:
- showStore = showAuthorStores();
- break;
- case StoreType.WebStagingMain:
- showStore = showStagingStores();
- break;
- case StoreType.WebAuthorPreview:
- case StoreType.WebStagingPreview:
- showStore = showPreviewStores();
- break;
- }
-
- return showStore;
- }
-
- /**
- * Close the filesystem context
- */
- public void CloseContext() {
-
- // Call the base class
-
- super.CloseContext();
- }
-
- /**
- * Create the I/O control handler for this filesystem type
- *
- * @param filesysDriver DiskInterface
- * @return IOControlHandler
- */
- protected IOControlHandler createIOHandler( DiskInterface filesysDriver)
- {
- return null;
- }
-
- /**
- * Create store call back handler
- *
- * @param storeName String
- * @param versionID int
- */
- public void storeCreated(String storeName)
- {
- // Not interested if the virtualization view is not enabled
-
- if ( isVirtualizationView() == false)
- return;
-
- // Make sure the file state cache is enabled
-
- FileStateCache fsTable = getStateCache();
- if ( fsTable == null)
- return;
-
- // Find the file state for the root folder
-
- FileState rootState = fsTable.findFileState( FileName.DOS_SEPERATOR_STR, true);
-
- if ( rootState != null)
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("Queueing new store " + storeName + " for addition to virtualization view");
-
- // Add the new store name to the list to be picked up by the next file server access
- // to the filesystem
-
- synchronized ( m_newStoresLock) {
-
- // Add the new store name
-
- m_newStores.addString( storeName);
- }
- }
- }
-
- /**
- * Purge store call back handler
- *
- * @param storeName String
- */
- public void storePurged(String storeName)
- {
- // Not interested if the virtualization view is not enabled
-
- if ( isVirtualizationView() == false)
- return;
-
- // Make sure the file state cache is enabled
-
- FileStateCache fsTable = getStateCache();
- if ( fsTable == null)
- return;
-
- // Find the file state for the root folder
-
- FileState rootState = fsTable.findFileState( FileName.DOS_SEPERATOR_STR);
-
- if ( rootState != null && rootState.hasPseudoFiles())
- {
- // Remove the pseudo folder for the store
-
- rootState.getPseudoFileList().removeFile( storeName, false);
-
- // Build the filesystem relative path to the deleted store folder
-
- StringBuilder pathStr = new StringBuilder();
-
- pathStr.append( FileName.DOS_SEPERATOR);
- pathStr.append( storeName);
-
- // Remove the file state for the deleted store
-
- String storePath = pathStr.toString();
- fsTable.removeFileState( storePath);
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug( "Removed pseudo folder for purged store " + storeName);
-
- // Update the file state modify time
-
- rootState.updateModifyDateTime();
-
- // Send a change notification for the deleted folder
-
- if ( hasChangeHandler())
- {
- // Send the change notification
-
- getChangeHandler().notifyDirectoryChanged(NotifyChange.ActionRemoved, storePath);
- }
- }
- }
-
- /**
- * Create version call back handler
- *
- * @param storeName String
- * @param versionID int
- */
- public void versionCreated(String storeName, int versionID)
- {
- // Not interested if the virtualization view is not enabled
-
- if ( isVirtualizationView() == false)
- return;
-
- // Make sure the file state cache is enabled
-
- FileStateCache fsTable = getStateCache();
- if ( fsTable == null)
- return;
-
- // Build the path to the store version folder
-
- StringBuilder pathStr = new StringBuilder();
-
- pathStr.append( FileName.DOS_SEPERATOR);
- pathStr.append( storeName);
- pathStr.append( FileName.DOS_SEPERATOR);
- pathStr.append( AVMPath.VersionsFolder);
-
- // Find the file state for the store versions folder
-
- FileState verState = fsTable.findFileState( pathStr.toString());
-
- if ( verState != null)
- {
- // Create the version folder name
-
- StringBuilder verStr = new StringBuilder();
-
- verStr.append( AVMPath.VersionFolderPrefix);
- verStr.append( versionID);
-
- String verName = verStr.toString();
-
- // Add a pseudo folder for the new version
-
- pathStr.append( FileName.DOS_SEPERATOR);
- pathStr.append( verName);
-
- verState.addPseudoFile( new VersionPseudoFile( verName, pathStr.toString()));
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug( "Added pseudo folder for new version " + storeName + ":/" + verName);
-
- // Send a change notification for the new folder
-
- if ( hasChangeHandler())
- {
- // Build the filesystem relative path to the new version folder
-
- pathStr.append( FileName.DOS_SEPERATOR);
- pathStr.append( verName);
-
- // Send the change notification
-
- getChangeHandler().notifyDirectoryChanged(NotifyChange.ActionAdded, pathStr.toString());
- }
- }
- }
-
- /**
- * Purge version call back handler
- *
- * @param storeName String
- */
- public void versionPurged(String storeName, int versionID)
- {
- // Not interested if the virtualization view is not enabled
-
- if ( isVirtualizationView() == false)
- return;
-
- // Make sure the file state cache is enabled
-
- FileStateCache fsTable = getStateCache();
- if ( fsTable == null)
- return;
-
- // Build the path to the store version folder
-
- StringBuilder pathStr = new StringBuilder();
-
- pathStr.append( FileName.DOS_SEPERATOR);
- pathStr.append( storeName);
- pathStr.append( FileName.DOS_SEPERATOR);
- pathStr.append( AVMPath.VersionsFolder);
-
- // Find the file state for the store versions folder
-
- FileState verState = fsTable.findFileState( pathStr.toString());
-
- if ( verState != null && verState.hasPseudoFiles())
- {
- // Create the version folder name
-
- StringBuilder verStr = new StringBuilder();
-
- verStr.append( AVMPath.VersionFolderPrefix);
- verStr.append( versionID);
-
- String verName = verStr.toString();
-
- // Remove the pseudo folder for the purged version
-
- verState.getPseudoFileList().removeFile( verName, true);
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug( "Removed pseudo folder for purged version " + storeName + ":/" + verName);
-
- // Send a change notification for the deleted folder
-
- if ( hasChangeHandler())
- {
- // Build the filesystem relative path to the deleted version folder
-
- pathStr.append( FileName.DOS_SEPERATOR);
- pathStr.append( verName);
-
- // Send the change notification
-
- getChangeHandler().notifyDirectoryChanged(NotifyChange.ActionRemoved, pathStr.toString());
- }
- }
- }
-}
diff --git a/source/java/org/alfresco/filesys/avm/AVMDiskDriver.java b/source/java/org/alfresco/filesys/avm/AVMDiskDriver.java
deleted file mode 100644
index ddd7316366..0000000000
--- a/source/java/org/alfresco/filesys/avm/AVMDiskDriver.java
+++ /dev/null
@@ -1,3347 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-
-package org.alfresco.filesys.avm;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-import java.util.SortedMap;
-import java.util.StringTokenizer;
-
-import javax.transaction.UserTransaction;
-
-import org.alfresco.filesys.alfresco.AlfrescoDiskDriver;
-import org.alfresco.filesys.config.ServerConfigurationBean;
-import org.alfresco.filesys.alfresco.AlfrescoTxDiskDriver;
-import org.alfresco.jlan.server.SrvSession;
-import org.alfresco.jlan.server.auth.ClientInfo;
-import org.alfresco.jlan.server.core.DeviceContext;
-import org.alfresco.jlan.server.core.DeviceContextException;
-import org.alfresco.jlan.server.filesys.AccessDeniedException;
-import org.alfresco.jlan.server.filesys.DirectoryNotEmptyException;
-import org.alfresco.jlan.server.filesys.DiskInterface;
-import org.alfresco.jlan.server.filesys.FileAttribute;
-import org.alfresco.jlan.server.filesys.FileExistsException;
-import org.alfresco.jlan.server.filesys.FileInfo;
-import org.alfresco.jlan.server.filesys.FileName;
-import org.alfresco.jlan.server.filesys.FileOpenParams;
-import org.alfresco.jlan.server.filesys.FileStatus;
-import org.alfresco.jlan.server.filesys.NetworkFile;
-import org.alfresco.jlan.server.filesys.PathNotFoundException;
-import org.alfresco.jlan.server.filesys.SearchContext;
-import org.alfresco.jlan.server.filesys.TreeConnection;
-import org.alfresco.jlan.server.filesys.cache.FileState;
-import org.alfresco.jlan.server.filesys.pseudo.PseudoFile;
-import org.alfresco.jlan.server.filesys.pseudo.PseudoFileList;
-import org.alfresco.jlan.server.filesys.pseudo.PseudoFolderNetworkFile;
-import org.alfresco.jlan.util.StringList;
-import org.alfresco.jlan.util.WildCard;
-import org.alfresco.model.ContentModel;
-import org.alfresco.model.WCMAppModel;
-import org.alfresco.repo.avm.AVMNodeConverter;
-import org.alfresco.repo.avm.CreateStoreTxnListener;
-import org.alfresco.repo.avm.CreateVersionTxnListener;
-import org.alfresco.repo.avm.PurgeStoreTxnListener;
-import org.alfresco.repo.avm.PurgeVersionTxnListener;
-import org.alfresco.repo.domain.PropertyValue;
-import org.alfresco.repo.security.authentication.AuthenticationComponent;
-import org.alfresco.repo.security.authentication.AuthenticationUtil;
-import org.alfresco.service.cmr.avm.AVMBadArgumentException;
-import org.alfresco.service.cmr.avm.AVMExistsException;
-import org.alfresco.service.cmr.avm.AVMNodeDescriptor;
-import org.alfresco.service.cmr.avm.AVMNotFoundException;
-import org.alfresco.service.cmr.avm.AVMService;
-import org.alfresco.service.cmr.avm.AVMStoreDescriptor;
-import org.alfresco.service.cmr.avm.AVMWrongTypeException;
-import org.alfresco.service.cmr.avm.VersionDescriptor;
-import org.alfresco.service.cmr.avm.locking.AVMLockingException;
-import org.alfresco.service.cmr.repository.ChildAssociationRef;
-import org.alfresco.service.cmr.repository.MimetypeService;
-import org.alfresco.service.cmr.repository.NodeRef;
-import org.alfresco.service.cmr.repository.NodeService;
-import org.alfresco.service.cmr.repository.InvalidNodeRefException;
-import org.alfresco.service.cmr.repository.CyclicChildRelationshipException;
-import org.alfresco.service.cmr.security.AuthenticationService;
-import org.alfresco.service.namespace.QName;
-import org.alfresco.service.namespace.RegexQNamePattern;
-import org.alfresco.wcm.sandbox.SandboxConstants;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.springframework.extensions.config.ConfigElement;
-
-/**
- * AVM Repository Filesystem Driver Class
- *
- * Provides a filesystem interface for various protocols such as SMB/CIFS and FTP.
- *
- * @author GKSpencer
- */
-public class AVMDiskDriver extends AlfrescoTxDiskDriver implements DiskInterface
-{
- // Logging
-
- private static final Log logger = LogFactory.getLog(AVMDiskDriver.class);
-
- // Configuration key names
-
- private static final String KEY_STORE = "storePath";
- private static final String KEY_VERSION = "version";
- private static final String KEY_CREATE = "createStore";
-
- // AVM path seperator
-
- public static final char AVM_SEPERATOR = '/';
- public static final String AVM_SEPERATOR_STR = "/";
-
- // Define client role names
-
- public static final String RoleContentManager = "ContentManager";
- public static final String RoleWebProject = "WebProject";
- public static final String RoleNotWebAuthor = "NotWebAuthor";
-
- // Content manager web project role
-
- private static final String ROLE_CONTENT_MANAGER = "ContentManager";
-
- // File status values used in the file state cache
-
- public static final int FileUnknown = FileStatus.Unknown;
- public static final int FileNotExist = FileStatus.NotExist;
- public static final int FileExists = FileStatus.FileExists;
- public static final int DirectoryExists = FileStatus.DirectoryExists;
-
- public static final int CustomFileStatus= FileStatus.MaxStatus + 1;
-
- // Services and helpers
-
- private AVMService m_avmService;
- private MimetypeService m_mimetypeService;
- private AuthenticationComponent m_authComponent;
- private AuthenticationService m_authService;
- private NodeService m_nodeService;
-
- // AVM listeners
-
- private CreateStoreTxnListener m_createStoreListener;
- private PurgeStoreTxnListener m_purgeStoreListener;
- private CreateVersionTxnListener m_createVerListener;
- private PurgeVersionTxnListener m_purgeVerListener;
-
- // Web project store
-
- private String m_webProjectStore;
-
- /**
- * Default constructor
- */
- public AVMDiskDriver()
- {
- }
-
- /**
- * Return the AVM service
- *
- * @return AVMService
- */
- public final AVMService getAvmService()
- {
- return m_avmService;
- }
-
- /**
- * Return the authentication service
- *
- * @return AuthenticationService
- */
- public final AuthenticationService getAuthenticationService()
- {
- return m_authService;
- }
-
- /**
- * Set the AVM service
- *
- * @param avmService
- * AVMService
- */
- public void setAvmService(AVMService avmService)
- {
- m_avmService = avmService;
- }
-
- /**
- * Set the authentication component
- *
- * @param authComponent
- * AuthenticationComponent
- */
- public void setAuthenticationComponent(AuthenticationComponent authComponent)
- {
- m_authComponent = authComponent;
- }
-
- /**
- * Set the authentication service
- *
- * @param authService
- * AuthenticationService
- */
- public void setAuthenticationService(AuthenticationService authService)
- {
- m_authService = authService;
- }
-
- /**
- * Set the mimetype service
- *
- * @param mimetypeService
- * MimetypeService
- */
- public void setMimetypeService(MimetypeService mimetypeService)
- {
- m_mimetypeService = mimetypeService;
- }
-
- /**
- * Set the node service
- *
- * @param nodeService NodeService
- */
- public void setNodeService(NodeService nodeService)
- {
- m_nodeService = nodeService;
- }
-
- /**
- * Set the create store listener
- *
- * @param createStoreListener
- * CreateStoreTxnListener
- */
- public void setCreateStoreListener(CreateStoreTxnListener createStoreListener)
- {
- m_createStoreListener = createStoreListener;
- }
-
- /**
- * Set the purge store listener
- *
- * @param purgeStoreListener
- * PurgeStoreTxnListener
- */
- public void setPurgeStoreListener(PurgeStoreTxnListener purgeStoreListener)
- {
- m_purgeStoreListener = purgeStoreListener;
- }
-
- /**
- * Set the create version listener
- *
- * @param createVersionListener
- * CreateVersionTxnListener
- */
- public void setCreateVersionListener(CreateVersionTxnListener createVersionListener)
- {
- m_createVerListener = createVersionListener;
- }
-
- /**
- * Set the purge version listener
- *
- * @param purgeVersionListener
- * PurgeVersionTxnListener
- */
- public void setPurgeVersionListener(PurgeVersionTxnListener purgeVersionListener)
- {
- m_purgeVerListener = purgeVersionListener;
- }
-
- /**
- * Set the web project store
- *
- * @param webStore String
- */
- public void setWebProjectStore(String webStore)
- {
- m_webProjectStore = webStore;
- }
-
- /**
- * Parse and validate the parameter string and create a device context object for this instance of the shared
- * device.
- *
- * @param shareName String
- * @param cfg ConfigElement
- * @return DeviceContext
- * @exception DeviceContextException
- */
- public DeviceContext createContext(String shareName, ConfigElement cfg)
- throws DeviceContextException
- {
- AVMContext context = null;
-
- try
- {
- // Check if the share is a virtualization view
-
- ConfigElement virtElem = cfg.getChild("virtualView");
- if (virtElem != null)
- {
- // Check if virtualization view show options have been specified
-
- int showOptions = AVMContext.ShowStagingStores + AVMContext.ShowAuthorStores;
-
- String showAttr = virtElem.getAttribute( "stores");
- if ( showAttr != null)
- {
- // Split the show options string
-
- StringTokenizer tokens = new StringTokenizer( showAttr, ",");
- StringList optList = new StringList();
-
- while ( tokens.hasMoreTokens())
- optList.addString( tokens.nextToken().trim().toLowerCase());
-
- // Build the show options mask
-
- showOptions = 0;
-
- if ( optList.containsString("normal"))
- showOptions += AVMContext.ShowNormalStores;
-
- if ( optList.containsString("site"))
- showOptions += AVMContext.ShowSiteStores;
-
- if ( optList.containsString("author"))
- showOptions += AVMContext.ShowAuthorStores;
-
- if ( optList.containsString("preview"))
- showOptions += AVMContext.ShowPreviewStores;
-
- if ( optList.containsString("staging"))
- showOptions += AVMContext.ShowStagingStores;
- }
- else if ( cfg.getChild("showAllSandboxes") != null)
- {
- // Old style show options
-
- showOptions = AVMContext.ShowNormalStores + AVMContext.ShowSiteStores +
- AVMContext.ShowAuthorStores + AVMContext.ShowPreviewStores +
- AVMContext.ShowStagingStores;
- }
-
- // Create the context
-
- context = new AVMContext(shareName, showOptions, this);
-
- // Check if the admin user should be allowed to write to the web project staging stores
-
- if ( cfg.getChild("adminWriteable") != null)
- context.setAllowAdminStagingWrites( true);
-
- }
- else
- {
- // Get the store path
-
- ConfigElement storeElement = cfg.getChild(KEY_STORE);
- if (storeElement == null
- || storeElement.getValue() == null || storeElement.getValue().length() == 0)
- throw new DeviceContextException("Device missing init value: " + KEY_STORE);
-
- String storePath = storeElement.getValue();
-
- // Get the version if specified, or default to the head version
-
- int version = AVMContext.VERSION_HEAD;
-
- ConfigElement versionElem = cfg.getChild(KEY_VERSION);
- if (versionElem != null)
- {
- // Check if the version is valid
-
- if (versionElem.getValue() == null || versionElem.getValue().length() == 0)
- throw new DeviceContextException("Store version not specified");
-
- // Validate the version id
-
- try
- {
- version = Integer.parseInt(versionElem.getValue());
- }
- catch (NumberFormatException ex)
- {
- throw new DeviceContextException("Invalid store version specified, "
- + versionElem.getValue());
- }
-
- // Range check the version id
-
- if (version < 0 && version != AVMContext.VERSION_HEAD)
- throw new DeviceContextException("Invalid store version id specified, " + version);
- }
-
- // Create the context
-
- context = new AVMContext(shareName, storePath, version);
-
- // Check if the create flag is enabled
-
- ConfigElement createStore = cfg.getChild(KEY_CREATE);
- context.setCreateStore(createStore != null);
-
- // Enable file state caching
-
- //context.enableStateCache( true);
- }
-
- }
- catch (Exception ex)
- {
- logger.error("Error during create context", ex);
-
- // Rethrow the exception
-
- throw new DeviceContextException("Driver setup error, " + ex.getMessage());
- }
-
- // Register the context bean
- registerContext(context);
-
- // Return the context for this shared filesystem
- return context;
- }
-
- /**
- * Register a device context object for this instance of the shared
- * device.
- *
- * @param context the device context
- * @param serverConfig ServerConfigurationBean
- * @exception DeviceContextException
- */
- @Override
- public void registerContext(DeviceContext ctx)
- throws DeviceContextException
- {
- super.registerContext(ctx);
-
- AVMContext context = (AVMContext)ctx;
- // Use the system user as the authenticated context for the filesystem initialization
-
- try
- {
- AuthenticationUtil.pushAuthentication();
- AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
-
- // Wrap the initialization in a transaction
-
- UserTransaction tx = getTransactionService().getUserTransaction(false);
-
- try
- {
- // Start the transaction
-
- if (tx != null)
- tx.begin();
-
- // Check if the share is a virtualization view
-
- if (context.isVirtualizationView())
- {
- // Enable file state caching
-
-// context.enableStateCache(serverConfig, true);
-
- // Plug the virtualization view context into the various store/version call back listeners
- // so that store/version pseudo folders can be kept in sync with AVM
-
- m_createStoreListener.addCallback(context);
- m_purgeStoreListener.addCallback(context);
-
- m_createVerListener.addCallback(context);
- m_purgeVerListener.addCallback(context);
-
- // Create the file state for the root path, this will build the store pseudo folder list
-
- findPseudoState( new AVMPath( ""), context);
- }
- else
- {
- // Get the store path
- String storePath = context.getStorePath();
-
- // Get the version
- int version = context.isVersion();
-
- // Validate the store path
-
- AVMNodeDescriptor rootNode = m_avmService.lookup(version, storePath);
- if (rootNode == null)
- {
- // Check if the store should be created
-
- if (!context.getCreateStore()|| version != AVMContext.VERSION_HEAD)
- throw new DeviceContextException("Invalid store path/version, "
- + storePath + " (" + version + ")");
-
- // Parse the store path
-
- String storeName = null;
- String path = null;
-
- int pos = storePath.indexOf(":/");
- if (pos != -1)
- {
- storeName = storePath.substring(0, pos);
- if (storePath.length() > pos)
- path = storePath.substring(pos + 2);
- }
- else
- storeName = storePath;
-
- // Check if the store exists
-
- AVMStoreDescriptor storeDesc = null;
-
- try
- {
- storeDesc = m_avmService.getStore(storeName);
- }
- catch (AVMNotFoundException ex)
- {
- }
-
- // Create a new store if it does not exist
-
- if (storeDesc == null)
- m_avmService.createStore(storeName);
-
- // Check if there is an optional path
-
- if (path != null)
- {
- // Split the path
-
- StringTokenizer tokens = new StringTokenizer(path, AVMPath.AVM_SEPERATOR_STR);
- StringList paths = new StringList();
-
- while (tokens.hasMoreTokens())
- paths.addString(tokens.nextToken());
-
- // Create the path, or folders that do not exist
-
- AVMPath curPath = new AVMPath(storeName, version, FileName.DOS_SEPERATOR_STR);
- AVMNodeDescriptor curDesc = m_avmService.lookup(curPath.getVersion(), curPath.getAVMPath());
-
- // Walk the path checking creating each folder as required
-
- for (int i = 0; i < paths.numberOfStrings(); i++)
- {
- AVMNodeDescriptor nextDesc = null;
-
- try
- {
- // Check if the child folder exists
-
- nextDesc = m_avmService.lookup(curDesc, paths.getStringAt(i));
- }
- catch (AVMNotFoundException ex)
- {
- }
-
- // Check if the folder exists
-
- if (nextDesc == null)
- {
- // Create the new folder
-
- m_avmService.createDirectory(curPath.getAVMPath(), paths.getStringAt(i));
-
- // Get the details of the new folder
-
- nextDesc = m_avmService.lookup(curDesc, paths.getStringAt(i));
- }
- else if (nextDesc.isFile())
- throw new DeviceContextException("Path element error, not a folder, "
- + paths.getStringAt(i));
-
- // Step to the next level
-
- curPath.parsePath(storeName, version, curPath.getRelativePath()
- + paths.getStringAt(i) + FileName.DOS_SEPERATOR_STR);
- curDesc = nextDesc;
- }
- }
-
- // Validate the store path again
-
- rootNode = m_avmService.lookup(version, storePath);
- if (rootNode == null)
- throw new DeviceContextException("Failed to create new store " + storePath);
- }
-
- // Enable file state caching
-
-// context.enableStateCache(serverConfig, true);
- }
-
- // Commit the transaction
-
- tx.commit();
- tx = null;
- }
- catch (Exception ex)
- {
- logger.error("Error during create context", ex);
-
- // Rethrow the exception
-
- throw new DeviceContextException("Driver setup error, " + ex.getMessage(), ex);
- }
- finally
- {
- // If there is an active transaction then roll it back
-
- if (tx != null)
- {
- try
- {
- tx.rollback();
- }
- catch (Exception ex)
- {
- logger.warn("Failed to rollback transaction", ex);
- }
- }
- }
-
- // Return the context for this shared filesystem
- }
- finally
- {
- AuthenticationUtil.popAuthentication();
- }
- }
-
- /**
- * Return a list of the available AVM store names
- *
- * @return StringList
- */
- public final StringList getAVMStoreNames()
- {
- // Use the system user as the authenticated context to get the AVM store list
-
- String currentUser = m_authComponent.getCurrentUserName();
- try
- {
- m_authComponent.setCurrentUser(m_authComponent.getSystemUserName());
-
- // Wrap the service request in a transaction
-
- UserTransaction tx = getTransactionService().getUserTransaction(false);
-
- StringList storeNames = new StringList();
-
- try
- {
- // Start the transaction
-
- if (tx != null)
- tx.begin();
-
- // Get the list of AVM stores
-
- List storeList = m_avmService.getStores();
-
- if (storeList != null)
- {
- for (AVMStoreDescriptor storeDesc : storeList)
- storeNames.addString(storeDesc.getName());
- }
-
- // Commit the transaction
- if (tx != null)
- tx.commit();
- tx = null;
- }
- catch (Exception ex)
- {
- logger.error("Error getting store names", ex);
- }
- finally
- {
- // If there is an active transaction then roll it back
-
- if (tx != null)
- {
- try
- {
- tx.rollback();
- }
- catch (Exception ex)
- {
- logger.warn("Failed to rollback transaction", ex);
- }
- }
- }
-
- // Return the list of AVM store names
-
- return storeNames;
- }
- finally
- {
- m_authComponent.setCurrentUser(currentUser);
- }
- }
-
- /**
- * Get the properties for a store
- *
- * @param storeName
- * String
- * @return Map
- */
- protected final Map getAVMStoreProperties(String storeName)
- {
- // Use the system user as the authenticated context to get the AVM store properties
-
- String currentUser = m_authComponent.getCurrentUserName();
- try
- {
- m_authComponent.setCurrentUser(m_authComponent.getSystemUserName());
-
- // Wrap the service request in a transaction
-
- UserTransaction tx = getTransactionService().getUserTransaction(false);
-
- Map properties = null;
-
- try
- {
- // Start the transaction
-
- if (tx != null)
- tx.begin();
-
- // Get the list of properties for AVM store
-
- properties = m_avmService.getStoreProperties(storeName);
-
- // Commit the transaction
-
- if (tx != null)
- tx.commit();
- tx = null;
- }
- catch (Exception ex)
- {
- logger.error("Error getting store properties", ex);
- }
- finally
- {
- // If there is an active transaction then roll it back
-
- if (tx != null)
- {
- try
- {
- tx.rollback();
- }
- catch (Exception ex)
- {
- logger.warn("Failed to rollback transaction", ex);
- }
- }
- }
-
- // Return the list of AVM store properties
-
- return properties;
- }
- finally
- {
- m_authComponent.setCurrentUser(currentUser);
- }
- }
-
- /**
- * Build the full store path for a file/folder using the share relative path
- *
- * @param ctx AVMContext
- * @param path String
- * @param sess SrvSession
- * @return AVMPath
- * @exception AccessDeniedException
- */
- protected final AVMPath buildStorePath(AVMContext ctx, String path, SrvSession sess)
- throws AccessDeniedException
- {
- // Check if the AVM filesystem is a normal or virtualization view
-
- AVMPath avmPath = null;
-
- if (ctx.isVirtualizationView())
- {
- // Create a path for the virtualization view
-
- avmPath = new AVMPath(path);
-
- // Check that the user has access to the path
-
- checkPathAccess( avmPath, ctx, sess);
- }
- else
- {
- // Create a path to a single store/version
-
- avmPath = new AVMPath(ctx.getStorePath(), ctx.isVersion(), path);
- }
-
- // Return the path
-
- return avmPath;
- }
-
- /**
- * Close the file.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection.
- * @param file
- * Network file context.
- * @exception java.io.IOException
- * If an error occurs.
- */
- public void closeFile(final SrvSession sess, final TreeConnection tree, final NetworkFile file) throws java.io.IOException
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("Close file " + file.getFullName());
-
- doInWriteTransaction(sess, new CallableIO(){
-
- public Void call() throws IOException
- {
- // Close the file
-
- file.closeFile();
-
- // Check if the file/directory is marked for delete
-
- if (file.hasDeleteOnClose())
- {
-
- // Check for a file or directory
-
- if (file.isDirectory())
- deleteDirectory(sess, tree, file.getFullName());
- else
- deleteFile(sess, tree, file.getFullName());
- }
- return null;
- }});
- }
-
- /**
- * Create a new directory on this file system.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection.
- * @param params
- * Directory create parameters
- * @exception java.io.IOException
- * If an error occurs.
- */
- public void createDirectory(SrvSession sess, TreeConnection tree, FileOpenParams params) throws java.io.IOException
- {
- // Check if the filesystem is writable
-
- AVMContext ctx = (AVMContext) tree.getContext();
- if (ctx.isVersion() != AVMContext.VERSION_HEAD)
- throw new AccessDeniedException("Cannot create " + params.getPath() + ", filesys not writable");
-
- // Split the path to get the new folder name and relative path
-
- final String[] paths = FileName.splitPath(params.getPath());
-
- // Convert the relative path to a store path
-
- final AVMPath storePath = buildStorePath(ctx, paths[0], sess);
-
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug("Create directory params=" + params + ", storePath=" + storePath + ", name=" + paths[1]);
-
- // Check if the filesystem is the virtualization view
-
- if (ctx.isVirtualizationView())
- {
- if (storePath.isReadOnlyPseudoPath())
- throw new AccessDeniedException("Cannot create folder in store/version layer, " + params.getPath());
- else if ( storePath.isReadOnlyAccess())
- throw new AccessDeniedException("Cannot create folder " + params.getPath() + ", read-only path");
- }
-
- // Create a new file
-
- try
- {
- doInWriteTransaction(sess, new CallableIO(){
-
- public Void call() throws IOException
- {
- // Create the new file entry
-
- m_avmService.createDirectory(storePath.getAVMPath(), paths[1]);
-
- return null;
- }});
- }
- catch (AVMExistsException ex)
- {
- throw new FileExistsException(params.getPath());
- }
- catch (AVMNotFoundException ex)
- {
- throw new FileNotFoundException(params.getPath());
- }
- catch (AVMWrongTypeException ex)
- {
- throw new FileNotFoundException(params.getPath());
- }
- catch (AVMBadArgumentException ex)
- {
- throw new FileNotFoundException(params.getPath());
- }
- catch (AVMLockingException ex)
- {
- throw new AccessDeniedException(params.getPath());
- }
- catch ( org.alfresco.repo.security.permissions.AccessDeniedException ex)
- {
- throw new AccessDeniedException(params.getPath());
- }
- }
-
- /**
- * Create a new file on the file system.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- * @param params
- * File create parameters
- * @return NetworkFile
- * @exception java.io.IOException
- * If an error occurs.
- */
- public NetworkFile createFile(final SrvSession sess, TreeConnection tree, final FileOpenParams params)
- throws java.io.IOException
- {
- // Check if the filesystem is writable
-
- final AVMContext ctx = (AVMContext) tree.getContext();
-
- // Split the path to get the file name and relative path
-
- final String[] paths = FileName.splitPath(params.getPath());
-
- // Convert the relative path to a store path
-
- final AVMPath storePath = buildStorePath(ctx, paths[0], sess);
-
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug("Create file params=" + params + ", storePath=" + storePath + ", name=" + paths[1]);
-
- // Check if the filesystem is the virtualization view
-
- if (ctx.isVirtualizationView())
- {
- if (storePath.isReadOnlyPseudoPath())
- throw new AccessDeniedException("Cannot create file in store/version layer, " + params.getPath());
- else if ( storePath.isReadOnlyAccess())
- throw new AccessDeniedException("Cannot create file " + params.getPath() + ", read-only path");
- }
- else if (storePath.getVersion() != AVMContext.VERSION_HEAD)
- {
- throw new AccessDeniedException("Cannot create " + params.getPath() + ", filesys not writable");
- }
-
-
- try
- {
- // Create a new file
- return doInWriteTransaction(sess, new CallableIO(){
-
- public NetworkFile call() throws IOException
- {
- // Create the new file entry
-
- m_avmService.createFile(storePath.getAVMPath(), paths[1]).close();
-
- // Get the new file details
-
- AVMPath fileStorePath = buildStorePath(ctx, params.getPath(), sess);
- AVMNodeDescriptor nodeDesc = m_avmService.lookup(fileStorePath.getVersion(), fileStorePath.getAVMPath());
-
- if (nodeDesc != null)
- {
- // Create the network file object for the new file
-
- AVMNetworkFile netFile = new AVMNetworkFile(nodeDesc, fileStorePath.getAVMPath(), fileStorePath.getVersion(),
- m_nodeService, m_avmService);
- netFile.setGrantedAccess(NetworkFile.READWRITE);
- netFile.setFullName(params.getPath());
-
- netFile.setFileId(fileStorePath.generateFileId());
-
- // Set the mime-type for the new file
-
- netFile.setMimeType(m_mimetypeService.guessMimetype(paths[1]));
- return netFile;
- }
- return null;
- }});
- }
- catch (AVMExistsException ex)
- {
- throw new FileExistsException(params.getPath());
- }
- catch (AVMNotFoundException ex)
- {
- throw new FileNotFoundException(params.getPath());
- }
- catch (AVMWrongTypeException ex)
- {
- throw new FileNotFoundException(params.getPath());
- }
- catch (AVMBadArgumentException ex)
- {
- throw new FileNotFoundException(params.getPath());
- }
- catch (AVMLockingException ex)
- {
- throw new AccessDeniedException(params.getPath());
- }
- catch ( org.alfresco.repo.security.permissions.AccessDeniedException ex)
- {
- throw new AccessDeniedException(params.getPath());
- }
- }
-
- /**
- * Delete the directory from the filesystem.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- * @param dir
- * Directory name.
- * @exception java.io.IOException
- * The exception description.
- */
- public void deleteDirectory(SrvSession sess, TreeConnection tree, final String dir) throws java.io.IOException
- {
- // Convert the relative path to a store path
-
- AVMContext ctx = (AVMContext) tree.getContext();
-
- final String[] paths = FileName.splitPath(dir);
- final AVMPath parentPath = buildStorePath(ctx, paths[0], sess);
- final AVMPath dirPath = buildStorePath(ctx, dir, sess);
-
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug("Delete directory, path=" + dir + ", dirPath=" + dirPath);
-
- // Check if the filesystem is the virtualization view
-
- if (ctx.isVirtualizationView())
- {
- if (parentPath.isPseudoPath())
- throw new AccessDeniedException("Cannot delete folder in store/version layer, " + dir);
- else if ( parentPath.isReadOnlyAccess())
- throw new AccessDeniedException("Cannot delete folder " + dir + ", read-only path");
- }
-
- // Make sure the path is to a folder before deleting it
-
- try
- {
- doInWriteTransaction(sess, new CallableIO(){
-
- public Void call() throws IOException
- {
- AVMNodeDescriptor nodeDesc = m_avmService.lookup(dirPath.getVersion(), dirPath.getAVMPath());
- if (nodeDesc != null)
- {
- // Check that we are deleting a folder
-
- if (nodeDesc.isDirectory())
- {
- // Make sure the directory is empty
-
- SortedMap fileList = m_avmService.getDirectoryListing(nodeDesc);
- if (fileList != null && fileList.size() > 0)
- throw new DirectoryNotEmptyException(dir);
-
- // Delete the folder
-
- m_avmService.removeNode(dirPath.getAVMPath());
- }
- else
- throw new IOException("Delete directory path is not a directory, " + dir);
- }
- return null;
- }});
- }
- catch (AVMNotFoundException ex)
- {
- throw new IOException("Directory not found, " + dir);
- }
- catch (AVMWrongTypeException ex)
- {
- throw new IOException("Invalid path, " + dir);
- }
- catch ( org.alfresco.repo.security.permissions.AccessDeniedException ex)
- {
- throw new AccessDeniedException("Access denied, " + dir);
- }
- }
-
- /**
- * Delete the specified file.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- * @param file
- * NetworkFile
- * @exception java.io.IOException
- * The exception description.
- */
- public void deleteFile(SrvSession sess, TreeConnection tree, final String name) throws java.io.IOException
- {
- // Convert the relative path to a store path
-
- AVMContext ctx = (AVMContext) tree.getContext();
-
- final String[] paths = FileName.splitPath(name);
- final AVMPath parentPath = buildStorePath(ctx, paths[0], sess);
- final AVMPath filePath = buildStorePath(ctx, name, sess);
-
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug("Delete file, path=" + name + ", filePath=" + filePath);
-
- // Check if the filesystem is the virtualization view
-
- if (ctx.isVirtualizationView())
- {
- if (parentPath.isPseudoPath())
- throw new AccessDeniedException("Cannot delete file in store/version layer, " + name);
- else if ( parentPath.isReadOnlyAccess())
- throw new AccessDeniedException("Cannot delete file " + name + ", read-only path");
- }
-
- // Make sure the path is to a file before deleting it
-
- try
- {
- doInWriteTransaction(sess, new CallableIO(){
-
- public Void call() throws IOException
- {
- AVMNodeDescriptor nodeDesc = m_avmService.lookup(filePath.getVersion(), filePath.getAVMPath());
- if (nodeDesc != null)
- {
- // Check that we are deleting a file
-
- if (nodeDesc.isFile())
- {
- // Delete the file
-
- m_avmService.removeNode(filePath.getAVMPath());
- }
- else
- throw new IOException("Delete file path is not a file, " + name);
- }
- return null;
- }});
- }
- catch (AVMNotFoundException ex)
- {
- throw new IOException("File not found, " + name);
- }
- catch (AVMWrongTypeException ex)
- {
- throw new IOException("Invalid path, " + name);
- }
- catch (AVMLockingException ex)
- {
- throw new AccessDeniedException("File locked, " + name);
- }
- catch ( org.alfresco.repo.security.permissions.AccessDeniedException ex)
- {
- throw new AccessDeniedException("Access denied, " + name);
- }
- }
-
- /**
- * Check if the specified file exists, and whether it is a file or directory.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- * @param name
- * java.lang.String
- * @return int
- * @see FileStatus
- */
- public int fileExists(SrvSession sess, TreeConnection tree, String name)
- {
- // Convert the relative path to a store path
-
- AVMContext ctx = (AVMContext) tree.getContext();
- AVMPath storePath = null;
-
- try
- {
- storePath = buildStorePath(ctx, name, sess);
- }
- catch ( AccessDeniedException ex)
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("File exists check, path=" + name + " Access denied");
-
- return FileStatus.NotExist;
- }
-
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug("File exists check, path=" + name + ", storePath=" + storePath);
-
- // Check if the path is valid
-
- int status = FileStatus.NotExist;
-
- if (storePath.isValid() == false)
- return status;
-
- // Check if the filesystem is the virtualization view
-
- if (ctx.isVirtualizationView() && storePath.isReadOnlyPseudoPath())
- {
- // Find the file state for the pseudo folder
-
- FileState fstate = findPseudoState(storePath, ctx);
-
- if (fstate != null)
- {
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug(" Found pseudo file " + fstate);
-
- // Check if the pseudo file is a file or folder
-
- if (fstate.isDirectory())
- status = FileStatus.DirectoryExists;
- else
- status = FileStatus.FileExists;
- }
- else
- {
- // Invalid pseudo file path
-
- status = FileStatus.NotExist;
- }
-
- // Return the file status
-
- return status;
- }
-
- // Search for the file/folder
-
- beginReadTransaction( sess);
-
- AVMNodeDescriptor nodeDesc = m_avmService.lookup(storePath.getVersion(), storePath.getAVMPath());
-
- if (nodeDesc != null)
- {
- // Check if the path is to a file or folder
-
- if (nodeDesc.isDirectory())
- status = FileStatus.DirectoryExists;
- else
- status = FileStatus.FileExists;
- }
-
- // Return the file status
-
- return status;
- }
-
- /**
- * Flush any buffered output for the specified file.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- * @param file
- * Network file context.
- * @exception java.io.IOException
- * The exception description.
- */
- public void flushFile(SrvSession sess, TreeConnection tree, NetworkFile file) throws java.io.IOException
- {
- // Flush the file
-
- file.flushFile();
- }
-
- /**
- * Get the file information for the specified file.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- * @param name
- * File name/path that information is required for.
- * @return File information if valid, else null
- * @exception java.io.IOException
- * The exception description.
- */
- public FileInfo getFileInformation(SrvSession sess, TreeConnection tree, String name) throws java.io.IOException
- {
- // Convert the relative path to a store path
-
- AVMContext ctx = (AVMContext) tree.getContext();
- AVMPath storePath = null;
-
- try
- {
- storePath = buildStorePath( ctx, name, sess);
- }
- catch ( Exception ex)
- {
- throw new FileNotFoundException( name);
- }
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("Get file information, path=" + name + ", storePath=" + storePath);
-
- // Check if hte path is valid
-
- if ( storePath.isValid() == false)
- throw new FileNotFoundException( name);
-
- // Check if the filesystem is the virtualization view
-
- if ( ctx.isVirtualizationView() && storePath.isReadOnlyPseudoPath())
- {
- // Search for the pseudo path, to check for any new stores
-
- FileState fstate = findPseudoState( storePath, ctx);
-
- // Check if the search path is for the root, a store or version folder
-
- if ( storePath.isRootPath())
- {
- // Return dummy file informatiom for the root folder, use cached timestamps
-
- FileInfo finfo = new FileInfo( name, 0L, FileAttribute.Directory);
-
- if ( fstate != null) {
- finfo.setModifyDateTime( fstate.getModifyDateTime());
- finfo.setChangeDateTime( fstate.getModifyDateTime());
- }
-
- // Return the root folder file information
-
- return finfo;
- }
- else
- {
- // Find the pseudo file for the store/version folder
-
- PseudoFile psFile = findPseudoFolder( storePath, ctx);
- if ( psFile != null)
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug( " Found pseudo file " + psFile);
- return psFile.getFileInfo();
- }
- else
- throw new FileNotFoundException( name);
- }
- }
-
- // Search for the file/folder
-
- beginReadTransaction( sess);
-
- FileInfo info = null;
-
- try
- {
- AVMNodeDescriptor nodeDesc = m_avmService.lookup( storePath.getVersion(), storePath.getAVMPath());
-
- if ( nodeDesc != null)
- {
- // Create, and fill in, the file information
-
- info = new FileInfo();
-
- info.setFileName( nodeDesc.getName());
-
- if ( nodeDesc.isFile())
- {
- info.setFileSize( nodeDesc.getLength());
- info.setAllocationSize((nodeDesc.getLength() + 512L) & 0xFFFFFFFFFFFFFE00L);
- }
- else
- info.setFileSize( 0L);
-
- info.setAccessDateTime( nodeDesc.getAccessDate());
- info.setCreationDateTime( nodeDesc.getCreateDate());
- info.setModifyDateTime( nodeDesc.getModDate());
- info.setChangeDateTime( nodeDesc.getModDate());
-
- // Build the file attributes
-
- int attr = 0;
-
- if ( nodeDesc.isDirectory())
- attr += FileAttribute.Directory;
-
- if ( nodeDesc.getName().startsWith( ".") ||
- nodeDesc.getName().equalsIgnoreCase( "Desktop.ini") ||
- nodeDesc.getName().equalsIgnoreCase( "Thumbs.db"))
- attr += FileAttribute.Hidden;
-
- // Mark the file/folder as read-only if not the head version
-
- if ( ctx.isVersion() != AVMContext.VERSION_HEAD || storePath.isReadOnlyAccess())
- attr += FileAttribute.ReadOnly;
-
- if ( attr == 0)
- attr = FileAttribute.NTNormal;
-
- info.setFileAttributes( attr);
-
- // Set the file id
-
- info.setFileId( storePath.generateFileId());
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug(" File info=" + info);
- }
- }
- catch ( AVMNotFoundException ex)
- {
- throw new FileNotFoundException( name);
- }
- catch ( AVMWrongTypeException ex)
- {
- throw new PathNotFoundException( name);
- }
-
- // Return the file information
-
- return info;
- }
-
- /**
- * Determine if the disk device is read-only.
- *
- * @param sess
- * Server session
- * @param ctx
- * Device context
- * @return boolean
- * @exception java.io.IOException
- * If an error occurs.
- */
- public boolean isReadOnly(SrvSession sess, DeviceContext ctx) throws java.io.IOException
- {
- // Check if the version indicates the head version, only the head is writable
-
- AVMContext avmCtx = (AVMContext) ctx;
- return avmCtx.isVersion() == AVMContext.VERSION_HEAD ? true : false;
- }
-
- /**
- * Open a file on the file system.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- * @param params
- * File open parameters
- * @return NetworkFile
- * @exception java.io.IOException
- * If an error occurs.
- */
- public NetworkFile openFile(SrvSession sess, TreeConnection tree, FileOpenParams params) throws java.io.IOException
- {
- // Convert the relative path to a store path
-
- AVMContext ctx = (AVMContext) tree.getContext();
- AVMPath storePath = buildStorePath(ctx, params.getPath(), sess);
-
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug("Open file params=" + params + ", storePath=" + storePath);
-
- // Check if the filesystem is the virtualization view
-
- if (ctx.isVirtualizationView() && storePath.isReadOnlyPseudoPath())
- {
- // Check if the path is for the root, a store or version folder
-
- if (storePath.isRootPath())
- {
- // Return a dummy file for the root folder
-
- return new PseudoFolderNetworkFile(FileName.DOS_SEPERATOR_STR);
- }
- else
- {
- // Find the pseudo file for the store/version folder
-
- PseudoFile psFile = findPseudoFolder(storePath, ctx);
- if (psFile != null)
- {
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug(" Found pseudo file " + psFile);
- return psFile.getFile(params.getPath());
- }
- else
- return null;
- }
- }
-
- // Search for the file/folder
-
- beginReadTransaction( sess);
-
- AVMNetworkFile netFile = null;
-
- try
- {
- // Get the details of the file/folder
-
- AVMNodeDescriptor nodeDesc = m_avmService.lookup(storePath.getVersion(), storePath.getAVMPath());
-
- if (nodeDesc != null)
- {
- // Check if the filesystem is read-only and write access has been requested
-
- if (storePath.getVersion() != AVMContext.VERSION_HEAD
- && (params.isReadWriteAccess() || params.isWriteOnlyAccess()))
- throw new AccessDeniedException("File " + params.getPath() + " is read-only");
-
- // Create the network file object for the opened file/folder
-
- netFile = new AVMNetworkFile(nodeDesc, storePath.getAVMPath(), storePath.getVersion(), m_nodeService, m_avmService);
-
- if (params.isReadOnlyAccess() || storePath.getVersion() != AVMContext.VERSION_HEAD)
- netFile.setGrantedAccess(NetworkFile.READONLY);
- else
- netFile.setGrantedAccess(NetworkFile.READWRITE);
-
- netFile.setFullName(params.getPath());
- netFile.setFileId(storePath.generateFileId());
-
- // Set the mime-type for the new file
-
- netFile.setMimeType(m_mimetypeService.guessMimetype(params.getPath()));
- }
- else
- throw new FileNotFoundException(params.getPath());
- }
- catch (AVMNotFoundException ex)
- {
- throw new FileNotFoundException(params.getPath());
- }
- catch (AVMWrongTypeException ex)
- {
- throw new FileNotFoundException(params.getPath());
- }
- catch ( org.alfresco.repo.security.permissions.AccessDeniedException ex)
- {
- throw new FileNotFoundException(params.getPath());
- }
-
- // Return the file
-
- return netFile;
- }
-
- /**
- * Read a block of data from the specified file.
- *
- * @param sess
- * Session details
- * @param tree
- * Tree connection
- * @param file
- * Network file
- * @param buf
- * Buffer to return data to
- * @param bufPos
- * Starting position in the return buffer
- * @param siz
- * Maximum size of data to return
- * @param filePos
- * File offset to read data
- * @return Number of bytes read
- * @exception java.io.IOException
- * The exception description.
- */
- public int readFile(SrvSession sess, TreeConnection tree, NetworkFile file, byte[] buf, int bufPos, int siz,
- long filePos) throws java.io.IOException
- {
- // Check if the file is a directory
-
- if (file.isDirectory())
- throw new AccessDeniedException();
-
- // If the content channel is not open for the file then start a transaction
-
- AVMNetworkFile avmFile = (AVMNetworkFile) file;
-
- if (avmFile.hasContentChannel() == false)
- beginReadTransaction( sess);
-
- // Read the file
-
- int rdlen = file.readFile(buf, siz, bufPos, filePos);
-
- // If we have reached end of file return a zero length read
-
- if (rdlen == -1)
- rdlen = 0;
-
- // Return the actual read length
-
- return rdlen;
- }
-
- /**
- * Rename the specified file.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- * @param oldName
- * java.lang.String
- * @param newName
- * java.lang.String
- * @exception java.io.IOException
- * The exception description.
- */
- public void renameFile(SrvSession sess, TreeConnection tree, String oldName, String newName)
- throws java.io.IOException
- {
- // Split the relative paths into parent and file/folder name pairs
-
- AVMContext ctx = (AVMContext) tree.getContext();
-
- final String[] oldPaths = FileName.splitPath(oldName);
- final String[] newPaths = FileName.splitPath(newName);
-
- // Convert the parent paths to store paths
-
- final AVMPath oldAVMPath = buildStorePath(ctx, oldPaths[0], sess);
- final AVMPath newAVMPath = buildStorePath(ctx, newPaths[0], sess);
-
- // DEBUG
-
- if (logger.isDebugEnabled())
- {
- logger.debug("Rename from path=" + oldPaths[0] + ", name=" + oldPaths[1]);
- logger.debug(" new path=" + newPaths[0] + ", name=" + newPaths[1]);
- }
-
- // Check if the filesystem is the virtualization view
-
- if (ctx.isVirtualizationView())
- {
- if ( oldAVMPath.isReadOnlyPseudoPath())
- throw new AccessDeniedException("Cannot rename folder in store/version layer, " + oldName);
- else if ( newAVMPath.isReadOnlyPseudoPath())
- throw new AccessDeniedException("Cannot rename folder to store/version layer, " + newName);
- else if ( oldAVMPath.isReadOnlyAccess() )
- throw new AccessDeniedException("Cannot rename read-only folder, " + oldName);
- else if ( newAVMPath.isReadOnlyAccess() )
- throw new AccessDeniedException("Cannot rename folder to read-only folder, " + newName);
- }
- final NodeRef oldNodeRef = AVMNodeConverter.ToNodeRef(-1, buildStorePath(ctx, oldName, sess).getAVMPath());
- final NodeRef newNodeParentRef = AVMNodeConverter.ToNodeRef(-1, newAVMPath.getAVMPath());
- try
- {
- doInWriteTransaction(sess, new CallableIO(){
-
- public Void call() throws IOException
- {
- // Rename the file/folder
-
- m_nodeService.moveNode(oldNodeRef, newNodeParentRef, ContentModel.ASSOC_CONTAINS, QName.createQName(newPaths[1]));
- return null;
- }});
- }
- catch (InvalidNodeRefException ex)
- {
- throw new IOException("Node reference no longer exists");
- }
- catch (CyclicChildRelationshipException ex)
- {
- throw new IOException("Cyclic parent-child relationship");
- }
- catch (AVMWrongTypeException ex)
- {
- throw new IOException("Invalid path, " + oldName);
- }
- catch ( org.alfresco.repo.security.permissions.AccessDeniedException ex)
- {
- throw new AccessDeniedException("Access denied, " + oldName);
- }
- }
-
- /**
- * Seek to the specified file position.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- * @param file
- * Network file.
- * @param pos
- * Position to seek to.
- * @param typ
- * Seek type.
- * @return New file position, relative to the start of file.
- */
- public long seekFile(SrvSession sess, TreeConnection tree, NetworkFile file, long pos, int typ)
- throws java.io.IOException
- {
- // Check if the file is a directory
-
- if (file.isDirectory())
- throw new AccessDeniedException();
-
- // If the content channel is not open for the file then start a transaction
-
- AVMNetworkFile avmFile = (AVMNetworkFile) file;
-
- if (avmFile.hasContentChannel() == false)
- beginReadTransaction( sess);
-
- // Set the file position
-
- return file.seekFile(pos, typ);
- }
-
- /**
- * Set the file information for the specified file.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- * @param name
- * java.lang.String
- * @param info
- * FileInfo
- * @exception java.io.IOException
- * The exception description.
- */
- public void setFileInformation(SrvSession sess, TreeConnection tree, String name, FileInfo info)
- throws java.io.IOException
- {
- // Check if the file is being marked for deletion, check if the file is writable
-
- if (info.hasSetFlag(FileInfo.SetDeleteOnClose) && info.hasDeleteOnClose())
- {
- // If this is not the head version then it's not writable
-
- AVMContext avmCtx = (AVMContext) tree.getContext();
-
- // Parse the path
-
- AVMPath storePath = buildStorePath(avmCtx, name, sess);
-
- if (avmCtx.isVersion() != AVMContext.VERSION_HEAD || storePath.isReadOnlyAccess())
- throw new AccessDeniedException("Store not writable, cannot set delete on close");
- }
- }
-
- /**
- * Start a new search on the filesystem using the specified searchPath that may contain wildcards.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- * @param searchPath
- * File(s) to search for, may include wildcards.
- * @param attrib
- * Attributes of the file(s) to search for, see class SMBFileAttribute.
- * @return SearchContext
- * @exception java.io.FileNotFoundException
- * If the search could not be started.
- */
- public SearchContext startSearch(SrvSession sess, TreeConnection tree, String searchPath, int attrib)
- throws java.io.FileNotFoundException
- {
- // Access the AVM context
-
- AVMContext avmCtx = (AVMContext) tree.getContext();
-
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug("Start search path=" + searchPath);
-
- // Split the search path into relative path and search name
-
- String[] paths = FileName.splitPath(searchPath);
-
- // Build the store path to the folder being searched
-
- AVMPath storePath = null;
-
- try
- {
- storePath = buildStorePath(avmCtx, paths[0], sess);
- }
- catch ( AccessDeniedException ex)
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("Start search access denied");
-
- throw new FileNotFoundException("Access denied");
- }
-
- // Check if the filesystem is the virtualization view
-
- if (avmCtx.isVirtualizationView())
- {
- // Check for a search of a pseudo folder
-
- if (storePath.isReadOnlyPseudoPath())
- {
- // Get the file state for the folder being searched
-
- FileState fstate = findPseudoState(storePath, avmCtx);
-
- if (fstate != null)
- {
- // Get the pseudo file list for the parent directory
-
- PseudoFileList searchList = null;
-
- if ( storePath.isLevel() == AVMPath.LevelId.Root)
- searchList = filterPseudoFolders(avmCtx, sess, storePath, fstate);
- else
- searchList = fstate.getPseudoFileList();
-
- // Check if the pseudo file list is valid
-
- if (searchList == null)
- searchList = new PseudoFileList();
-
- // Check if this is a single file or wildcard search
-
- if (WildCard.containsWildcards(searchPath))
- {
- // Create the search context, wildcard filter will take care of secondary filtering of the
- // folder listing
-
- WildCard wildCardFilter = new WildCard(paths[1], false);
- return new PseudoFileListSearchContext(searchList, attrib, wildCardFilter, storePath.isReadOnlyAccess());
- }
- else
- {
- // Search the pseudo file list for the required file
-
- PseudoFile pseudoFile = searchList.findFile(paths[1], false);
- if (pseudoFile != null)
- {
- // Create a search context using the single file details
-
- PseudoFileList singleList = new PseudoFileList();
- singleList.addFile(pseudoFile);
-
- return new PseudoFileListSearchContext(singleList, attrib, null, storePath.isReadOnlyAccess());
- }
- }
- }
-
- // File not found
-
- throw new FileNotFoundException(searchPath);
- }
- else if (storePath.isLevel() == AVMPath.LevelId.HeadMetaData
- || storePath.isLevel() == AVMPath.LevelId.VersionMetaData)
- {
- // Return an empty file list for now
-
- PseudoFileList metaFiles = new PseudoFileList();
-
- return new PseudoFileListSearchContext(metaFiles, attrib, null, storePath.isReadOnlyAccess());
- }
- }
-
- // Check if the path is a wildcard search
-
- beginReadTransaction( sess);
- SearchContext context = null;
-
- if (WildCard.containsWildcards(searchPath))
- {
- // Get the file listing for the folder
-
- AVMNodeDescriptor[] fileList = m_avmService.getDirectoryListingArray(storePath.getVersion(), storePath.getAVMPath(), false);
-
- // Create the search context
-
- if (fileList != null)
- {
-
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug(" Wildcard search returned " + fileList.length + " files");
-
- // Create the search context, wildcard filter will take care of secondary filtering of the
- // folder listing
-
- WildCard wildCardFilter = new WildCard(paths[1], false);
- context = new AVMSearchContext(fileList, attrib, wildCardFilter, storePath.getRelativePath(), storePath.isReadOnlyAccess());
- }
- }
- else
- {
- // Single file/folder search, convert the path to a store path
-
- try
- {
- storePath = buildStorePath(avmCtx, searchPath, sess);
- }
- catch ( AccessDeniedException ex)
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("Start search access denied");
-
- throw new FileNotFoundException("Access denied");
- }
-
- // Get the single file/folder details
-
- AVMNodeDescriptor nodeDesc = m_avmService.lookup(storePath.getVersion(), storePath.getAVMPath());
-
- if (nodeDesc != null)
- {
- // Create the search context for the single file/folder
-
- context = new AVMSingleFileSearchContext(nodeDesc, storePath.getRelativePath(), storePath.isReadOnlyAccess());
- }
-
- }
-
- // Return the search context
-
- return context;
- }
-
- /**
- * Truncate a file to the specified size
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- * @param file
- * Network file details
- * @param siz
- * New file length
- * @exception java.io.IOException
- * The exception description.
- */
- public void truncateFile(SrvSession sess, TreeConnection tree, final NetworkFile file, final long siz)
- throws java.io.IOException
- {
- // Check if the file is a directory, or only has read access
-
- if (file.getGrantedAccess() <= NetworkFile.READONLY)
- throw new AccessDeniedException();
-
- // If the content channel is not open for the file then start a transaction
-
- AVMNetworkFile avmFile = (AVMNetworkFile) file;
-
- // Truncate or extend the file
- if (avmFile.hasContentChannel() == false || avmFile.isWritable() == false)
- {
- doInWriteTransaction(sess, new CallableIO(){
-
- public Void call() throws IOException
- {
- file.truncateFile(siz);
- file.flushFile();
- return null;
- }});
- }
- else
- {
- file.truncateFile(siz);
- file.flushFile();
- }
-
-
- }
-
- /**
- * Write a block of data to the file.
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- * @param file
- * Network file details
- * @param buf
- * byte[] Data to be written
- * @param bufoff
- * Offset within the buffer that the data starts
- * @param siz
- * int Data length
- * @param fileoff
- * Position within the file that the data is to be written.
- * @return Number of bytes actually written
- * @exception java.io.IOException
- * The exception description.
- */
- public int writeFile(SrvSession sess, TreeConnection tree, final NetworkFile file, final byte[] buf, final int bufoff, final int siz,
- final long fileoff) throws java.io.IOException
- {
- // Check if the file is a directory, or only has read access
-
- if (file.isDirectory() || file.getGrantedAccess() <= NetworkFile.READONLY)
- throw new AccessDeniedException();
-
- // If the content channel is not open for the file, or the channel is not writable, then start a transaction
-
- AVMNetworkFile avmFile = (AVMNetworkFile) file;
-
- // Write the data to the file
- if (avmFile.hasContentChannel() == false || avmFile.isWritable() == false)
- {
- doInWriteTransaction(sess, new CallableIO(){
-
- public Void call() throws IOException
- {
- file.writeFile(buf, siz, bufoff, fileoff);
- return null;
- }});
- }
- else
- {
- file.writeFile(buf, siz, bufoff, fileoff);
- }
-
-
- // Return the actual write length
-
- return siz;
- }
-
- /**
- * Connection opened to this disk device
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- */
- public void treeClosed(SrvSession sess, TreeConnection tree)
- {
- // Nothing to do
- }
-
- /**
- * Connection closed to this device
- *
- * @param sess
- * Server session
- * @param tree
- * Tree connection
- */
- public void treeOpened(SrvSession sess, TreeConnection tree)
- {
- // Nothing to do
- }
-
- /**
- * Find the pseudo file for a virtual path
- *
- * @param avmPath
- * AVMPath
- * @param avmCtx
- * AVMContext
- * @return PseudoFile
- */
- private final PseudoFile findPseudoFolder(AVMPath avmPath, AVMContext avmCtx)
- {
- return findPseudoFolder(avmPath, avmCtx, true);
- }
-
- /**
- * Find the pseudo file for a virtual path
- *
- * @param avmPath
- * AVMPath
- * @param avmCtx
- * AVMContext
- * @param generateStates
- * boolean
- * @return PseudoFile
- */
- private final PseudoFile findPseudoFolder(AVMPath avmPath, AVMContext avmCtx, boolean generateStates)
- {
- // Check if the path is to a store pseudo folder
-
- if (avmPath.isRootPath())
- return null;
-
- // Get the file state for the parent of the required folder
-
- FileState fstate = null;
- StringBuilder str = null;
- PseudoFile psFile = null;
-
- switch (avmPath.isLevel())
- {
- // Store root folder
-
- case StoreRoot:
-
- // Get the root folder file state
-
- fstate = avmCtx.getStateCache().findFileState(FileName.DOS_SEPERATOR_STR);
-
- if (fstate != null && fstate.hasPseudoFiles())
- psFile = fstate.getPseudoFileList().findFile(avmPath.getStoreName(), false);
- break;
-
- // Versions root or Head folder
-
- case VersionRoot:
- case Head:
-
- // Create a path to the parent store
-
- str = new StringBuilder();
-
- str.append(FileName.DOS_SEPERATOR);
- str.append(avmPath.getStoreName());
-
- // Find/create the file state for the store
-
- AVMPath storePath = new AVMPath(str.toString());
- fstate = findPseudoState(storePath, avmCtx);
-
- // Find the version root or head pseudo folder
-
- if (fstate != null)
- {
- if (avmPath.isLevel() == AVMPath.LevelId.Head)
- psFile = fstate.getPseudoFileList().findFile(AVMPath.VersionNameHead, true);
- else
- psFile = fstate.getPseudoFileList().findFile(AVMPath.VersionsFolder, true);
- }
- break;
-
- // Version folder
-
- case Version:
-
- // Create a path to the versions folder
-
- str = new StringBuilder();
-
- str.append(FileName.DOS_SEPERATOR);
- str.append(avmPath.getStoreName());
- str.append(FileName.DOS_SEPERATOR);
- str.append(AVMPath.VersionsFolder);
-
- // Find/create the file state for the store
-
- AVMPath verrootPath = new AVMPath(str.toString());
- fstate = findPseudoState(verrootPath, avmCtx);
-
- // Find the version pseudo file
-
- if (fstate != null)
- {
- // Build the version folder name string
-
- str.setLength(0);
-
- str.append(AVMPath.VersionFolderPrefix);
- str.append(avmPath.getVersion());
-
- // find the version folder pseduo file
-
- psFile = fstate.getPseudoFileList().findFile(str.toString(), true);
- }
- break;
-
- // Head data or metadata folder
-
- case HeadData:
- case HeadMetaData:
-
- // Create a path to the head folder
-
- str = new StringBuilder();
-
- str.append(FileName.DOS_SEPERATOR);
- str.append(avmPath.getStoreName());
- str.append(FileName.DOS_SEPERATOR);
- str.append(AVMPath.VersionNameHead);
-
- // Find/create the file state for the store
-
- AVMPath headPath = new AVMPath(str.toString());
- fstate = findPseudoState(headPath, avmCtx);
-
- // Find the data or metadata pseudo folder
-
- if (fstate != null)
- {
- // Find the pseudo folder
-
- if (avmPath.isLevel() == AVMPath.LevelId.HeadData)
- {
- psFile = fstate.getPseudoFileList().findFile(AVMPath.DataFolder, true);
- }
- else
- {
- psFile = fstate.getPseudoFileList().findFile(AVMPath.MetaDataFolder, true);
- }
- }
- break;
-
- // Version data or metadata folder
-
- case VersionData:
- case VersionMetaData:
-
- // Create a path to the version folder
-
- str = new StringBuilder();
-
- str.append(FileName.DOS_SEPERATOR);
- str.append(avmPath.getStoreName());
- str.append(FileName.DOS_SEPERATOR);
- str.append(AVMPath.VersionFolderPrefix);
- str.append(avmPath.getVersion());
-
- // Find/create the file state for the store
-
- AVMPath verPath = new AVMPath(str.toString());
- fstate = findPseudoState(verPath, avmCtx);
-
- // Find the data or metadata pseudo folder
-
- if (fstate != null)
- {
- // Find the pseudo folder
-
- if (avmPath.isLevel() == AVMPath.LevelId.VersionData)
- {
- psFile = fstate.getPseudoFileList().findFile(AVMPath.DataFolder, true);
- }
- else
- {
- psFile = fstate.getPseudoFileList().findFile(AVMPath.MetaDataFolder, true);
- }
- }
- break;
- }
-
- // Check if the pseudo file was not found but file states should be generated
-
- if (psFile == null && generateStates == true)
- {
- // Generate the file states for the path, this is required if a request is made to a path without
- // walking the folder tree
-
- generatePseudoFolders(avmPath, avmCtx);
-
- // Try and find the pseudo file again
-
- psFile = findPseudoFolder(avmPath, avmCtx, false);
- }
-
- // Return the pseudo file, or null if not found
-
- return psFile;
- }
-
- /**
- * Find the file state for a pseudo folder path
- *
- * @param avmPath
- * AVMPath
- * @param avmCtx
- * AVMContext
- * @return FileState
- */
- protected final FileState findPseudoState(AVMPath avmPath, AVMContext avmCtx)
- {
- // Make sure the is to a pseudo file/folder
-
- if ( avmPath.isPseudoPath() == false)
- return null;
-
- // Check if there are any new stores to be added to the virtualization view
-
- if ( avmCtx.hasNewStoresQueued()) {
-
- // Get the new stores list, there is a chance another thread might get the queue, if the queue is empty
- // another thread is processing it
-
- StringList storeNames = avmCtx.getNewStoresQueue();
-
- while ( storeNames.numberOfStrings() > 0) {
-
- // Get the current store name
-
- String curStoreName = storeNames.removeStringAt( 0);
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("Adding new store " + curStoreName);
-
- // Add the current store to the virtualization view
-
- addNewStore( avmCtx, curStoreName);
- }
-
- // Get the root folder file state, update the modification timestamp
-
- FileState rootState = avmCtx.getStateCache().findFileState( FileName.DOS_SEPERATOR_STR);
- if ( rootState != null)
- rootState.updateModifyDateTime();
- }
-
- // Check if the path is to a store pseudo folder
-
- FileState fstate = null;
- StringBuilder str = null;
- String relPath = null;
-
- switch ( avmPath.isLevel())
- {
- // Root of the hieararchy
-
- case Root:
-
- // Get the root path file state
-
- fstate = avmCtx.getStateCache().findFileState( FileName.DOS_SEPERATOR_STR);
-
- // Check if the root file state is valid
-
- if ( fstate == null)
- {
- // Create a file state for the root folder
-
- fstate = avmCtx.getStateCache().findFileState( FileName.DOS_SEPERATOR_STR, true);
- fstate.setExpiryTime( FileState.NoTimeout);
- fstate.setFileStatus( DirectoryExists);
-
- // Set the modification timestamp for the root folder
-
- fstate.updateModifyDateTime();
-
- // Get a list of the available AVM stores
-
- List storeList = m_avmService.getStores();
-
- if ( storeList != null && storeList.size() > 0)
- {
- // Add pseudo files for the stores
-
- for ( AVMStoreDescriptor storeDesc : storeList)
- {
- // Get the properties for the current store
-
- String storeName = storeDesc.getName();
- Map props = m_avmService.getStoreProperties( storeName);
-
- // Check if the store is a main web project
-
- if ( props.containsKey( SandboxConstants.PROP_SANDBOX_STAGING_MAIN))
- {
- // Get the noderef for the web project
-
- PropertyValue prop = props.get( SandboxConstants.PROP_WEB_PROJECT_NODE_REF);
- if ( prop != null) {
-
- // Get the web project noderef
-
- NodeRef webNodeRef = new NodeRef( prop.getStringValue());
-
- if (m_nodeService.exists(webNodeRef))
- {
- // Create the web project pseudo folder
-
- WebProjectStorePseudoFile webProjFolder = new WebProjectStorePseudoFile( storeDesc, FileName.DOS_SEPERATOR_STR + storeName, webNodeRef);
- fstate.addPseudoFile( webProjFolder);
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug( "Found web project " + webProjFolder.getFileName());
-
- // Get the list of content managers for this web project
-
- List mgrAssocs = m_nodeService.getChildAssocs( webNodeRef, WCMAppModel.ASSOC_WEBUSER, RegexQNamePattern.MATCH_ALL);
-
- for ( ChildAssociationRef mgrRef : mgrAssocs)
- {
- // Get the child node and see if it is a content manager association
-
- NodeRef childRef = mgrRef.getChildRef();
-
- if ( m_nodeService.getProperty( childRef, WCMAppModel.PROP_WEBUSERROLE).equals(ROLE_CONTENT_MANAGER))
- {
- // Get the user name add it to the web project pseudo folder
-
- String userName = (String) m_nodeService.getProperty( childRef, WCMAppModel.PROP_WEBUSERNAME);
-
- webProjFolder.addUserRole( userName, WebProjectStorePseudoFile.RoleContentManager);
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug(" Added content manager " + userName);
- }
- }
- }
- else
- {
- logger.warn("AVM Store '"+storeName+"' with webProjectNodeRef that does not exist: "+webNodeRef);
- }
- }
- }
- else
- {
- // Check if this store is a web project sandbox
-
- int storeType = StoreType.Normal;
- String webProjName = null;
- String userName = null;
-
- if ( props.containsKey( SandboxConstants.PROP_SANDBOX_AUTHOR_MAIN))
- {
- // Sandbox store, linked to a web project
-
- storeType = StoreType.WebAuthorMain;
-
- // Get the associated web project name
-
- webProjName = props.get( SandboxConstants.PROP_WEBSITE_NAME).getStringValue();
-
- // Get the user name from the store name
-
- userName = storeName.substring( webProjName.length() + 2);
- }
- else if ( props.containsKey( SandboxConstants.PROP_SANDBOX_AUTHOR_PREVIEW))
- {
- // Author preview sandbox store, linked to a web project
-
- storeType = StoreType.WebAuthorPreview;
-
- // Get the associated web project name
-
- String projPlusUser = storeName.substring( 0, storeName.length() - "--preview".length());
- int pos = projPlusUser.lastIndexOf("--");
- if ( pos != -1)
- {
- webProjName = projPlusUser.substring( 0, pos);
- userName = projPlusUser.substring(pos + 2);
- }
- }
- else if ( props.containsKey( SandboxConstants.PROP_SANDBOX_WORKFLOW_PREVIEW))
- {
- // Staging preview sandbox store, linked to a web project
-
- storeType = StoreType.WebStagingPreview;
- }
- else if ( props.containsKey( SandboxConstants.PROP_SANDBOX_STAGING_PREVIEW))
- {
- // Staging preview sandbox store, linked to a web project
-
- storeType = StoreType.WebStagingPreview;
-
- // Get the associated web project name
-
- webProjName = storeName.substring( 0, storeName.length() - "--preview".length());
- }
- else if ( props.containsKey(QName.createQName(null, ".sitestore")))
- {
- // Site data store type
-
- storeType = StoreType.SiteStore;
- }
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug( "Store " + storeDesc.getName() + ", type=" + StoreType.asString( storeType) + ", webproj=" + webProjName + ", username=" + userName);
-
- // Add a pseudo file for the current store
-
- if ( avmCtx.showStoreType( storeType))
- {
- // Create the pseudo folder for the store
-
- StorePseudoFile storeFolder = new StorePseudoFile( storeDesc, FileName.DOS_SEPERATOR_STR + storeName, storeType);
- if (storeType == StoreType.WebAuthorMain || storeType == StoreType.WebAuthorPreview ||
- storeType == StoreType.WebStagingMain || storeType == StoreType.WebStagingPreview)
- {
- storeFolder.setWebProject( webProjName);
- storeFolder.setUserName( userName);
- }
-
- // Add the store pseudo folder to the root folder file list
-
- fstate.addPseudoFile( storeFolder);
- }
- }
- }
- }
-
- // Scan the pseudo folder list and add all publisher/reviewer user names to the web project roles list
-
- PseudoFileList folderList = fstate.getPseudoFileList();
- if ( folderList != null && folderList.numberOfFiles() > 0)
- {
- // Scan the pseudo folder list
-
- for ( int i = 0; i < folderList.numberOfFiles(); i++)
- {
- // Check if the current pseduo file is a store folder
-
- if ( folderList.getFileAt( i) instanceof StorePseudoFile)
- {
- // Check if the store has an associated web project
-
- StorePseudoFile curFile = (StorePseudoFile) folderList.getFileAt( i);
- if ( curFile.hasWebProject())
- {
- // Find the associated web project pseudo folder
-
- WebProjectStorePseudoFile webProj = (WebProjectStorePseudoFile) folderList.findFile( curFile.getWebProject(), true);
-
- if (webProj == null)
- {
- logger.warn("Missing web project for: "+curFile.getFileName()+" ("+curFile.getWebProject()+")");
- }
- else
- {
- // Strip the web project name from the sandbox store name and extract the user name.
- // Add the user as a publisher/reviewer to the web project roles list
-
- String userName = curFile.getFileName().substring( webProj.getFileName().length() + 2);
-
- // If the user does not have a content manager role then add as a publisher
-
- if ( webProj.getUserRole( userName) == WebProjectStorePseudoFile.RoleNone)
- {
- webProj.addUserRole( userName, WebProjectStorePseudoFile.RolePublisher);
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug( "Added publisher " + userName + " to " + webProj.getFileName());
- }
- }
- }
- }
- }
- }
- }
- break;
-
- // Store folder
-
- case StoreRoot:
-
- // Build the path to the parent store folder
-
- str = new StringBuilder();
-
- str.append( FileName.DOS_SEPERATOR);
- str.append( avmPath.getStoreName());
-
- // Search for the file state for the store pseudo folder
-
- relPath = str.toString();
- fstate = avmCtx.getStateCache().findFileState( relPath);
-
- if ( fstate == null)
- {
- // Create a file state for the store path
-
- fstate = avmCtx.getStateCache().findFileState( str.toString(), true);
- fstate.setFileStatus( DirectoryExists);
-
- // Add a pseudo file for the head version
-
- str.append( FileName.DOS_SEPERATOR);
- str.append( AVMPath.VersionNameHead);
-
- fstate.addPseudoFile( new VersionPseudoFile( AVMPath.VersionNameHead, str.toString()));
-
- // Add a pseudo file for the version root folder
-
- str.setLength( relPath.length() + 1);
- str.append( AVMPath.VersionsFolder);
-
- fstate.addPseudoFile( new DummyFolderPseudoFile( AVMPath.VersionsFolder, str.toString()));
- }
- break;
-
- // Head folder
-
- case Head:
-
- // Build the path to the store head version folder
-
- str = new StringBuilder();
-
- str.append( FileName.DOS_SEPERATOR);
- str.append( avmPath.getStoreName());
- str.append( FileName.DOS_SEPERATOR);
- str.append( AVMPath.VersionNameHead);
-
- // Search for the file state for the store head version pseudo folder
-
- relPath = str.toString();
-
- fstate = avmCtx.getStateCache().findFileState( relPath);
-
- if ( fstate == null)
- {
- // Create a file state for the store head folder path
-
- fstate = avmCtx.getStateCache().findFileState( str.toString(), true);
- fstate.setFileStatus( DirectoryExists);
-
- // Add a pseudo file for the data pseudo folder
-
- str.append( FileName.DOS_SEPERATOR);
- str.append( AVMPath.DataFolder);
-
- fstate.addPseudoFile( new DummyFolderPseudoFile( AVMPath.DataFolder, str.toString()));
-
- // Add a pseudo file for the metadata pseudo folder
-
- str.setLength( relPath.length() + 1);
- str.append( AVMPath.MetaDataFolder);
-
- fstate.addPseudoFile( new DummyFolderPseudoFile( AVMPath.MetaDataFolder, str.toString()));
- }
- break;
-
- // Version root folder
-
- case VersionRoot:
-
- // Get the list of AVM store versions
-
- try
- {
- // Build the path to the parent store folder
-
- str = new StringBuilder();
-
- str.append( FileName.DOS_SEPERATOR);
- str.append( avmPath.getStoreName());
- str.append( FileName.DOS_SEPERATOR);
- str.append( AVMPath.VersionsFolder);
-
- // Create a file state for the store path
-
- relPath = str.toString();
- fstate = avmCtx.getStateCache().findFileState( relPath, true);
- fstate.setFileStatus( DirectoryExists);
-
- // Add pseudo folders if the list is empty
-
- if ( fstate.hasPseudoFiles() == false)
- {
- // Build the version folder name for the head version
-
- StringBuilder verStr = new StringBuilder( AVMPath.VersionFolderPrefix);
- verStr.append( "-1");
-
- // Add a pseudo file for the head version
-
- str.append( FileName.DOS_SEPERATOR);
- str.append( verStr.toString());
-
- fstate.addPseudoFile( new VersionPseudoFile( verStr.toString(), str.toString()));
-
- // Get the list of versions for the store
-
- List verList = m_avmService.getStoreVersions( avmPath.getStoreName());
-
- // Add pseudo files for the versions to the store state
-
- if ( verList.size() > 0)
- {
- for ( VersionDescriptor verDesc : verList)
- {
- // Generate the version string
-
- String verName = null;
-
- verStr.setLength( AVMPath.VersionFolderPrefix.length());
- verStr.append( verDesc.getVersionID());
-
- verName = verStr.toString();
-
- str.setLength( relPath.length() + 1);
- str.append( verName);
-
- // Add the version pseudo folder
-
- fstate.addPseudoFile( new VersionPseudoFile ( verName, verDesc, str.toString()));
- }
- }
- }
- }
- catch ( AVMNotFoundException ex)
- {
- // Invalid store name
- }
- break;
-
- // Version folder
-
- case Version:
-
- // Build the path to the store version folder
-
- str = new StringBuilder();
-
- str.append( FileName.DOS_SEPERATOR);
- str.append( avmPath.getStoreName());
- str.append( FileName.DOS_SEPERATOR);
- str.append( AVMPath.VersionFolderPrefix);
- str.append( avmPath.getVersion());
-
- // Search for the file state for the version pseudo folder
-
- relPath = str.toString();
- fstate = avmCtx.getStateCache().findFileState( relPath);
-
- if ( fstate == null)
- {
- // Create a file state for the version folder path
-
- fstate = avmCtx.getStateCache().findFileState( str.toString(), true);
- fstate.setFileStatus( DirectoryExists);
-
- // Add a pseudo file for the data pseudo folder
-
- str.append( FileName.DOS_SEPERATOR);
- str.append( AVMPath.DataFolder);
-
- fstate.addPseudoFile( new DummyFolderPseudoFile( AVMPath.DataFolder, str.toString()));
-
- // Add a pseudo file for the metadata pseudo folder
-
- str.setLength( relPath.length() + 1);
- str.append( AVMPath.MetaDataFolder);
-
- fstate.addPseudoFile( new DummyFolderPseudoFile( AVMPath.MetaDataFolder, str.toString()));
- }
- break;
- }
-
- // Return the file state
-
- return fstate;
- }
-
- /**
- * Generate the pseudo folders for the specified path
- *
- * @param avmPath
- * AVMPath
- * @param avmCtx
- * AVMContext
- */
- private final void generatePseudoFolders(AVMPath avmPath, AVMContext avmCtx)
- {
- // Create the root file state
-
- AVMPath createPath = new AVMPath();
- StringBuilder pathStr = new StringBuilder();
-
- pathStr.append(FileName.DOS_SEPERATOR);
- createPath.parsePath(pathStr.toString());
-
- FileState rootState = findPseudoState(createPath, avmCtx);
-
- // Check if the path has a store name
-
- if (avmPath.getStoreName() != null)
- {
- // Check if the store name is valid
-
- if (rootState.hasPseudoFiles()
- && rootState.getPseudoFileList().findFile(avmPath.getStoreName(), false) != null)
- {
- // Create the store file state
-
- pathStr.append(avmPath.getStoreName());
- pathStr.append(FileName.DOS_SEPERATOR);
-
- createPath.parsePath(pathStr.toString());
-
- findPseudoState(createPath, avmCtx);
-
- // Add the head and version root pseudo folders
-
- createPath.parsePath(pathStr.toString() + AVMPath.VersionNameHead);
- findPseudoState(createPath, avmCtx);
-
- createPath.parsePath(pathStr.toString() + AVMPath.VersionsFolder);
- findPseudoState(createPath, avmCtx);
-
- // Check if the path is to a version folder
-
- if (avmPath.isLevel().ordinal() >= AVMPath.LevelId.Version.ordinal())
- {
- // Build the path
-
- pathStr.append(AVMPath.VersionsFolder);
- pathStr.append(FileName.DOS_SEPERATOR);
- pathStr.append(AVMPath.VersionFolderPrefix);
- pathStr.append(avmPath.getVersion());
-
- createPath.parsePath(pathStr.toString());
-
- // Generate the version folders
-
- findPseudoState(createPath, avmCtx);
- }
- }
- }
- }
-
- /**
- * Check that the user has access to the path
- *
- * @param avmPath AVMPath
- * @param avmCtx AVMContext
- * @param sess SrvSession
- * @exception AccessDeniedException
- */
- private final void checkPathAccess( AVMPath avmPath, AVMContext avmCtx, SrvSession sess)
- throws AccessDeniedException {
-
- // Only enforce access checks on virtualization views
-
- if ( avmCtx.isVirtualizationView() == false)
- return;
-
- // Get the client details for the session
-
- ClientInfo cInfo = sess.getClientInformation();
- if ( cInfo == null || cInfo.getUserName() == null || cInfo.getUserName().length() == 0)
- throw new AccessDeniedException();
-
- // Allow access to the root folder
-
- if ( avmPath.isLevel() == AVMPath.LevelId.Root || avmPath.isLevel() == AVMPath.LevelId.HeadData || avmPath.isLevel() == AVMPath.LevelId.StoreRootPath ) {
-
- // Allow read only access to the root, www and avm_webapps folders
- avmPath.setReadOnlyAccess(true);
- return;
- }
-
- // Get root file state, get the store pseudo folder details
-
- FileState rootState = avmCtx.getStateCache().findFileState( FileName.DOS_SEPERATOR_STR);
- if ( rootState == null){
-
- // Recreate the root file state, new stores may have been added
-
- rootState = findPseudoState( new AVMPath( FileName.DOS_SEPERATOR_STR), avmCtx);
- }
-
- // Check if there are any store pseudo folders
-
- if ( rootState != null && rootState.hasPseudoFiles())
- {
- PseudoFile pseudoFolder = rootState.getPseudoFileList().findFile( avmPath.getStoreName(), false);
- if ( pseudoFolder != null)
- {
- // Check if the pseudo folder is a web project folder or sandbox within a web project
-
- String curUserName = m_authComponent.getCurrentUserName();
-
- if ( pseudoFolder instanceof WebProjectStorePseudoFile)
- {
- // Check the users role within the web project
-
- WebProjectStorePseudoFile webFolder = (WebProjectStorePseudoFile) pseudoFolder;
-
- int role = webFolder.getUserRole( curUserName);
-
- if ( role == WebProjectStorePseudoFile.RoleNone)
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("User " + curUserName + " has no access to web project, " + webFolder.getFileName());
-
- // User does not have access to this web project
-
- throw new AccessDeniedException("User " + curUserName + " has no access to web project, " + webFolder.getFileName());
- }
- else if ( avmCtx.allowAdminStagingWrites() && cInfo.isAdministrator())
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("User " + curUserName + " granted write access to web project, " + webFolder.getFileName());
-
- // Allow admin write access
-
- avmPath.setReadOnlyAccess( false);
- }
- else
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("User " + curUserName + " granted read-only access to web project, " + webFolder.getFileName());
-
- // Only allow read-only access to the staging area
-
- avmPath.setReadOnlyAccess( true);
- }
- }
- else if ( pseudoFolder instanceof StorePseudoFile)
- {
- // Check the store type
-
- StorePseudoFile storeFolder = (StorePseudoFile) pseudoFolder;
- if ( storeFolder.isStoreType() == StoreType.Normal)
- return;
- else if ( storeFolder.hasWebProject())
- {
- // Get the web project that the sandbox is linked to
-
- WebProjectStorePseudoFile webFolder = (WebProjectStorePseudoFile) rootState.getPseudoFileList().findFile( storeFolder.getWebProject(), false);
-
- int role = webFolder.getUserRole( curUserName);
-
- if ( role == WebProjectStorePseudoFile.RoleNone)
- {
- // User does not have access to this web project
-
- throw new AccessDeniedException("User " + curUserName + " has no access to web project, " + webFolder.getFileName() + "/" + storeFolder.getFileName());
- }
- else if ( role == WebProjectStorePseudoFile.RolePublisher &&
- storeFolder.getUserName().equalsIgnoreCase( curUserName) == false)
- {
- // User does not have access to this web project
-
- throw new AccessDeniedException("User " + curUserName + " has no access to web project, " + webFolder.getFileName() + "/" + storeFolder.getFileName());
- }
- }
- }
- }
- }
- else
- {
- // Store does not exist
-
- throw new AccessDeniedException("Store does not exist, " + avmPath.getStoreName());
- }
-
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug( "Check access " + avmPath);
- }
-
- /**
- * Filter the list of pseudo folders returned in a search
- *
- * @param avmCtx AVMContext
- * @param sess SrvSession
- * @param avmPath AVMPath
- * @param fstate FileState
- * @return PseudoFileList
- */
- private final PseudoFileList filterPseudoFolders( AVMContext avmCtx, SrvSession sess, AVMPath avmPath, FileState fstate)
- {
- // Check if the root folder file state has any store pseudo folders
-
- if ( fstate.hasPseudoFiles() == false)
- return null;
-
- // Get the client details for the session
-
- ClientInfo cInfo = sess.getClientInformation();
- if ( cInfo == null || cInfo.getUserName() == null || cInfo.getUserName().length() == 0)
- return null;
-
- // Check for the admin user, no need to filter the list
-
- PseudoFileList fullList = fstate.getPseudoFileList();
- if ( cInfo.isAdministrator())
- return fullList;
-
- // Create a filtered list of store pseudo folders that the user has access to
-
- PseudoFileList filterList = new PseudoFileList();
- String userName = m_authComponent.getCurrentUserName();
-
- for ( int i = 0; i < fullList.numberOfFiles(); i++)
- {
- // Get the current store pseudo folder
-
- PseudoFile pseudoFolder = fullList.getFileAt( i);
-
- // Check if the pseudo folder is a web project folder or sandbox within a web project
-
- if ( pseudoFolder instanceof WebProjectStorePseudoFile)
- {
- // Check the users role within the web project
-
- WebProjectStorePseudoFile webFolder = (WebProjectStorePseudoFile) pseudoFolder;
-
- if ( avmCtx.showStagingStores() && webFolder.getUserRole( userName) != WebProjectStorePseudoFile.RoleNone)
- {
- // User has access to this store
-
- filterList.addFile( pseudoFolder);
- }
- }
- else if ( pseudoFolder instanceof StorePseudoFile)
- {
- // Check if the store type should be included in the visible list
-
- StorePseudoFile storeFolder = (StorePseudoFile) pseudoFolder;
- if ( avmCtx.showStoreType( storeFolder.isStoreType()))
- {
- // Check if the user has access to this store
-
- if ( storeFolder.hasWebProject())
- {
- // Get the web project that the sandbox is linked to
-
- WebProjectStorePseudoFile webFolder = (WebProjectStorePseudoFile) fullList.findFile( storeFolder.getWebProject(), false);
-
- if ( webFolder != null) {
- int role = webFolder.getUserRole( userName);
-
- if ( role == WebProjectStorePseudoFile.RoleContentManager && avmCtx.showStoreType( storeFolder.isStoreType()))
- {
- // User is a content manager, allow access to the store
-
- filterList.addFile( storeFolder);
- }
- else if ( role == WebProjectStorePseudoFile.RolePublisher && avmCtx.showStoreType( storeFolder.isStoreType()))
- {
- // Allow access if the user owns the current folder
-
- if ( storeFolder.getUserName().equalsIgnoreCase( userName))
- filterList.addFile( storeFolder);
- }
- }
- else if ( logger.isDebugEnabled())
- logger.debug("Cannot find associated web folder for store " + storeFolder.getFileName());
-
- }
- else if ( avmCtx.showNormalStores() || avmCtx.showSiteStores())
- {
- // Store is not linked to a web project, allow access to the store
-
- filterList.addFile( storeFolder);
- }
- }
- }
- }
-
- // Return the filtered list
-
- return filterList;
- }
-
- /**
- * Add a new store to the top level folder list
- *
- * @param avmCtx AVMContext
- * @param storeName String
- */
- protected void addNewStore( AVMContext avmCtx, String storeName) {
-
- // Get the root folder file state
-
- FileState fstate = avmCtx.getStateCache().findFileState( FileName.DOS_SEPERATOR_STR, true);
- if ( fstate == null)
- return;
-
- // Get the properties for the store
-
- AVMStoreDescriptor storeDesc = m_avmService.getStore( storeName);
- if ( storeDesc == null)
- return;
-
- Map props = m_avmService.getStoreProperties( storeName);
-
- // Check if the store is a main web project
-
- if ( props.containsKey( SandboxConstants.PROP_SANDBOX_STAGING_MAIN))
- {
- // Get the noderef for the web project
-
- PropertyValue prop = props.get( SandboxConstants.PROP_WEB_PROJECT_NODE_REF);
- if ( prop != null) {
-
- // Get the web project noderef
-
- NodeRef webNodeRef = new NodeRef( prop.getStringValue());
-
- if (m_nodeService.exists(webNodeRef))
- {
- // Create the web project pseudo folder
-
- WebProjectStorePseudoFile webProjFolder = new WebProjectStorePseudoFile( storeDesc, FileName.DOS_SEPERATOR_STR + storeName, webNodeRef);
- fstate.addPseudoFile( webProjFolder);
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug( " Found web project " + webProjFolder.getFileName());
-
- // Get the list of content managers for this web project
-
- List mgrAssocs = m_nodeService.getChildAssocs( webNodeRef, WCMAppModel.ASSOC_WEBUSER, RegexQNamePattern.MATCH_ALL);
-
- for ( ChildAssociationRef mgrRef : mgrAssocs)
- {
- // Get the child node and see if it is a content manager association
-
- NodeRef childRef = mgrRef.getChildRef();
-
- if ( m_nodeService.getProperty( childRef, WCMAppModel.PROP_WEBUSERROLE).equals(ROLE_CONTENT_MANAGER))
- {
- // Get the user name add it to the web project pseudo folder
-
- String userName = (String) m_nodeService.getProperty( childRef, WCMAppModel.PROP_WEBUSERNAME);
-
- webProjFolder.addUserRole( userName, WebProjectStorePseudoFile.RoleContentManager);
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug(" Added content manager " + userName);
- }
- }
- }
- else
- {
- logger.warn("AVM Store '"+storeName+"' with webProjectNodeRef that does not exist: "+webNodeRef);
- }
- }
- }
- else
- {
- // Check if this store is a web project sandbox
-
- int storeType = StoreType.Normal;
- String webProjName = null;
- String userName = null;
-
- if ( props.containsKey( SandboxConstants.PROP_SANDBOX_AUTHOR_MAIN))
- {
- // Sandbox store, linked to a web project
-
- storeType = StoreType.WebAuthorMain;
-
- // Get the associated web project name
-
- webProjName = props.get( SandboxConstants.PROP_WEBSITE_NAME).getStringValue();
-
- // Get the user name from teh store name
-
- userName = storeName.substring( webProjName.length() + 2);
- }
- else if ( props.containsKey( SandboxConstants.PROP_SANDBOX_AUTHOR_PREVIEW))
- {
- // Author preview sandbox store, linked to a web project
-
- storeType = StoreType.WebAuthorPreview;
-
- // Get the associated web project name
-
- String projPlusUser = storeName.substring( 0, storeName.length() - "--preview".length());
- int pos = projPlusUser.lastIndexOf("--");
- if ( pos != -1)
- {
- webProjName = projPlusUser.substring( 0, pos);
- userName = projPlusUser.substring(pos + 2);
- }
- }
- else if ( props.containsKey( SandboxConstants.PROP_SANDBOX_WORKFLOW_PREVIEW))
- {
- // Staging preview sandbox store, linked to a web project
-
- storeType = StoreType.WebStagingPreview;
- }
- else if ( props.containsKey( SandboxConstants.PROP_SANDBOX_STAGING_PREVIEW))
- {
- // Staging preview sandbox store, linked to a web project
-
- storeType = StoreType.WebStagingPreview;
-
- // Get the associated web project name
-
- webProjName = storeName.substring( 0, storeName.length() - "--preview".length());
- }
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug( " Store " + storeDesc.getName() + ", type=" + StoreType.asString( storeType) + ", webproj=" + webProjName + ", username=" + userName);
-
- // Add a pseudo file for the current store
-
- if ( avmCtx.showStoreType( storeType))
- {
- // Create the pseudo folder for the store
-
- StorePseudoFile storeFolder = new StorePseudoFile( storeDesc, FileName.DOS_SEPERATOR_STR + storeName, storeType);
- if ( storeType != StoreType.Normal)
- {
- storeFolder.setWebProject( webProjName);
- storeFolder.setUserName( userName);
-
- // Add all publisher/reviewer user names to the web project roles list
-
- if ( storeFolder.hasWebProject())
- {
- // Find the associated web project pseudo folder
-
- PseudoFileList folderList = fstate.getPseudoFileList();
- if ( folderList != null) {
-
- // Find the associated web project
-
- WebProjectStorePseudoFile webProj = (WebProjectStorePseudoFile) folderList.findFile( storeFolder.getWebProject(), true);
-
- if ( webProj != null) {
-
- // Strip the web project name from the sandbox store name and extract the user name.
- // Add the user as a publisher/reviewer to the web project roles list
-
- userName = storeFolder.getFileName().substring( webProj.getFileName().length() + 2);
-
- // If the user does not have a content manager role then add as a publisher
-
- if ( webProj.getUserRole( userName) == WebProjectStorePseudoFile.RoleNone)
- {
- webProj.addUserRole( userName, WebProjectStorePseudoFile.RolePublisher);
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug( " Added publisher " + userName + " to " + webProj.getFileName());
- }
- }
- }
- }
- }
-
- // Add the store pseudo folder to the root folder file list
-
- fstate.addPseudoFile( storeFolder);
- }
- }
- }
-}
diff --git a/source/java/org/alfresco/filesys/avm/AVMNetworkFile.java b/source/java/org/alfresco/filesys/avm/AVMNetworkFile.java
deleted file mode 100644
index 800922534d..0000000000
--- a/source/java/org/alfresco/filesys/avm/AVMNetworkFile.java
+++ /dev/null
@@ -1,565 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-
-package org.alfresco.filesys.avm;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel;
-
-import org.alfresco.error.AlfrescoRuntimeException;
-import org.alfresco.filesys.alfresco.AlfrescoNetworkFile;
-import org.alfresco.jlan.server.filesys.AccessDeniedException;
-import org.alfresco.jlan.server.filesys.DiskFullException;
-import org.alfresco.jlan.server.filesys.FileAttribute;
-import org.alfresco.jlan.server.filesys.NetworkFile;
-import org.alfresco.jlan.smb.SeekType;
-import org.alfresco.model.ContentModel;
-import org.alfresco.repo.avm.AVMNodeConverter;
-import org.alfresco.repo.transaction.AlfrescoTransactionSupport;
-import org.alfresco.repo.transaction.RetryingTransactionHelper;
-import org.alfresco.repo.transaction.TransactionListenerAdapter;
-import org.alfresco.service.cmr.avm.AVMNodeDescriptor;
-import org.alfresco.service.cmr.avm.AVMService;
-import org.alfresco.service.cmr.repository.ContentData;
-import org.alfresco.service.cmr.repository.ContentReader;
-import org.alfresco.service.cmr.repository.ContentWriter;
-import org.alfresco.service.cmr.repository.NodeRef;
-import org.alfresco.service.cmr.repository.NodeService;
-import org.alfresco.service.cmr.usage.ContentQuotaException;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * AVM Network File Class
- *
- * Holds the details of an open file, and provides access to the file data.
- *
- * @author GKSpencer
- */
-public class AVMNetworkFile extends AlfrescoNetworkFile {
-
- // Logging
-
- private static final Log logger = LogFactory.getLog(AVMNetworkFile.class);
-
- // Node Service
-
- private NodeService m_nodeService;
-
- // AVM service
-
- private AVMService m_avmService;
-
- // AVM path to the file/folder and store version
-
- private String m_avmPath;
- private int m_avmVersion;
-
- // Flag to indicate if the file has been modified
-
- private boolean m_modified;
-
- // Access to the file data, flag to indicate if the file channel is writable
-
- private FileChannel m_channel;
- private ContentWriter m_content;
-
- private boolean m_writable;
-
- // Mime type, if a writer is opened
-
- private String m_mimeType;
-
- /**
- * Class constructor
- *
- * @param details AVMNodeDescriptor
- * @param avmPath String
- * @param avmVersion int
- * @param nodeService NodeService
- * @param avmService AVMService
- */
- public AVMNetworkFile( AVMNodeDescriptor details, String avmPath, int avmVersion, NodeService nodeService, AVMService avmService)
- {
- super( details.getName());
-
- // Save the service, apth and version
-
- m_nodeService = nodeService;
- m_avmService = avmService;
- m_avmPath = avmPath;
- m_avmVersion = avmVersion;
-
- // Copy the file details
-
- setAccessDate( details.getAccessDate());
- setCreationDate( details.getCreateDate());
- setModifyDate( details.getModDate());
-
- if ( details.isFile())
- setFileSize( details.getLength());
- else
- setFileSize( 0L);
-
- int attr = 0;
-
- if ( details.isDirectory())
- attr += FileAttribute.Directory;
-
- if ( avmVersion != AVMContext.VERSION_HEAD)
- attr += FileAttribute.ReadOnly;
-
- setAttributes( attr);
- }
-
- /**
- * Check if there is an open file channel to the content
- *
- * @return boolean
- */
- public final boolean hasContentChannel()
- {
- return m_channel != null ? true : false;
- }
-
- /**
- * Return the mime type
- *
- * @return String
- */
- public final String getMimeType()
- {
- return m_mimeType;
- }
-
- /**
- * Set the mime type
- *
- * @param mimeType String
- */
- public final void setMimeType(String mimeType)
- {
- m_mimeType = mimeType;
- }
-
- /**
- * Open the file
- *
- * @param createFlag boolean
- * @exception IOException
- */
- public void openFile(boolean createFlag)
- throws IOException
- {
- // Nothing to do, content is opened on first read/write
- }
-
- /**
- * Read from the file.
- *
- * @param buf byte[]
- * @param len int
- * @param pos int
- * @param fileOff long
- * @return Length of data read.
- * @exception IOException
- */
- public int readFile(byte[] buf, int len, int pos, long fileOff)
- throws java.io.IOException
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("Read file " + getName() + ", len=" + len + ", offset=" + fileOff);
-
- // Open the channel for reading
-
- openContent(false, false);
-
- // Read from the channel
-
- ByteBuffer byteBuffer = ByteBuffer.wrap(buf, pos, len);
- int count = m_channel.read(byteBuffer, fileOff);
- if (count < 0)
- {
- // Return a zero count at end of file
-
- count = 0;
- }
-
- // Return the length of data read
-
- return count;
- }
-
- /**
- * Write a block of data to the file.
- *
- * @param buf byte[]
- * @param len int
- * @param pos int
- * @param fileOff long
- * @exception IOException
- */
- public void writeFile(byte[] buf, int len, int pos, long fileOff)
- throws java.io.IOException
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("Write file " + getName() + ", len=" + len + ", offset=" + fileOff);
-
- // Open the channel for writing
-
- openContent(true, false);
-
- // Write to the channel
-
- ByteBuffer byteBuffer = ByteBuffer.wrap(buf, pos, len);
- m_channel.write(byteBuffer, fileOff);
-
- // Set modification flag
-
- m_modified = true;
- incrementWriteCount();
-
- // Update the current file size
-
- setFileSize( m_channel.size());
- }
-
- /**
- * Seek to the specified file position.
- *
- * @param pos long
- * @param typ int
- * @return int
- * @exception IOException
- */
- public long seekFile(long pos, int typ)
- throws IOException
- {
- // Open the file, if not already open
-
- openContent( false, false);
-
- // Check if the current file position is the required file position
-
- long curPos = m_channel.position();
-
- switch (typ) {
-
- // From start of file
-
- case SeekType.StartOfFile :
- if (curPos != pos)
- m_channel.position( pos);
- break;
-
- // From current position
-
- case SeekType.CurrentPos :
- m_channel.position( curPos + pos);
- break;
-
- // From end of file
-
- case SeekType.EndOfFile :
- {
- long newPos = m_channel.size() + pos;
- m_channel.position(newPos);
- }
- break;
- }
-
- // Return the new file position
-
- return m_channel.position();
- }
-
- /**
- * Flush any buffered output to the file
- *
- * @throws IOException
- */
- public void flushFile()
- throws IOException
- {
- // If the file channel is open for write then flush the channel
-
- if ( m_channel != null && m_writable)
- m_channel.force( false);
- }
-
- /**
- * Truncate the file to the specified file size
- *
- * @param siz long
- * @exception IOException
- */
- public void truncateFile(long siz)
- throws IOException
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("Truncate file " + getName() + ", size=" + siz);
-
- // If the content data channel has not been opened yet and the requested size is zero
- // then this is an open for overwrite so the existing content data is not copied
-
- if ( m_channel == null && siz == 0L)
- {
- // Open content for overwrite, no need to copy existing content data
-
- openContent(true, true);
- }
- else
- {
- // Normal open for write
-
- openContent(true, false);
-
- // Truncate or extend the channel
-
- m_channel.truncate(siz);
- }
-
- // Set modification flag
-
- m_modified = true;
- incrementWriteCount();
- }
-
- /**
- * Close the database file
- */
- public void closeFile()
- throws IOException
- {
- // If the file is a directory or the file channel has not been opened then there is nothing to do
-
- if ( isDirectory() || m_channel == null && m_content == null)
- return;
-
- // We may be in a retry block, in which case this section will already have executed and channel will be null
- if (m_channel != null)
- {
- // Close the file channel
-
- try
- {
- m_channel.close();
- m_channel = null;
- }
- catch ( IOException ex)
- {
- if (RetryingTransactionHelper.extractRetryCause(ex) != null)
- {
- throw ex;
- }
- logger.error("Failed to close file channel for " + getName(), ex);
- }
-
- }
-
- if (m_content != null)
- {
- // Retrieve the content data and stop the content URL from being 'eagerly deleted', in case we need to
- // retry the transaction
-
- final ContentData contentData = m_content.getContentData();
-
- try
- {
- NodeRef nodeRef = AVMNodeConverter.ToNodeRef(-1, m_avmPath);
- m_nodeService.setProperty(nodeRef, ContentModel.PROP_CONTENT, contentData);
- }
- catch (ContentQuotaException qe)
- {
- throw new DiskFullException(qe.getMessage());
- }
-
- // Tidy up after ourselves after a successful commit. Otherwise leave things to allow a
- AlfrescoTransactionSupport.bindListener(new TransactionListenerAdapter()
- {
- @Override
- public void afterCommit()
- {
- m_content = null;
- }
- });
- }
- }
-
- /**
- * Open a file channel to the file content, switching to a writable file channel if required.
- *
- * @param write boolean
- * @param trunc boolean
- * @throws AccessDeniedException If this network file is read only
- * @throws AlfrescoRuntimeException If this network file represents a directory
- */
- private void openContent(boolean write, boolean trunc)
- throws AccessDeniedException, AlfrescoRuntimeException
- {
- // Check if this network file is a directory, no content to open
-
- if ( isDirectory())
- throw new AlfrescoRuntimeException("Unable to open channel for a directory network file: " + this);
-
- // Check if write access is required and the current channel is read-only
-
- long curPos = 0L;
-
- if ( write && m_writable == false && m_channel != null)
- {
- // Close the existing read-only channel
-
- try
- {
- // Save the current file position
-
- curPos = m_channel.position();
-
- // Close the read-only file channel
-
- m_channel.close();
- m_channel = null;
- }
- catch (IOException ex)
- {
- logger.error("Error closing read-only channel", ex);
- }
-
- // Debug
-
- if ( logger.isDebugEnabled())
- logger.debug("Switching to writable channel for " + getName());
- }
- else if ( m_channel != null)
- {
- // File channel already open
-
- return;
- }
-
- // We need to create the channel
-
- if (write && getGrantedAccess() <= NetworkFile.READONLY)
- throw new AccessDeniedException("The network file was created for read-only: " + this);
-
- // Access the content data and get a file channel to the data
-
- if ( write )
- {
- // Access the content data for write
-
- m_content = null;
-
- try {
-
- // Create a writer to access the file data
-
- m_content = m_avmService.getContentWriter(m_avmPath, false);
-
- // Set the mime-type
-
- m_content.setMimetype( getMimeType());
- }
- catch (Exception ex) {
- logger.debug( ex);
- ex.printStackTrace();
-
- // Rethrow exception, convert to access denied
-
- throw new AccessDeniedException("Failed to open file for write access, " + m_avmPath);
- }
-
- // Indicate that we have a writable channel to the file
-
- m_writable = true;
-
- // Get the writable channel, do not copy existing content data if the file is to be truncated
-
- m_channel = m_content.getFileChannel( trunc);
-
- // Reset the file position to match the read-only file channel position, unless we truncated the file
-
- if ( curPos != 0L && trunc == false)
- {
- try
- {
- m_channel.position( curPos);
- }
- catch (IOException ex)
- {
- logger.error("Failed to set file position for " + getName(), ex);
- }
- }
- }
- else
- {
- // Access the content data for read
-
- ContentReader cReader = m_avmService.getContentReader( m_avmVersion, m_avmPath);
-
- // Indicate that we only have a read-only channel to the data
-
- m_writable = false;
-
- // Get the read-only channel
-
- m_channel = cReader.getFileChannel();
- }
- }
-
- /**
- * Return the writable state of the content channel
- *
- * @return boolean
- */
- public final boolean isWritable()
- {
- return m_writable;
- }
-
- /**
- * Return the network file details as a string
- *
- * @return String
- */
- public String toString()
- {
- StringBuilder str = new StringBuilder();
-
- str.append( "[");
- str.append( getName());
- str.append( ":");
- str.append( isDirectory() ? "Dir," : "File,");
- str.append( getFileSize());
- str.append( "-Channel=");
- str.append( m_channel);
- str.append( m_writable ? ",Write" : ",Read");
- str.append( m_modified ? ",Modified" : "");
- str.append( "]");
-
- return str.toString();
- }
-}
diff --git a/source/java/org/alfresco/filesys/avm/AVMPath.java b/source/java/org/alfresco/filesys/avm/AVMPath.java
deleted file mode 100644
index 62c26e56d1..0000000000
--- a/source/java/org/alfresco/filesys/avm/AVMPath.java
+++ /dev/null
@@ -1,727 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-
-package org.alfresco.filesys.avm;
-
-import org.alfresco.jlan.server.filesys.FileName;
-
-/**
- * AVM Path Class
- *
- *
Parses a share relative path into store, version and remaining path values.
- *
- * @author gkspencer
- */
-public class AVMPath {
-
- // Constants
- //
- // Invalid version id value
-
- private static final int InvalidVersionId = -2;
-
- // Version id string for the head version
-
- public static final String VersionNameHead = "HEAD";
-
- // Folder name for the versions folder
-
- public static final String VersionsFolder = "VERSION";
-
- // Head and version sub-folders
-
- public static final String DataFolder = "DATA";
- public static final String MetaDataFolder = "METADATA";
-
- // Version folder prefix
-
- public static final String VersionFolderPrefix = "v";
-
- // AVM path seperator
-
- public static final char AVM_SEPERATOR = '/';
- public static final String AVM_SEPERATOR_STR = "/";
-
- // Level identifiers
-
- public enum LevelId { Invalid, Root, StoreRoot, Head, HeadData, HeadMetaData, VersionRoot, Version, VersionData, VersionMetaData, StoreRootPath, StorePath };
-
- // Level identifier for this path
-
- private LevelId m_levelId = LevelId.Invalid;
-
- // Store name
-
- private String m_storeName;
-
- // Version id
-
- private int m_version = InvalidVersionId;
-
- // Remaining path
-
- private String m_path;
-
- // AVM style path
-
- private String m_avmPath;
-
- // Path is read-only access
-
- private boolean m_readOnly;
-
- /**
- * Default constructor
- */
- public AVMPath()
- {
- }
-
- /**
- * Class constructor
- *
- *
Construct an AVM path for the virtualization view, with store and version folders
- *
- * @param shrPath String
- */
- public AVMPath(String shrPath)
- {
- // Parse the path
-
- parsePath( shrPath);
- }
-
- /**
- * Class constructor
- *
- *
Construct an AVM path for a standard view onto a store/version
- *
- * @param storeName String
- * @param version int
- * @param path String
- */
- public AVMPath(String storeName, int version, String path)
- {
- // Parse the path
-
- parsePath( storeName, version, path);
- }
-
- /**
- * Return the level id for the path
- *
- * @return LevelId
- */
- public LevelId isLevel()
- {
- return m_levelId;
- }
-
- /**
- * Check if the path is read-only
- *
- * @return boolean
- */
- public final boolean isReadOnlyAccess() {
- return m_readOnly;
- }
-
- /**
- * Return the store name
- *
- * @return String
- */
- public final String getStoreName()
- {
- return m_storeName;
- }
-
- /**
- * Check if the version id was specified in the path
- *
- * @return boolean
- */
- public final boolean hasVersion()
- {
- return m_version != InvalidVersionId ? true : false;
- }
-
- /**
- * Return the version id
- *
- * @return int
- */
- public final int getVersion()
- {
- return m_version;
- }
-
- /**
- * Return the version as a string
- *
- * @return String
- */
- public final String getVersionString()
- {
- if ( m_version == -1)
- return VersionNameHead;
- return "" + m_version;
- }
-
- /**
- * Check if there is a share relative path
- *
- * @return boolean
- */
- public final boolean hasRelativePath()
- {
- return m_path != null ? true : false;
- }
-
- /**
- * Return the share relative path
- *
- * @return String
- */
- public final String getRelativePath()
- {
- return m_path;
- }
-
- /**
- * Return the AVM style path, in :/ format
- *
- * @return String
- */
- public final String getAVMPath()
- {
- return m_avmPath;
- }
-
- /**
- * Check if the path is valid
- *
- * @return boolean
- */
- public final boolean isValid()
- {
- return m_levelId == LevelId.Invalid ? false : true;
- }
-
- /**
- * Check if the path is to a pseudo folder in the virtualization view
- *
- * @return boolean
- */
- public final boolean isPseudoPath()
- {
- return m_levelId == LevelId.Invalid || m_levelId == LevelId.StorePath || m_levelId == LevelId.StoreRootPath ? false : true;
- }
-
- /**
- * Check if hte path is a read-only part of the pseudo folder tree
- *
- * @return boolean
- */
- public final boolean isReadOnlyPseudoPath()
- {
- if ( isLevel() == LevelId.Root || isLevel() == LevelId.StoreRoot || isLevel() == LevelId.VersionRoot ||
- isLevel() == LevelId.Head || isLevel() == LevelId.Version)
- return true;
- return false;
- }
-
- /**
- * Check if the path is the root path
- *
- * @return boolean
- */
- public final boolean isRootPath()
- {
- return m_levelId == LevelId.Root ? true : false;
- }
-
- /**
- * Parse the path, for the virtualization view onto all stores/versions
- *
- * @param path String
- */
- public final void parsePath( String path)
- {
- // Clear current settings
-
- m_storeName = null;
- m_version = InvalidVersionId;
- m_path = null;
- m_avmPath = null;
-
- // Split the path
-
- String[] paths = FileName.splitAllPaths(path);
-
- if ( paths == null || paths.length == 0)
- {
- m_path = FileName.DOS_SEPERATOR_STR;
- m_levelId = LevelId.Root;
- return;
- }
-
- // Set the store name
-
- m_storeName = paths[0];
- m_levelId = LevelId.StoreRoot;
-
- if ( paths.length > 1)
- {
- // Validate the next element, should be either the HEAD or VERSIONS folder
-
- String levelStr = paths[1];
-
- if ( levelStr.equalsIgnoreCase( VersionNameHead))
- {
- m_version = -1;
- m_levelId = LevelId.Head;
- }
- else if ( levelStr.equalsIgnoreCase( VersionsFolder))
- {
- m_levelId = LevelId.VersionRoot;
- }
- else
- {
- // Invalid folder at the current level
-
- m_levelId = LevelId.Invalid;
- return;
- }
-
- // Check the next level, if available
-
- if ( paths.length > 2)
- {
- // If the previous level is the versions root then the next level should be a
- // version id folder
-
- String folderName = paths[2];
- int pathIdx = 3;
-
- if ( isLevel() == LevelId.VersionRoot)
- {
- // Check that the folder name starts with the version folder prefix
-
- if ( folderName != null && folderName.startsWith( VersionFolderPrefix) &&
- folderName.length() > VersionFolderPrefix.length())
- {
- try
- {
- // Parse the version id
-
- m_version = Integer.parseInt( folderName.substring( VersionFolderPrefix.length()));
- m_levelId = LevelId.Version;
-
- // Validate the version id
-
- if ( m_version < -1)
- {
- // Invalid version id
-
- m_levelId = LevelId.Invalid;
- return;
- }
- }
- catch ( NumberFormatException ex)
- {
- m_levelId = LevelId.Invalid;
- return;
- }
-
- // Check for the next level
-
- if ( paths.length > 3)
- {
- // Get the next level name
-
- folderName = paths[3];
- pathIdx++;
-
- // Check for the data folder
-
- if ( folderName.equalsIgnoreCase( DataFolder))
- {
- m_levelId = LevelId.VersionData;
-
- // Set the path to the root of the store
-
- m_path = FileName.DOS_SEPERATOR_STR;
- }
- else if ( folderName.equalsIgnoreCase( MetaDataFolder))
- {
- m_levelId = LevelId.VersionMetaData;
-
- // Set the path to the root of the metadata
-
- m_path = FileName.DOS_SEPERATOR_STR;
- }
- else
- {
- m_levelId = LevelId.Invalid;
- return;
- }
- }
- }
- else
- {
- m_levelId = LevelId.Invalid;
- return;
- }
- }
-
- // If the previous level is head the next level should be the data or metadata folder
-
- else if ( isLevel() == LevelId.Head)
- {
- // Check for the data folder
-
- if ( folderName.equalsIgnoreCase( DataFolder))
- {
- m_levelId = LevelId.HeadData;
-
- // Set the path to the root of the store
-
- m_path = FileName.DOS_SEPERATOR_STR;
- }
- else if ( folderName.equalsIgnoreCase( MetaDataFolder))
- {
- m_levelId = LevelId.HeadMetaData;
-
- // Set the path to the root of the metadata
-
- m_path = FileName.DOS_SEPERATOR_STR;
- }
- else
- {
- m_levelId = LevelId.Invalid;
- return;
- }
- }
-
- // If there are remaining paths then build a relative path
- if ( paths.length > pathIdx)
- {
- StringBuilder pathStr = new StringBuilder();
-
- for ( int i = pathIdx; i < paths.length; i++)
- {
- pathStr.append( FileName.DOS_SEPERATOR);
- pathStr.append( paths[i]);
- }
-
- m_path = pathStr.toString();
-
- // ALF-1719: make "www" and "avm_webapps" read only by setting their level to
- // StoreRootPath (which is checked in AVMDiskDriver.checkPathAccess).
- String lastPath = paths[paths.length-1].toLowerCase();
- if(lastPath.equals("www") || lastPath.equals("avm_webapps"))
- {
- // Set the level to indicate a store root path i.e. "www",
- // "avm_webapps"
- m_levelId = LevelId.StoreRootPath;
- }
- else
- {
- // Set the level to indicate a store relative path
- m_levelId = LevelId.StorePath;
- }
- }
-
- // Build the AVM path, in :/ format
-
- if ( m_path != null)
- {
- StringBuilder pathStr = new StringBuilder();
-
- pathStr.append( m_storeName);
- pathStr.append( ":");
- pathStr.append( m_path.replace( FileName.DOS_SEPERATOR, AVM_SEPERATOR));
-
- m_avmPath = pathStr.toString();
- }
- }
- }
- }
-
- /**
- * Parse the path, to generate a path for a single store/version
- *
- * @param storeName String
- * @param version int
- * @param path String
- */
- public final void parsePath( String storeName, int version, String path)
- {
- // Clear current settings
-
- m_levelId = LevelId.Invalid;
-
- m_storeName = null;
- m_version = InvalidVersionId;
- m_path = null;
- m_avmPath = null;
-
- // Set the store/version
-
- m_storeName = storeName;
- m_version = version;
-
- // Save the relative path
-
- m_path = path;
-
- // Build the store path
-
- StringBuilder avmPath = new StringBuilder();
- avmPath.append( m_storeName);
-
- if ( storeName.indexOf( ":") == -1)
- avmPath.append( ":");
-
- if ( path == null || path.length() == 0)
- {
- avmPath.append( AVM_SEPERATOR);
-
- // Set the share relative path as the root path
-
- m_path = FileName.DOS_SEPERATOR_STR;
- }
- else
- {
- if ( path.startsWith( FileName.DOS_SEPERATOR_STR) == false)
- avmPath.append( AVM_SEPERATOR);
-
- avmPath.append( path.replace( FileName.DOS_SEPERATOR, AVM_SEPERATOR));
- }
-
- m_avmPath = avmPath.toString();
-
- // Indicate that the path is to a store relative path
-
- String lowerPath = path.toLowerCase();
- String[] paths = FileName.splitAllPaths(lowerPath);
- if(paths[paths.length - 1].equals("www") || paths[paths.length - 1].equals("avm_webapps"))
- {
- // Set the level to indicate a store root path i.e. "www",
- // "avm_webapps"
- m_levelId = LevelId.StoreRootPath;
- }
- else
- {
- m_levelId = LevelId.StorePath;
- }
- }
-
- /**
- * Generate a file id for the path
- *
- * @return int
- */
- public final int generateFileId()
- {
- // Check if the path is a store path or pseudo path
-
- int fid = -1;
-
- if ( isLevel() == LevelId.StorePath || isLevel() == LevelId.StoreRootPath)
- {
- // Use the share relative path to generate the file id
-
- fid = getRelativePath().hashCode();
- }
- else if ( isPseudoPath())
- {
- // Create a relative path to the pseudo folder
-
- StringBuilder relStr = new StringBuilder();
- relStr.append( FileName.DOS_SEPERATOR);
-
- switch( isLevel())
- {
- case StoreRoot:
- relStr.append( getStoreName());
- break;
- case Head:
- relStr.append( getStoreName());
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.VersionNameHead);
- break;
- case HeadData:
- relStr.append( getStoreName());
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.VersionNameHead);
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.DataFolder);
- break;
- case HeadMetaData:
- relStr.append( getStoreName());
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.VersionNameHead);
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.MetaDataFolder);
- break;
- case VersionRoot:
- relStr.append( getStoreName());
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.VersionsFolder);
- break;
- case Version:
- relStr.append( getStoreName());
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.VersionsFolder);
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.VersionFolderPrefix);
- relStr.append( getVersion());
- break;
- case VersionData:
- relStr.append( getStoreName());
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.VersionsFolder);
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.VersionFolderPrefix);
- relStr.append( getVersion());
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.DataFolder);
- break;
- case VersionMetaData:
- relStr.append( getStoreName());
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.VersionsFolder);
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.VersionFolderPrefix);
- relStr.append( getVersion());
- relStr.append( FileName.DOS_SEPERATOR);
- relStr.append( AVMPath.MetaDataFolder);
- break;
- }
-
- // Generate the file id using the pseudo folder relative path
-
- fid = relStr.toString().hashCode();
- }
-
- // Return the file id
-
- return fid;
- }
-
- /**
- * Set the path access, true for read-only access
- *
- * @param access boolean
- */
- public final void setReadOnlyAccess( boolean readOnly)
- {
- m_readOnly = readOnly;
- }
-
- /**
- * Return the AVM path details as a string
- *
- * @return String
- */
- public String toString()
- {
- StringBuilder str = new StringBuilder();
-
- switch ( m_levelId)
- {
- case Invalid:
- str.append("[Invalid");
- break;
- case Root:
- str.append("[Root");
- break;
- case StoreRoot:
- str.append("[StoresRoot");
- break;
- case Head:
- str.append("[");
- str.append(getStoreName());
- str.append(":HEAD");
- break;
- case HeadData:
- str.append("[");
- str.append(getStoreName());
- str.append(":HEAD\\");
- str.append( DataFolder);
- break;
- case HeadMetaData:
- str.append("[");
- str.append(getStoreName());
- str.append(":HEAD\\");
- str.append( MetaDataFolder);
- break;
- case VersionRoot:
- str.append("[");
- str.append(getStoreName());
- str.append(":Versions");
- break;
- case Version:
- str.append("[");
- str.append(getStoreName());
- str.append(":");
- str.append(VersionFolderPrefix);
- str.append(getVersion());
- break;
- case VersionData:
- str.append("[");
- str.append(getStoreName());
- str.append(":");
- str.append(VersionFolderPrefix);
- str.append(getVersion());
- str.append("\\");
- str.append( DataFolder);
- break;
- case VersionMetaData:
- str.append("[");
- str.append(getStoreName());
- str.append(":");
- str.append(VersionFolderPrefix);
- str.append(getVersion());
- str.append("\\");
- str.append( MetaDataFolder);
- break;
- case StoreRootPath:
- case StorePath:
- str.append("[");
- str.append(getStoreName());
- str.append(":");
- str.append(VersionFolderPrefix);
- str.append(getVersion());
- str.append(",");
- str.append(getRelativePath());
- str.append(":");
- str.append(getAVMPath());
- break;
- }
-
- if ( isReadOnlyAccess())
- str.append("-ReadOnly");
-
- str.append("]");
-
- return str.toString();
- }
-}
diff --git a/source/java/org/alfresco/filesys/avm/AVMSearchContext.java b/source/java/org/alfresco/filesys/avm/AVMSearchContext.java
deleted file mode 100644
index 232626335d..0000000000
--- a/source/java/org/alfresco/filesys/avm/AVMSearchContext.java
+++ /dev/null
@@ -1,324 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-
-package org.alfresco.filesys.avm;
-
-import org.alfresco.jlan.server.filesys.FileAttribute;
-import org.alfresco.jlan.server.filesys.FileInfo;
-import org.alfresco.jlan.server.filesys.FileName;
-import org.alfresco.jlan.server.filesys.SearchContext;
-import org.alfresco.jlan.util.WildCard;
-import org.alfresco.service.cmr.avm.AVMNodeDescriptor;
-
-/**
- * AVM Filesystem Search Context Class
- *
- * Contains the details of a wildcard folder search.
- *
- * @author GKSpencer
- */
-public class AVMSearchContext extends SearchContext {
-
- // File list and current index
-
- private AVMNodeDescriptor[] m_fileList;
- private int m_fileIdx;
-
- // File attributes
-
- private int m_attrib;
-
- // Optional wildcard filter
-
- private WildCard m_filter;
-
- // Relative path to the parent folder being searched
-
- private String m_parentPath;
-
- // Mark all files/folders as read-only
-
- private boolean m_readOnly;
-
- /**
- * Class constructor
- *
- * @param fileList SortedMap
- * @param attrib int
- * @param filter WildCard
- * @param parentPath String
- * @param readOnly boolean
- */
- public AVMSearchContext( AVMNodeDescriptor[] fileList, int attrib, WildCard filter, String parentPath, boolean readOnly)
- {
- m_attrib = attrib;
- m_filter = filter;
- m_fileList = fileList;
-
- m_parentPath = parentPath;
- if ( m_parentPath != null && m_parentPath.endsWith( FileName.DOS_SEPERATOR_STR) == false)
- m_parentPath = m_parentPath + FileName.DOS_SEPERATOR_STR;
-
- m_readOnly = readOnly;
- }
-
- /**
- * Determine if there are more files for the active search.
- *
- * @return boolean
- */
- public boolean hasMoreFiles()
- {
- return m_fileIdx < m_fileList.length ? true : false;
- }
-
- /**
- * Return file information for the next file in the active search. Returns false if the search
- * is complete.
- *
- * @param info FileInfo to return the file information.
- * @return true if the file information is valid, else false
- */
- public boolean nextFileInfo(FileInfo info)
- {
- // Check if there is another file record to return
-
- if ( m_fileIdx >= m_fileList.length)
- return false;
-
- // Search for the next valid file
-
- boolean foundMatch = false;
- AVMNodeDescriptor curFile = null;
-
- while (foundMatch == false && m_fileIdx < m_fileList.length)
- {
- // Get the next file from the list
-
- curFile = m_fileList[ m_fileIdx++];
-
- // Check if the file name matches the search pattern
-
- if ( m_filter.matchesPattern(curFile.getName()) == true)
- {
-
- // Check if the file matches the search attributes
-
- if (FileAttribute.hasAttribute(m_attrib, FileAttribute.Directory) &&
- curFile.isDirectory())
- {
-
- // Found a match
-
- foundMatch = true;
- }
- else if ( curFile.isFile())
- {
-
- // Found a match
-
- foundMatch = true;
- }
-
- // Check if we found a match
-
- if ( foundMatch == false)
- {
-
- // Get the next file from the list
-
- if ( ++m_fileIdx < m_fileList.length)
- curFile = m_fileList[ m_fileIdx];
- }
- }
- }
-
- // If we found a match then fill in the file information
-
- if ( foundMatch)
- {
- // Fill in the file information
-
- info.setFileName( curFile.getName());
-
- if ( curFile.isFile())
- {
- info.setFileSize( curFile.getLength());
- info.setAllocationSize((curFile.getLength() + 512L) & 0xFFFFFFFFFFFFFE00L);
- }
- else
- info.setFileSize( 0L);
-
- info.setAccessDateTime( curFile.getAccessDate());
- info.setCreationDateTime( curFile.getCreateDate());
- info.setModifyDateTime( curFile.getModDate());
-
- // Build the file attributes
-
- int attr = 0;
-
- if ( curFile.isDirectory())
- attr += FileAttribute.Directory;
-
- if ( curFile.getName().startsWith( ".") ||
- curFile.getName().equalsIgnoreCase( "Desktop.ini") ||
- curFile.getName().equalsIgnoreCase( "Thumbs.db"))
- attr += FileAttribute.Hidden;
-
- if ( isReadOnly())
- attr += FileAttribute.ReadOnly;
-
- if ( attr == 0)
- attr = FileAttribute.NTNormal;
-
- info.setFileAttributes( attr);
-
- // Generate a file id for the current file
-
- StringBuilder pathStr = new StringBuilder( m_parentPath);
- pathStr.append ( curFile.getName());
-
- info.setFileId( pathStr.toString().hashCode());
- }
-
- // Indicate if the file information is valid
-
- return foundMatch;
- }
-
- /**
- * Return the file name of the next file in the active search. Returns null is the search is
- * complete.
- *
- * @return String
- */
- public String nextFileName()
- {
- // Check if there is another file record to return
-
- // Find the next matching file name
-
- while ( m_fileIdx < m_fileList.length) {
-
- // Check if the current file name matches the search pattern
-
- String fname = m_fileList[m_fileIdx++].getName();
-
- if ( m_filter.matchesPattern(fname))
- return fname;
- }
-
- // No more matching file names
-
- return null;
- }
-
- /**
- * Return the total number of file entries for this search if known, else return -1
- *
- * @return int
- */
- public int numberOfEntries()
- {
- return m_fileList.length;
- }
-
- /**
- * Return the resume id for the current file/directory in the search.
- *
- * @return int
- */
- public int getResumeId()
- {
- return m_fileIdx;
- }
-
- /**
- * Restart a search at the specified resume point.
- *
- * @param resumeId Resume point id.
- * @return true if the search can be restarted, else false.
- */
- public boolean restartAt(int resumeId)
- {
- // Range check the resume id
-
- int resId = resumeId - 1;
-
- if ( resId < 0 || resId >= m_fileList.length)
- return false;
-
- // Reset the current file index
-
- m_fileIdx = resId;
- return true;
- }
-
- /**
- * Restart the current search at the specified file.
- *
- * @param info File to restart the search at.
- * @return true if the search can be restarted, else false.
- */
- public boolean restartAt(FileInfo info)
- {
- // Search backwards from the current file
-
- int curFileIdx = m_fileIdx;
-
- if (m_fileIdx >= m_fileList.length)
- {
- m_fileIdx = m_fileList.length - 1;
- }
-
- while ( m_fileIdx > 0) {
-
- // Check if the current file is the required search restart point
-
- if ( m_fileList[ m_fileIdx].getName().equals( info.getFileName()))
- return true;
- else
- m_fileIdx--;
- }
-
- // Failed to find the restart file
-
- m_fileIdx = curFileIdx;
- return false;
- }
-
- /**
- * Check if all files/folders returned by the search should be marked as read-only
- *
- * @return boolean
- */
- public final boolean isReadOnly()
- {
- return m_readOnly;
- }
-
- /**
- * Set all files/folders returned by the search as read-only
- *
- * @param readOnly boolean
- */
- public final void setReadOnly( boolean readOnly)
- {
- m_readOnly = readOnly;
- }
-}
diff --git a/source/java/org/alfresco/filesys/avm/AVMShareMapper.java b/source/java/org/alfresco/filesys/avm/AVMShareMapper.java
deleted file mode 100644
index bd72faa1f4..0000000000
--- a/source/java/org/alfresco/filesys/avm/AVMShareMapper.java
+++ /dev/null
@@ -1,393 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-
-package org.alfresco.filesys.avm;
-
-import java.util.Enumeration;
-
-import org.springframework.extensions.config.ConfigElement;
-import org.alfresco.error.AlfrescoRuntimeException;
-import org.alfresco.filesys.config.ServerConfigurationBean;
-import org.alfresco.jlan.server.SrvSession;
-import org.alfresco.jlan.server.config.InvalidConfigurationException;
-import org.alfresco.jlan.server.config.ServerConfiguration;
-import org.alfresco.jlan.server.core.InvalidDeviceInterfaceException;
-import org.alfresco.jlan.server.core.ShareMapper;
-import org.alfresco.jlan.server.core.ShareType;
-import org.alfresco.jlan.server.core.SharedDevice;
-import org.alfresco.jlan.server.core.SharedDeviceList;
-import org.alfresco.jlan.server.filesys.DiskSharedDevice;
-import org.alfresco.jlan.server.filesys.FilesystemsConfigSection;
-import org.alfresco.jlan.util.StringList;
-import org.alfresco.service.cmr.avm.AVMNotFoundException;
-import org.alfresco.service.cmr.avm.AVMService;
-import org.alfresco.service.cmr.avm.AVMWrongTypeException;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.springframework.beans.factory.InitializingBean;
-
-/**
- * AVM Filesystem Share Mapper Class
- *
- * Provides access to store versions using the share name '_'.
- *
- * @author gkspencer
- */
-public class AVMShareMapper implements ShareMapper, InitializingBean {
-
- // Logging
-
- private static final Log logger = LogFactory.getLog("org.alfresco.smb.protocol");
-
- // Regular expression to test for AVM versioned share name
-
- private static final String AVM_SHAREPATTERN = "[a-zA-Z0-9-]*_[0-9]+";
-
- // Server configuration
-
- private ServerConfiguration m_config;
- private FilesystemsConfigSection m_filesysConfig;
-
- // List of available AVM shares
-
- private StringList m_avmShareNames;
-
- // Filesystem driver to be used to create home shares
-
- private AVMDiskDriver m_driver;
-
- // Debug enable flag
-
- private boolean m_debug;
-
- /**
- * Default constructor
- */
- public AVMShareMapper()
- {
- }
-
- public void setServerConfiguration(ServerConfiguration config)
- {
- this.m_config = config;
- }
-
- public void setDebug(boolean debug)
- {
- this.m_debug = debug;
- }
-
- /**
- * Initialize the share mapper
- *
- * @param config ServerConfiguration
- * @param params ConfigElement
- * @exception InvalidConfigurationException
- */
- public void initializeMapper(ServerConfiguration config, ConfigElement params) throws InvalidConfigurationException
- {
- // Save the server configuration
-
- setServerConfiguration(config);
-
- // Check if debug is enabled
-
- if (params != null && params.getChild("debug") != null)
- setDebug(true);
-
- // Complete the initialization
- afterPropertiesSet();
- }
-
- public void afterPropertiesSet()
- {
- // Save the server configuration
-
- m_filesysConfig = (FilesystemsConfigSection) m_config.getConfigSection(FilesystemsConfigSection.SectionName);
-
-
- // Build the list of available AVM share names
-
- m_avmShareNames = new StringList();
-
- SharedDeviceList shrList = m_filesysConfig.getShares();
- Enumeration shrEnum = shrList.enumerateShares();
-
- while ( shrEnum.hasMoreElements())
- {
- // Get the current shared device and check if it is an AVM filesystem device
-
- SharedDevice curShare = shrEnum.nextElement();
-
- try
- {
- if ( curShare.getInterface() instanceof AVMDiskDriver)
- {
- // Add the shared filesystem name to the list of AVM shares
-
- m_avmShareNames.addString( curShare.getName());
-
- // Set the AVM filesystem driver to be used when creating dynamic shares
-
- if ( m_driver == null)
- m_driver = (AVMDiskDriver) curShare.getInterface();
- }
- }
- catch ( InvalidDeviceInterfaceException ex)
- {
- }
- }
- }
-
- /**
- * Check if debug output is enabled
- *
- * @return boolean
- */
- public final boolean hasDebug()
- {
- return m_debug;
- }
-
- /**
- * Return the list of available shares.
- *
- * @param host String
- * @param sess SrvSession
- * @param allShares boolean
- * @return SharedDeviceList
- */
- public SharedDeviceList getShareList(String host, SrvSession sess, boolean allShares)
- {
- // Make a copy of the global share list and add the per session dynamic shares
-
- SharedDeviceList shrList = new SharedDeviceList(m_filesysConfig.getShares());
-
- if ( sess != null && sess.hasDynamicShares()) {
-
- // Add the per session dynamic shares
-
- shrList.addShares(sess.getDynamicShareList());
- }
-
- // Remove unavailable shares from the list and return the list
-
- if ( allShares == false)
- shrList.removeUnavailableShares();
- return shrList;
- }
-
- /**
- * Find a share using the name and type for the specified client.
- *
- * @param host String
- * @param name String
- * @param typ int
- * @param sess SrvSession
- * @param create boolean
- * @return SharedDevice
- * @exception InvalidUserException
- */
- public SharedDevice findShare(String tohost, String name, int typ, SrvSession sess, boolean create)
- throws Exception
- {
- // Find the required share by name/type. Use a case sensitive search first, if that fails use a case
- // insensitive search.
-
- SharedDevice share = m_filesysConfig.getShares().findShare(name, typ, false);
-
- if ( share == null)
- {
-
- // Try a case insensitive search for the required share
-
- share = m_filesysConfig.getShares().findShare(name, typ, true);
- }
-
- // If the share was not found then check if the share is in the AVM versioned share format - '_'
-
- if ( share == null && ( typ == ShareType.DISK || typ == ShareType.UNKNOWN))
- {
- // Check if the share has already been created for the session
-
- if ( sess.hasDynamicShares())
- {
-
- // Check if the required share exists in the sessions dynamic share list
-
- share = sess.getDynamicShareList().findShare(name, typ, false);
-
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug(" Reusing existing dynamic share for " + name);
- }
-
- // Check if the share name matches the AVM versioned share name pattern
-
- if ( share == null && create == true && name.matches( AVM_SHAREPATTERN))
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug("Map dynamic share " + name + ", type=" + ShareType.TypeAsString(typ));
-
- // Split the store name and version id from the share name
-
- int pos = name.indexOf( '_');
-
- String storePath = name.substring(0, pos) + ":/";
- int storeVersion = -1;
-
- try
- {
- String storeVer = name.substring( pos + 1);
- storeVersion = Integer.parseInt( storeVer);
-
- if ( storeVersion < 0)
- storeVersion = -1;
- }
- catch ( NumberFormatException ex)
- {
- logger.error( "Invalid store version id, name=" + name);
- }
-
- // Create the disk driver and context
-
- if ( storePath.length() > 0 && storeVersion != -1)
- {
- // Validate the store name and version
-
- AVMService avmService = m_driver.getAvmService();
-
- m_driver.beginReadTransaction( sess);
-
- try
- {
- // Validate the store name/version
-
- avmService.lookup( storeVersion, storePath);
-
- // Create a dynamic share mapped to the AVM store/version
-
- AVMContext avmCtx = new AVMContext( name, storePath, storeVersion);
-
- if(m_config instanceof ServerConfigurationBean)
- {
- ServerConfigurationBean config = (ServerConfigurationBean)m_config;
-
- config.initialiseRuntimeContext("cifs.avm" + name, avmCtx);
-
- // Enable file state caching
- // diskCtx.enableStateCache(serverConfigurationBean, true);
- }
- else
- {
- throw new AlfrescoRuntimeException("configuration error, unknown configuration bean");
- }
-
- // Create a dynamic shared device for the store version
-
- DiskSharedDevice diskShare = new DiskSharedDevice( name, m_driver, avmCtx, SharedDevice.Temporary);
-
- // Add the new share to the sessions dynamic share list
-
- sess.addDynamicShare(diskShare);
- share = diskShare;
-
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug(" Mapped share " + name + " - " + diskShare);
- }
- catch ( AVMNotFoundException ex)
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug( "Failed to map share to " + name + ", not such store/version");
- }
- catch ( AVMWrongTypeException ex)
- {
- // DEBUG
-
- if ( logger.isDebugEnabled())
- logger.debug( "Failed to map share to " + name + ", wrong type");
- }
- }
- }
- }
-
- // Check if the share is available
-
- if ( share != null && share.getContext() != null && share.getContext().isAvailable() == false)
- share = null;
-
- // Return the shared device, or null if no matching device was found
-
- return share;
- }
-
- /**
- * Delete temporary shares for the specified session
- *
- * @param sess SrvSession
- */
- public void deleteShares(SrvSession sess)
- {
-
- // Check if the session has any dynamic shares
-
- if ( sess.hasDynamicShares() == false)
- return;
-
- // Delete the dynamic shares
-
- SharedDeviceList shares = sess.getDynamicShareList();
- Enumeration enm = shares.enumerateShares();
-
- while ( enm.hasMoreElements()) {
-
- // Get the current share from the list
-
- SharedDevice shr = (SharedDevice) enm.nextElement();
-
- // Close the shared device
-
- shr.getContext().CloseContext();
-
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug("Deleted dynamic share " + shr);
- }
-
- // Clear the dynamic share list
-
- shares.removeAllShares();
- }
-
- /**
- * Close the share mapper, release any resources.
- */
- public void closeMapper()
- {
- // TODO Auto-generated method stub
-
- }
-}
diff --git a/source/java/org/alfresco/filesys/avm/AVMSingleFileSearchContext.java b/source/java/org/alfresco/filesys/avm/AVMSingleFileSearchContext.java
deleted file mode 100644
index 5164de6721..0000000000
--- a/source/java/org/alfresco/filesys/avm/AVMSingleFileSearchContext.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-
-package org.alfresco.filesys.avm;
-
-import org.alfresco.jlan.server.filesys.FileAttribute;
-import org.alfresco.jlan.server.filesys.FileInfo;
-import org.alfresco.jlan.server.filesys.SearchContext;
-import org.alfresco.service.cmr.avm.AVMNodeDescriptor;
-
-/**
- * AVM Filesystem Single File Search Context Class
- *
- * Contains the details of a non-wildcard file/folder search, where there is only one result to return.
- *
- * @author GKSpencer
- */
-public class AVMSingleFileSearchContext extends SearchContext {
-
- // Details of the single file/folder
-
- private AVMNodeDescriptor m_fileDetails;
-
- // Flag to indicate file details have been returned
-
- private boolean m_endOfSearch;
-
- // Relative path to the file/folder
-
- private String m_relativePath;
-
- // Mark thel file/folder as read-only
-
- private boolean m_readOnly;
-
- /**
- * Class constructor
- *
- * @param fileDetails AVMNodeDescriptor
- * @param relPath String
- * @param readOnly boolean
- */
- public AVMSingleFileSearchContext( AVMNodeDescriptor fileDetails, String relPath, boolean readOnly)
- {
- m_fileDetails = fileDetails;
- m_relativePath = relPath;
-
- m_readOnly = readOnly;
- }
-
- /**
- * Determine if there are more files for the active search.
- *
- * @return boolean
- */
- public boolean hasMoreFiles()
- {
- return m_endOfSearch == false ? true : false;
- }
-
- /**
- * Return file information for the next file in the active search. Returns false if the search
- * is complete.
- *
- * @param info FileInfo to return the file information.
- * @return true if the file information is valid, else false
- */
- public boolean nextFileInfo(FileInfo info)
- {
- // Check if the file details have been returned
-
- if ( m_endOfSearch == true)
- return false;
-
- // Fill in the file information details
-
- info.setFileName( m_fileDetails.getName());
-
- if ( m_fileDetails.isFile())
- {
- info.setFileSize( m_fileDetails.getLength());
- info.setAllocationSize((m_fileDetails.getLength() + 512L) & 0xFFFFFFFFFFFFFE00L);
- }
- else
- info.setFileSize( 0L);
-
- info.setAccessDateTime( m_fileDetails.getAccessDate());
- info.setCreationDateTime( m_fileDetails.getCreateDate());
- info.setModifyDateTime( m_fileDetails.getModDate());
-
- // Build the file attributes
-
- int attr = 0;
-
- if ( m_fileDetails.isDirectory())
- attr += FileAttribute.Directory;
-
- if ( m_fileDetails.getName().startsWith( ".") ||
- m_fileDetails.getName().equalsIgnoreCase( "Desktop.ini") ||
- m_fileDetails.getName().equalsIgnoreCase( "Thumbs.db"))
- attr += FileAttribute.Hidden;
-
- if ( m_readOnly == true)
- attr += FileAttribute.ReadOnly;
-
- info.setFileAttributes( attr);
- info.setFileId( m_relativePath.hashCode());
-
- // Set the end of search flag, indicate that the file informatin is valid
-
- m_endOfSearch = true;
- return true;
- }
-
- /**
- * Return the file name of the next file in the active search. Returns null is the search is
- * complete.
- *
- * @return String
- */
- public String nextFileName()
- {
- // Check if the file details have been returned
-
- if ( m_endOfSearch == true)
- return null;
-
- // Return the file/folder name, set the end of search flag
-
- m_endOfSearch = true;
- return m_fileDetails.getName();
- }
-
- /**
- * Return the total number of file entries for this search if known, else return -1
- *
- * @return int
- */
- public int numberOfEntries()
- {
- return 1;
- }
-
- /**
- * Return the resume id for the current file/directory in the search.
- *
- * @return int
- */
- public int getResumeId()
- {
- return 1;
- }
-
- /**
- * Restart a search at the specified resume point.
- *
- * @param resumeId Resume point id.
- * @return true if the search can be restarted, else false.
- */
- public boolean restartAt(int resumeId)
- {
- // Validate the resume id and clear the end of search flag
-
- if ( resumeId == 1)
- m_endOfSearch = false;
- else
- return false;
- return true;
- }
-
- /**
- * Restart the current search at the specified file.
- *
- * @param info File to restart the search at.
- * @return true if the search can be restarted, else false.
- */
- public boolean restartAt(FileInfo info)
- {
- return true;
- }
-}
diff --git a/source/java/org/alfresco/filesys/avm/DummyFolderPseudoFile.java b/source/java/org/alfresco/filesys/avm/DummyFolderPseudoFile.java
deleted file mode 100644
index 5f34acd485..0000000000
--- a/source/java/org/alfresco/filesys/avm/DummyFolderPseudoFile.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-package org.alfresco.filesys.avm;
-
-import org.alfresco.jlan.server.filesys.FileAttribute;
-import org.alfresco.jlan.server.filesys.FileInfo;
-import org.alfresco.jlan.server.filesys.FileName;
-import org.alfresco.jlan.server.filesys.NetworkFile;
-import org.alfresco.jlan.server.filesys.pseudo.PseudoFile;
-import org.alfresco.jlan.server.filesys.pseudo.PseudoFolderNetworkFile;
-
-
-/**
- * Dummy Folder Pseudo File Class
- *
- *
Represents a dummy folder within the virtualization filesystem view.
- *
- * @author gkspencer
- */
-public class DummyFolderPseudoFile extends PseudoFile {
-
- /**
- * Class constructor
- *
- * @param fname String
- * @param relPath String
- */
- public DummyFolderPseudoFile( String fname, String relPath)
- {
- super( fname, FileAttribute.Directory + FileAttribute.ReadOnly);
-
- // Create static file information from the folder details
-
- FileInfo fInfo = new FileInfo( fname, 0L, FileAttribute.Directory + FileAttribute.ReadOnly);
- fInfo.setCreationDateTime( System.currentTimeMillis());
-
- fInfo.setPath( relPath);
- fInfo.setFileId( relPath.hashCode());
-
- long timeNow = System.currentTimeMillis();
- fInfo.setCreationDateTime( timeNow);
- fInfo.setModifyDateTime( timeNow);
- fInfo.setAccessDateTime( timeNow);
- fInfo.setChangeDateTime( timeNow);
-
- setFileInfo( fInfo);
- }
-
- /**
- * Return a network file for reading/writing the pseudo file
- *
- * @param netPath String
- * @return NetworkFile
- */
- @Override
- public NetworkFile getFile(String netPath) {
-
- // Split the path to get the name
-
- String[] paths = FileName.splitPath( netPath);
-
- // Create a network file for the folder
-
- return new PseudoFolderNetworkFile( paths[1], netPath);
- }
-
- /**
- * Return the file information for the pseudo file
- *
- * @return FileInfo
- */
- @Override
- public FileInfo getFileInfo() {
- return getInfo();
- }
-}
diff --git a/source/java/org/alfresco/filesys/avm/PseudoFileListSearchContext.java b/source/java/org/alfresco/filesys/avm/PseudoFileListSearchContext.java
deleted file mode 100644
index 402786760b..0000000000
--- a/source/java/org/alfresco/filesys/avm/PseudoFileListSearchContext.java
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-
-package org.alfresco.filesys.avm;
-
-import org.alfresco.jlan.server.filesys.FileAttribute;
-import org.alfresco.jlan.server.filesys.FileInfo;
-import org.alfresco.jlan.server.filesys.SearchContext;
-import org.alfresco.jlan.server.filesys.pseudo.PseudoFile;
-import org.alfresco.jlan.server.filesys.pseudo.PseudoFileList;
-import org.alfresco.jlan.util.WildCard;
-
-
-/**
- * Pseudo File List Search Context Class
- *
- *
Returns files from a pseudo file list for a wildcard search.
- *
- * @author gkspencer
- */
-public class PseudoFileListSearchContext extends SearchContext {
-
- // Pseudo file list and current index
-
- private PseudoFileList m_fileList;
- private int m_fileIdx;
-
- // File attributes
-
- private int m_attrib;
-
- // Optional wildcard filter
-
- private WildCard m_filter;
-
- // Mark all files/folders as read-only
-
- private boolean m_readOnly;
-
- /**
- * Class constructor
- *
- * @param fileList PseudoFileList
- * @param attrib int
- * @param filter WildCard
- * @param readOnly boolean
- */
- public PseudoFileListSearchContext( PseudoFileList fileList, int attrib, WildCard filter, boolean readOnly)
- {
- m_attrib = attrib;
- m_filter = filter;
- m_fileList = fileList;
- m_readOnly = readOnly;
- }
-
- /**
- * Determine if there are more files for the active search.
- *
- * @return boolean
- */
- public boolean hasMoreFiles()
- {
- return m_fileIdx < m_fileList.numberOfFiles() ? true : false;
- }
-
- /**
- * Return file information for the next file in the active search. Returns false if the search
- * is complete.
- *
- * @param info FileInfo to return the file information.
- * @return true if the file information is valid, else false
- */
- public boolean nextFileInfo(FileInfo info)
- {
- // Check if there is another file record to return
-
- if ( m_fileIdx >= m_fileList.numberOfFiles())
- return false;
-
- // Search for the next valid file
-
- boolean foundMatch = false;
- PseudoFile curFile = null;
-
- while (foundMatch == false && m_fileIdx < m_fileList.numberOfFiles())
- {
- // Get the next file from the list
-
- curFile = m_fileList.getFileAt( m_fileIdx++);
-
- // Check if the file name matches the search pattern
-
- if ( m_filter != null)
- {
- // Check if the current file matches the wildcard pattern
-
- if ( m_filter.matchesPattern(curFile.getFileName()) == true)
- {
- // Check if the file matches the search attributes
-
- if (FileAttribute.hasAttribute(m_attrib, FileAttribute.Directory) &&
- curFile.isDirectory())
- {
-
- // Found a match
-
- foundMatch = true;
- }
- else if ( curFile.isFile())
- {
-
- // Found a match
-
- foundMatch = true;
- }
-
- // Check if we found a match
-
- if ( foundMatch == false)
- {
-
- // Get the next file from the list
-
- if ( ++m_fileIdx < m_fileList.numberOfFiles())
- curFile = m_fileList.getFileAt( m_fileIdx);
- }
- }
- }
- else
- foundMatch = true;
- }
-
- // If we found a match then fill in the file information
-
- if ( foundMatch)
- {
- // Fill in the file information
-
- info.setFileName( curFile.getFileName());
-
- // Get the file information from the pseudo file
-
- FileInfo pfInfo = curFile.getFileInfo();
-
- if ( curFile.isFile())
- {
- info.setFileSize( pfInfo.getSize());
- info.setAllocationSize( pfInfo.getAllocationSize());
- }
- else
- info.setFileSize( 0L);
-
- info.setAccessDateTime( pfInfo.getAccessDateTime());
- info.setCreationDateTime( pfInfo.getCreationDateTime());
- info.setModifyDateTime( pfInfo.getModifyDateTime());
-
- // Build the file attributes
-
- int attr = pfInfo.getFileAttributes();
-
- if ( pfInfo.isHidden() == false &&
- curFile.getFileName().startsWith( ".") ||
- curFile.getFileName().equalsIgnoreCase( "Desktop.ini") ||
- curFile.getFileName().equalsIgnoreCase( "Thumbs.db"))
- attr += FileAttribute.Hidden;
-
- // Check if the file/folder should be marked as read-only
-
- if ( m_readOnly && pfInfo.isReadOnly() == false)
- attr += FileAttribute.ReadOnly;
-
- info.setFileAttributes( attr);
- info.setFileId( pfInfo.getFileId());
- }
-
- // Indicate if the file information is valid
-
- return foundMatch;
- }
-
- /**
- * Return the file name of the next file in the active search. Returns null is the search is
- * complete.
- *
- * @return String
- */
- public String nextFileName()
- {
- // Check if there is another file record to return
-
- // Find the next matching file name
-
- while ( m_fileIdx < m_fileList.numberOfFiles()) {
-
- // Check if the current file name matches the search pattern
-
- String fname = m_fileList.getFileAt( m_fileIdx++).getFileName();
-
- if ( m_filter.matchesPattern(fname))
- return fname;
- }
-
- // No more matching file names
-
- return null;
- }
-
- /**
- * Return the total number of file entries for this search if known, else return -1
- *
- * @return int
- */
- public int numberOfEntries()
- {
- return m_fileList.numberOfFiles();
- }
-
- /**
- * Return the resume id for the current file/directory in the search.
- *
- * @return int
- */
- public int getResumeId()
- {
- return m_fileIdx;
- }
-
- /**
- * Restart a search at the specified resume point.
- *
- * @param resumeId Resume point id.
- * @return true if the search can be restarted, else false.
- */
- public boolean restartAt(int resumeId)
- {
- // Range check the resume id
-
- int resId = resumeId - 1;
-
- if ( resId < 0 || resId >= m_fileList.numberOfFiles())
- return false;
-
- // Reset the current file index
-
- m_fileIdx = resId;
- return true;
- }
-
- /**
- * Restart the current search at the specified file.
- *
- * @param info File to restart the search at.
- * @return true if the search can be restarted, else false.
- */
- public boolean restartAt(FileInfo info)
- {
- // Search backwards from the current file
-
- int curFileIdx = m_fileIdx;
-
- if (m_fileIdx >= m_fileList.numberOfFiles())
- {
- m_fileIdx = m_fileList.numberOfFiles() - 1;
- }
-
- while ( m_fileIdx > 0) {
-
- // Check if the current file is the required search restart point
-
- if ( m_fileList.getFileAt( m_fileIdx).getFileName().equals( info.getFileName()))
- return true;
- else
- m_fileIdx--;
- }
-
- // Failed to find the restart file
-
- m_fileIdx = curFileIdx;
- return false;
- }
-}
diff --git a/source/java/org/alfresco/filesys/avm/StorePseudoFile.java b/source/java/org/alfresco/filesys/avm/StorePseudoFile.java
deleted file mode 100644
index 27ca113b1f..0000000000
--- a/source/java/org/alfresco/filesys/avm/StorePseudoFile.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-
-package org.alfresco.filesys.avm;
-
-import org.alfresco.jlan.server.filesys.FileAttribute;
-import org.alfresco.jlan.server.filesys.FileInfo;
-import org.alfresco.jlan.server.filesys.FileName;
-import org.alfresco.jlan.server.filesys.NetworkFile;
-import org.alfresco.jlan.server.filesys.pseudo.PseudoFile;
-import org.alfresco.jlan.server.filesys.pseudo.PseudoFolderNetworkFile;
-import org.alfresco.service.cmr.avm.AVMStoreDescriptor;
-
-/**
- * Store Pseudo File Class
- *
- *
Represents an AVM store as a folder.
- *
- * @author gkspencer
- */
-public class StorePseudoFile extends PseudoFile {
-
- // Store type
-
- private int m_storeType = StoreType.Normal;
-
- // Web project this sandbox links to, or null if this store is not linked
-
- private String m_webProject;
-
- // User name if this is an author sandbox for a web project
-
- private String m_userName;
-
- /**
- * Class constructor
- *
- * @param storeDesc AVMStoreDescriptor
- * @param relPath String
- * @param storeType int
- */
- public StorePseudoFile( AVMStoreDescriptor storeDesc, String relPath, int storeType)
- {
- super( storeDesc.getName(), FileAttribute.Directory + FileAttribute.ReadOnly);
-
- // Create static file information from the store details
-
- FileInfo fInfo = new FileInfo( storeDesc.getName(), 0L, FileAttribute.Directory + FileAttribute.ReadOnly);
-
- fInfo.setCreationDateTime( storeDesc.getCreateDate());
- fInfo.setModifyDateTime( storeDesc.getCreateDate());
- fInfo.setAccessDateTime( storeDesc.getCreateDate());
- fInfo.setChangeDateTime( storeDesc.getCreateDate());
-
- fInfo.setPath( relPath);
- fInfo.setFileId( relPath.hashCode());
-
- setFileInfo( fInfo);
-
- setStoreType( storeType);
- }
-
- /**
- * Class constructor
- *
- * @param storeName String
- * @param relPath String
- */
- public StorePseudoFile( String storeName, String relPath)
- {
- super( storeName, FileAttribute.Directory + FileAttribute.ReadOnly);
-
- // Create static file information from the store details
-
- FileInfo fInfo = new FileInfo( storeName, 0L, FileAttribute.Directory + FileAttribute.ReadOnly);
-
- long timeNow = System.currentTimeMillis();
- fInfo.setCreationDateTime( timeNow);
- fInfo.setModifyDateTime( timeNow);
- fInfo.setAccessDateTime( timeNow);
- fInfo.setChangeDateTime( timeNow);
-
- fInfo.setPath( relPath);
- fInfo.setFileId( relPath.hashCode());
-
- setFileInfo( fInfo);
- }
-
- /**
- * Return a network file for reading/writing the pseudo file
- *
- * @param netPath String
- * @return NetworkFile
- */
- @Override
- public NetworkFile getFile(String netPath) {
-
- // Split the path to get the name
-
- String[] paths = FileName.splitPath( netPath);
-
- // Create a network file for the folder
-
- return new PseudoFolderNetworkFile( paths[1], netPath);
- }
-
- /**
- * Return the file information for the pseudo file
- *
- * @return FileInfo
- */
- @Override
- public FileInfo getFileInfo() {
- return getInfo();
- }
-
- /**
- * Return the store type
- *
- * @return int
- */
- public final int isStoreType()
- {
- return m_storeType;
- }
-
- /**
- * Check if this store is linked to a web project
- *
- * @return boolean
- */
- public final boolean hasWebProject()
- {
- return m_webProject != null ? true : false;
- }
-
- /**
- * Get the web project that this store links to, or null if not linked
- *
- * @return String
- */
- public final String getWebProject()
- {
- return m_webProject;
- }
-
- /**
- * Set the web project that this store is linked to
- *
- * @param webProject String
- */
- public final void setWebProject(String webProject)
- {
- m_webProject = webProject;
- }
-
- /**
- * Check if this store is an author sandbox
- *
- * @return boolean
- */
- public final boolean hasUserName()
- {
- return m_userName != null ? true : false;
- }
-
- /**
- * Get the owner of this sandbox
- *
- * @return String
- */
- public final String getUserName()
- {
- return m_userName;
- }
-
- /**
- * Set the owner of this sandbox
- *
- * @param userName String
- */
- public final void setUserName(String userName)
- {
- m_userName = userName;
- }
-
- /**
- * Set the store type
- *
- * @param storeType int
- */
- public final void setStoreType(int storeType)
- {
- m_storeType = storeType;
- }
-}
diff --git a/source/java/org/alfresco/filesys/avm/StoreType.java b/source/java/org/alfresco/filesys/avm/StoreType.java
deleted file mode 100644
index d32477e93a..0000000000
--- a/source/java/org/alfresco/filesys/avm/StoreType.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see .
- */
-package org.alfresco.filesys.avm;
-
-/**
- * Store Types Class
- *
- * @author gkspencer
- */
-public class StoreType {
-
- // Store types
-
- public static final int Normal = 0;
-
- // Site data store types
-
- public static final int SiteStore = 1;
-
- // Web project store types
-
- public static final int WebAuthorMain = 2;
- public static final int WebAuthorPreview = 3;
- public static final int WebStagingPreview = 4;
- public static final int WebStagingMain = 5;
-
- // Store type strings
-
- private static final String[] _types = { "Normal", "SiteStore", "AuthorMain", "AuthorPreview", "StagingPreview", "StagingMain" };
-
- /**
- * Return a store type as a string
- *
- * @param typ int
- * @return String
- */
- public final static String asString( int typ)
- {
- if ( typ < 0 || typ > _types.length)
- return "Invalid";
- return _types[ typ];
- }
-}
diff --git a/source/java/org/alfresco/filesys/avm/VersionPseudoFile.java b/source/java/org/alfresco/filesys/avm/VersionPseudoFile.java
deleted file mode 100644
index cc48fe22fa..0000000000
--- a/source/java/org/alfresco/filesys/avm/VersionPseudoFile.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-
-package org.alfresco.filesys.avm;
-
-import org.alfresco.jlan.server.filesys.FileAttribute;
-import org.alfresco.jlan.server.filesys.FileInfo;
-import org.alfresco.jlan.server.filesys.FileName;
-import org.alfresco.jlan.server.filesys.NetworkFile;
-import org.alfresco.jlan.server.filesys.pseudo.PseudoFile;
-import org.alfresco.jlan.server.filesys.pseudo.PseudoFolderNetworkFile;
-import org.alfresco.service.cmr.avm.VersionDescriptor;
-
-/**
- * Version Pseudo File Class
- *
- *
Represents an AVM store version as a folder.
- *
- * @author gkspencer
- */
-public class VersionPseudoFile extends PseudoFile {
-
- /**
- * Class constructor
- *
- * @param name String
- * @param relPath String
- */
- public VersionPseudoFile( String name, String relPath)
- {
- super( name, FileAttribute.Directory + FileAttribute.ReadOnly);
-
- // Create static file information from the store details
-
- FileInfo fInfo = new FileInfo( name, 0L, FileAttribute.Directory + FileAttribute.ReadOnly);
-
- fInfo.setPath( relPath);
- fInfo.setFileId( relPath.hashCode());
-
- long timeNow = System.currentTimeMillis();
- fInfo.setCreationDateTime( timeNow);
- fInfo.setModifyDateTime( timeNow);
- fInfo.setAccessDateTime( timeNow);
- fInfo.setChangeDateTime( timeNow);
-
- setFileInfo( fInfo);
- }
-
- /**
- * Class constructor
- *
- * @param name String
- * @param verDesc VersionDescriptor
- * @param relPath String
- */
- public VersionPseudoFile( String name, VersionDescriptor verDesc, String relPath)
- {
- super( name, FileAttribute.Directory + FileAttribute.ReadOnly);
-
- // Create static file information from the store details
-
- FileInfo fInfo = new FileInfo( name, 0L, FileAttribute.Directory + FileAttribute.ReadOnly);
- fInfo.setCreationDateTime( verDesc.getCreateDate());
-
- fInfo.setPath( relPath);
- fInfo.setFileId( relPath.hashCode());
-
- long timeNow = System.currentTimeMillis();
- fInfo.setCreationDateTime( timeNow);
- fInfo.setModifyDateTime( timeNow);
- fInfo.setAccessDateTime( timeNow);
- fInfo.setChangeDateTime( timeNow);
-
- setFileInfo( fInfo);
- }
-
- /**
- * Return a network file for reading/writing the pseudo file
- *
- * @param netPath String
- * @return NetworkFile
- */
- @Override
- public NetworkFile getFile(String netPath) {
-
- // Split the path to get the name
-
- String[] paths = FileName.splitPath( netPath);
-
- // Create a network file for the folder
-
- return new PseudoFolderNetworkFile( paths[1], netPath);
- }
-
- /**
- * Return the file information for the pseudo file
- *
- * @return FileInfo
- */
- @Override
- public FileInfo getFileInfo() {
- return getInfo();
- }
-}
diff --git a/source/java/org/alfresco/filesys/avm/WebProjectStorePseudoFile.java b/source/java/org/alfresco/filesys/avm/WebProjectStorePseudoFile.java
deleted file mode 100644
index 21a3799bb0..0000000000
--- a/source/java/org/alfresco/filesys/avm/WebProjectStorePseudoFile.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-
-package org.alfresco.filesys.avm;
-
-import java.util.Hashtable;
-
-import org.alfresco.jlan.server.filesys.FileAttribute;
-import org.alfresco.jlan.server.filesys.FileInfo;
-import org.alfresco.service.cmr.avm.AVMStoreDescriptor;
-import org.alfresco.service.cmr.repository.NodeRef;
-
-/**
- * Web Project Store Pseudo File Class
- *
- *
Represents an AVM store as a folder.
- *
- * @author gkspencer
- */
-public class WebProjectStorePseudoFile extends StorePseudoFile {
-
- // Store/web project user access roles
-
- public static final int RoleNone = 0;
- public static final int RolePublisher = 1;
- public static final int RoleContentManager = 2;
-
- // Node ref for this store
-
- private NodeRef m_noderef;
-
- // List of users that are content managers/publishers for this web project store
-
- private Hashtable m_users;
-
- /**
- * Class constructor
- *
- * @param storeDesc AVMStoreDescriptor
- * @param relPath String
- * @param nodeRef NodeRef
- */
- public WebProjectStorePseudoFile( AVMStoreDescriptor storeDesc, String relPath, NodeRef nodeRef)
- {
- super( storeDesc, relPath, StoreType.WebStagingMain);
-
- // Create static file information from the store details
-
- FileInfo fInfo = new FileInfo( storeDesc.getName(), 0L, FileAttribute.Directory + FileAttribute.ReadOnly);
-
- fInfo.setCreationDateTime( storeDesc.getCreateDate());
- fInfo.setModifyDateTime( storeDesc.getCreateDate());
- fInfo.setAccessDateTime( storeDesc.getCreateDate());
- fInfo.setChangeDateTime( storeDesc.getCreateDate());
-
- fInfo.setPath( relPath);
- fInfo.setFileId( relPath.hashCode());
-
- setFileInfo( fInfo);
-
- // Set the associated node ref for the web project
-
- m_noderef = nodeRef;
- }
-
- /**
- * Class constructor
- *
- * @param storeName String
- * @param relPath String
- * @param nodeRef NodeRef
- */
- public WebProjectStorePseudoFile( String storeName, String relPath, NodeRef nodeRef)
- {
- super( storeName, relPath);
-
- // Create static file information from the store details
-
- FileInfo fInfo = new FileInfo( storeName, 0L, FileAttribute.Directory + FileAttribute.ReadOnly);
-
- long timeNow = System.currentTimeMillis();
- fInfo.setCreationDateTime( timeNow);
- fInfo.setModifyDateTime( timeNow);
- fInfo.setAccessDateTime( timeNow);
- fInfo.setChangeDateTime( timeNow);
-
- fInfo.setPath( relPath);
- fInfo.setFileId( relPath.hashCode());
-
- setFileInfo( fInfo);
-
- // Set the associated node ref for the web project
-
- m_noderef = nodeRef;
- }
-
- /**
- * Check if the associated node ref is valid
- *
- * @return boolean
- */
- public final boolean hasNodeRef()
- {
- return m_noderef != null ? true : false;
- }
-
- /**
- * Get the associated node ref for the store
- *
- * @return NodeRef
- */
- public final NodeRef getNodeRef()
- {
- return m_noderef;
- }
-
- /**
- * Set the associated node ref for the store
- *
- * @param node NodeRef
- */
- public final void setNodeRef(NodeRef node)
- {
- m_noderef = node;
- }
-
- /**
- * Return the role for the specified user within this web project
- *
- * @param userName String
- * @return int
- */
- public final int getUserRole(String userName)
- {
- if ( m_users == null)
- return RoleNone;
-
- Integer role = m_users.get( userName);
- return role != null ? role.intValue() : RoleNone;
- }
-
- /**
- * Add a user role for this web project
- *
- * @param userName String
- * @param role int
- */
- public final void addUserRole(String userName, int role)
- {
- if ( m_users == null)
- m_users = new Hashtable();
-
- m_users.put(userName, Integer.valueOf(role));
- }
-
- /**
- * Remove a user role for this project
- *
- * @param userName String
- */
- public final void removeUserRole(String userName)
- {
- if ( m_users != null)
- m_users.remove(userName);
- }
-}
diff --git a/source/java/org/alfresco/filesys/avm/package-info.java b/source/java/org/alfresco/filesys/avm/package-info.java
deleted file mode 100644
index 301b0d456d..0000000000
--- a/source/java/org/alfresco/filesys/avm/package-info.java
+++ /dev/null
@@ -1,5 +0,0 @@
-/**
- */
-@PackageMarker
-package org.alfresco.filesys.avm;
-import org.alfresco.util.PackageMarker;
diff --git a/source/java/org/alfresco/filesys/config/ServerConfigurationBean.java b/source/java/org/alfresco/filesys/config/ServerConfigurationBean.java
index 934920e8b5..b9744b1a7b 100644
--- a/source/java/org/alfresco/filesys/config/ServerConfigurationBean.java
+++ b/source/java/org/alfresco/filesys/config/ServerConfigurationBean.java
@@ -40,8 +40,6 @@ import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.filesys.AbstractServerConfigurationBean;
import org.alfresco.filesys.alfresco.AlfrescoContext;
import org.alfresco.filesys.alfresco.ExtendedDiskInterface;
-import org.alfresco.filesys.avm.AVMContext;
-import org.alfresco.filesys.avm.AVMDiskDriver;
import org.alfresco.filesys.config.acl.AccessControlListBean;
import org.alfresco.filesys.repo.BufferedContentDiskDriver;
import org.alfresco.filesys.repo.ContentContext;
@@ -107,7 +105,6 @@ public class ServerConfigurationBean extends AbstractServerConfigurationBean imp
private FTPConfigBean ftpConfigBean;
private NFSConfigBean nfsConfigBean;
private List filesystemContexts;
- private boolean avmAllStores;
private SecurityConfigBean securityConfigBean;
private CoreServerConfigBean coreServerConfigBean;
@@ -153,11 +150,6 @@ public class ServerConfigurationBean extends AbstractServerConfigurationBean imp
this.filesystemContexts = filesystemContexts;
}
- public void setAvmAllStores(boolean avmAllStores)
- {
- this.avmAllStores = avmAllStores;
- }
-
public void setSecurityConfigBean(SecurityConfigBean securityConfigBean)
{
this.securityConfigBean = securityConfigBean;
@@ -1742,133 +1734,86 @@ public class ServerConfigurationBean extends AbstractServerConfigurationBean imp
DiskSharedDevice filesys = null;
- if (filesystem instanceof AVMContext)
+ // Create a new filesystem driver instance and register a context for
+ // the new filesystem
+
+ ExtendedDiskInterface filesysDriver = getRepoDiskInterface();
+ ContentContext filesysContext = (ContentContext) filesystem;
+
+ if(clusterConfigBean != null && clusterConfigBean.getClusterEnabled())
{
- // Create a new filesystem driver instance and register a context for
- // the new filesystem
-
- ExtendedDiskInterface filesysDriver = getAvmDiskInterface();
- DiskDeviceContext diskCtx = (DiskDeviceContext) filesystem;
-
- if(clusterConfigBean != null && clusterConfigBean.getClusterEnabled())
+ if(logger.isDebugEnabled())
{
- if(logger.isDebugEnabled())
- {
- logger.debug("start hazelcast cache : " + clusterConfigBean.getClusterName() + ", shareName: "+ diskCtx.getShareName());
- }
- GenericConfigElement hazelConfig = createClusterConfig("cifs.avm."+diskCtx.getShareName());
- HazelCastClusterFileStateCache hazel = new HazelCastClusterFileStateCache();
- hazel.initializeCache(hazelConfig, this);
- diskCtx.setStateCache(hazel);
+ logger.debug("start hazelcast cache : " + clusterConfigBean.getClusterName() + ", shareName: "+ filesysContext.getShareName());
}
- else
- {
- // Check if the filesystem uses the file state cache, if so then add to the file state reaper
- StandaloneFileStateCache standaloneCache = new StandaloneFileStateCache();
- standaloneCache.initializeCache( new GenericConfigElement( ""), this);
- diskCtx.setStateCache(standaloneCache);
- }
-
- if ( diskCtx.hasStateCache()) {
-
- // Register the state cache with the reaper thread
-
- fsysConfig.addFileStateCache( filesystem.getDeviceName(), diskCtx.getStateCache());
- }
-
- filesysDriver.registerContext(filesystem);
-
- // Create the shared filesystem
-
- filesys = new DiskSharedDevice(filesystem.getDeviceName(), filesysDriver, (AVMContext)filesystem);
- filesys.setConfiguration( this);
- // Start the filesystem
-
- ((AVMContext)filesystem).startFilesystem(filesys);
+ GenericConfigElement hazelConfig = createClusterConfig("cifs.filesys."+filesysContext.getShareName());
+ HazelCastClusterFileStateCache hazel = new HazelCastClusterFileStateCache();
+ hazel.initializeCache(hazelConfig, this);
+ filesysContext.setStateCache(hazel);
}
else
{
- // Create a new filesystem driver instance and register a context for
- // the new filesystem
-
- ExtendedDiskInterface filesysDriver = getRepoDiskInterface();
- ContentContext filesysContext = (ContentContext) filesystem;
-
- if(clusterConfigBean != null && clusterConfigBean.getClusterEnabled())
- {
- if(logger.isDebugEnabled())
- {
- logger.debug("start hazelcast cache : " + clusterConfigBean.getClusterName() + ", shareName: "+ filesysContext.getShareName());
- }
- GenericConfigElement hazelConfig = createClusterConfig("cifs.filesys."+filesysContext.getShareName());
- HazelCastClusterFileStateCache hazel = new HazelCastClusterFileStateCache();
- hazel.initializeCache(hazelConfig, this);
- filesysContext.setStateCache(hazel);
- }
- else
- {
- // Create state cache here and inject
- StandaloneFileStateCache standaloneCache = new StandaloneFileStateCache();
- standaloneCache.initializeCache( new GenericConfigElement( ""), this);
- filesysContext.setStateCache(standaloneCache);
- }
-
- if ( filesysContext.hasStateCache()) {
-
- // Register the state cache with the reaper thread
- // has many side effects including initialisation of the cache
- fsysConfig.addFileStateCache( filesystem.getDeviceName(), filesysContext.getStateCache());
-
- // Create the lock manager for the context.
- FileStateLockManager lockMgr = new FileStateLockManager(filesysContext.getStateCache());
- filesysContext.setLockManager(lockMgr);
- filesysContext.setOpLockManager(lockMgr);
- }
-
- if ((!cifsConfigBean.getServerEnabled() && !ftpConfigBean.getServerEnabled())
- && isContentDiskDriver2(filesysDriver))
- {
- ((ContentContext) filesystem).setDisableNodeMonitor(true);
- }
-
- filesysDriver.registerContext(filesystem);
-
- // Check if an access control list has been specified
-
- AccessControlList acls = null;
- AccessControlListBean accessControls = filesysContext.getAccessControlList();
- if (accessControls != null)
- {
- // Parse the access control list
- acls = accessControls.toAccessControlList(secConfig);
- }
- else if (secConfig.hasGlobalAccessControls())
- {
-
- // Use the global access control list for this disk share
- acls = secConfig.getGlobalAccessControls();
- }
-
- // Create the shared filesystem
-
- filesys = new DiskSharedDevice(filesystem.getDeviceName(), filesysDriver, filesysContext);
- filesys.setConfiguration( this);
-
- // Add any access controls to the share
-
- filesys.setAccessControlList(acls);
-
-
-
- // Check if change notifications should be enabled
-
- if ( filesysContext.getDisableChangeNotifications() == false)
- filesysContext.enableChangeHandler( true);
-
- // Start the filesystem
-
- filesysContext.startFilesystem(filesys);
+ // Create state cache here and inject
+ StandaloneFileStateCache standaloneCache = new StandaloneFileStateCache();
+ standaloneCache.initializeCache( new GenericConfigElement( ""), this);
+ filesysContext.setStateCache(standaloneCache);
}
+
+ if ( filesysContext.hasStateCache()) {
+
+ // Register the state cache with the reaper thread
+ // has many side effects including initialisation of the cache
+ fsysConfig.addFileStateCache( filesystem.getDeviceName(), filesysContext.getStateCache());
+
+ // Create the lock manager for the context.
+ FileStateLockManager lockMgr = new FileStateLockManager(filesysContext.getStateCache());
+ filesysContext.setLockManager(lockMgr);
+ filesysContext.setOpLockManager(lockMgr);
+ }
+
+ if ((!cifsConfigBean.getServerEnabled() && !ftpConfigBean.getServerEnabled())
+ && isContentDiskDriver2(filesysDriver))
+ {
+ ((ContentContext) filesystem).setDisableNodeMonitor(true);
+ }
+
+ filesysDriver.registerContext(filesystem);
+
+ // Check if an access control list has been specified
+
+ AccessControlList acls = null;
+ AccessControlListBean accessControls = filesysContext.getAccessControlList();
+ if (accessControls != null)
+ {
+ // Parse the access control list
+ acls = accessControls.toAccessControlList(secConfig);
+ }
+ else if (secConfig.hasGlobalAccessControls())
+ {
+
+ // Use the global access control list for this disk share
+ acls = secConfig.getGlobalAccessControls();
+ }
+
+ // Create the shared filesystem
+
+ filesys = new DiskSharedDevice(filesystem.getDeviceName(), filesysDriver, filesysContext);
+ filesys.setConfiguration( this);
+
+ // Add any access controls to the share
+
+ filesys.setAccessControlList(acls);
+
+
+
+ // Check if change notifications should be enabled
+
+ if ( filesysContext.getDisableChangeNotifications() == false)
+ filesysContext.enableChangeHandler( true);
+
+ // Start the filesystem
+
+ filesysContext.startFilesystem(filesys);
// Add the new filesystem
@@ -1891,50 +1836,6 @@ public class ServerConfigurationBean extends AbstractServerConfigurationBean imp
logger.warn("No filesystems defined");
}
- // Check if shares should be added for all AVM stores
- if (this.avmAllStores && getAvmDiskInterface() != null)
- {
- // Get the list of store names
-
- AVMDiskDriver avmDriver = (AVMDiskDriver) getAvmDiskInterface();
- StringList storeNames = avmDriver.getAVMStoreNames();
-
- // Add shares for each of the store names, if the share name does not already exist
-
- if (storeNames != null && storeNames.numberOfStrings() > 0)
- {
- // Add a share for each store
-
- for (int i = 0; i < storeNames.numberOfStrings(); i++)
- {
- String storeName = storeNames.getStringAt(i);
-
- // Check if a share of the same name already exists
-
- if (fsysConfig.getShares().findShare(storeName, ShareType.DISK, true) == null)
- {
- // Create the new share for the store
-
- AVMContext avmContext = new AVMContext(storeName, storeName + ":/", AVMContext.VERSION_HEAD);
-// avmContext.enableStateCache(this, true);
-
- // Create the shared filesystem
-
- DiskSharedDevice filesys = new DiskSharedDevice(storeName, avmDriver, avmContext);
- filesys.setConfiguration( this);
-
- fsysConfig.addShare( filesys);
-
- // DEBUG
-
- if (logger.isDebugEnabled())
- logger.debug("Added AVM share " + storeName);
- }
- }
- }
- }
-
-
// home folder share mapper could be declared in security config
}
diff --git a/source/java/org/alfresco/model/WCMAppModel.java b/source/java/org/alfresco/model/WCMAppModel.java
deleted file mode 100644
index 12d722e69e..0000000000
--- a/source/java/org/alfresco/model/WCMAppModel.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see .
- */
-package org.alfresco.model;
-
-import org.alfresco.service.namespace.NamespaceService;
-import org.alfresco.service.namespace.QName;
-
-/**
- * @author Kevin Roast
- */
-public interface WCMAppModel
-{
- // AVM web folder
- static final QName TYPE_AVMWEBFOLDER = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "webfolder");
- static final QName PROP_AVMSTORE = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "avmstore");
- static final QName PROP_DEFAULTWEBAPP = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "defaultwebapp");
- static final QName PROP_DEPLOYTO = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployto");
- static final QName PROP_SELECTEDDEPLOYTO = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "selecteddeployto");
- static final QName PROP_SELECTEDDEPLOYVERSION = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "selecteddeployversion");
- static final QName PROP_ISSOURCE = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "issource");
- static final QName PROP_PREVIEW_PROVIDER = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "previewprovidername");
- static final QName ASSOC_WEBUSER = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "webuser");
- static final QName ASSOC_WEBFORM = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "webform");
- static final QName ASSOC_WEBWORKFLOWDEFAULTS = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "webworkflowdefaults");
- static final QName ASSOC_DEPLOYMENTSERVER = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deploymentserver");
- static final QName ASSOC_DEPLOYMENTATTEMPT = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deploymentattempt");
- static final QName ASSOC_DEPLOYMENTREPORT = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deploymentreport");
-
- // AVM web user reference
- static final QName TYPE_WEBUSER = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "webuser");
- static final QName PROP_WEBUSERNAME = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "username");
- static final QName PROP_WEBUSERROLE = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "role");
-
- // AVM web form
- static final QName TYPE_WEBFORM = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "webform");
- static final QName PROP_FORMNAME = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "formname");
- static final QName ASSOC_WEBFORMTEMPLATE = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "webformtemplate");
- static final QName ASSOC_WORKFLOWDEFAULTS = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "workflowdefaults");
-
- // AVM web form template
- static final QName TYPE_WEBFORMTEMPLATE = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "webformtemplate");
- static final QName PROP_BASE_RENDERING_ENGINE_TEMPLATE_NAME = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "baserenderingenginetemplatename");
-
- // AVM workflow defaults
- static final QName TYPE_WORKFLOW_DEFAULTS = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "workflowdefaults");
- static final QName PROP_WORKFLOW_NAME = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "workflowname");
- static final QName PROP_WORKFLOW_DEFAULT_PROPERTIES = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "workflowdefaultproperties");
-
- // AVM web workflow defaults
- static final QName TYPE_WEBWORKFLOWDEFAULTS = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "webworkflowdefaults");
-
- // AVM website deployment server
- static final String CONSTRAINT_ALFDEPLOY = "alfresco";
- static final String CONSTRAINT_FILEDEPLOY = "file";
- static final String CONSTRAINT_LIVESERVER = "live";
- static final String CONSTRAINT_TESTSERVER = "test";
- static final QName TYPE_DEPLOYMENTSERVER = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deploymentserver");
- static final QName PROP_DEPLOYTYPE = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deploytype");
- static final QName PROP_DEPLOYSERVERTYPE = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployservertype");
- static final QName PROP_DEPLOYSERVERHOST = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployserverhost");
- static final QName PROP_DEPLOYSERVERPORT = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployserverport");
- static final QName PROP_DEPLOYSERVERNAME = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployservername");
- static final QName PROP_DEPLOYSERVERUSERNAME = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployserverusername");
- static final QName PROP_DEPLOYSERVERPASSWORD = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployserverpassword");
- static final QName PROP_DEPLOYSERVERGROUP = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployservergroup");
- static final QName PROP_DEPLOYSERVERADPTERNAME = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployserveradaptername");
- static final QName PROP_DEPLOYSERVERURL = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployserverurl");
- static final QName PROP_DEPLOYSERVERTARGET = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployservertarget");
- static final QName PROP_DEPLOYSOURCEPATH = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deploysourcepath");
- static final QName PROP_DEPLOYEXCLUDES = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployexcludes");
- static final QName PROP_DEPLOYSERVERALLOCATEDTO = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployserverallocatedto");
- static final QName PROP_DEPLOYONAPPROVAL = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployonapproval");
-
- // AVM website deployment attempt
- static final QName TYPE_DEPLOYMENTATTEMPT = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deploymentattempt");
- static final QName PROP_DEPLOYATTEMPTID = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployattemptid");
- static final QName PROP_DEPLOYATTEMPTTYPE = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployattempttype");
- static final QName PROP_DEPLOYATTEMPTSTORE = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployattemptstore");
- static final QName PROP_DEPLOYATTEMPTVERSION = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployattemptversion");
- static final QName PROP_DEPLOYATTEMPTSERVERS = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployattemptservers");
- static final QName PROP_DEPLOYATTEMPTTIME = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployattempttime");
- static final QName ASSOC_DEPLOYMENTREPORTS = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deploymentreports");
-
- // AVM website deployment report
- static final QName TYPE_DEPLOYMENTREPORT = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deploymentreport");
- static final QName PROP_DEPLOYSERVER = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployserver");
- static final QName PROP_DEPLOYVERSION = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployversion");
- static final QName PROP_DEPLOYSUCCESSFUL = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deploysuccessful");
- static final QName PROP_DEPLOYFAILEDREASON = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployfailedreason");
- static final QName PROP_DEPLOYSTARTTIME = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deploystarttime");
- static final QName PROP_DEPLOYENDTIME = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployendtime");
- static final QName PROP_DEPLOYSERVERNAMEUSED = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployservernameused");
- static final QName PROP_DEPLOYSERVERUSERNAMEUSED = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployserverusernameused");
- static final QName PROP_DEPLOYSERVERTARGETUSED = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployservertargetused");
- static final QName PROP_DEPLOYSOURCEPATHUSED = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deploysourcepathused");
- static final QName PROP_DEPLOYEXCLUDESUSED = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployexcludesused");
- static final QName PROP_DEPLOYSERVERURLUSED = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployserverurlused");
-
- // AVM webapp aspect
- static final QName ASPECT_WEBAPP = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "webapp");
-
- // AVM filename pattern aspect
- static final QName ASPECT_FILENAMEPATTERN = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "filenamepattern");
- static final QName PROP_FILENAMEPATTERN = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "filenamepattern");
-
- // AVM output path pattern aspect
- static final QName ASPECT_OUTPUT_PATH_PATTERN = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "outputpathpattern");
- static final QName PROP_OUTPUT_PATH_PATTERN = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "outputpathpattern");
-
- // The XForms data capture form aspect.
- static final QName TYPE_FORMFOLDER = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "formfolder");
- static final QName ASPECT_FORM = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "form");
-
- /**
- * there was a mismapping between this definition of PROP_XML_SCHEMA here and in wcmAppModel.xml.
- * leaving in this definition for now as a failover.
- */
- static final QName PROP_XML_SCHEMA_OLD = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "schema");
- static final QName PROP_XML_SCHEMA = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "xmlschema");
- static final QName PROP_XML_SCHEMA_ROOT_ELEMENT_NAME = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "xmlschemarootelementname");
- static final QName ASSOC_RENDERING_ENGINE_TEMPLATES = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "renderingenginetemplates");
- static final QName ASSOC_FORM_WORKFLOW_DEFAULTS = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "formworkflowdefaults");
-
- // An XML to something else tranformer aspect.
- static final QName ASPECT_RENDERING_ENGINE_TEMPLATE = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "renderingenginetemplate");
- static final QName PROP_PARENT_RENDERING_ENGINE_NAME = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "parentrenderingenginename");
- static final QName PROP_FORM_SOURCE = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "formsource");
- static final QName ASSOC_RENDITION_PROPERTIES = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "renditionproperties");
-
- static final QName ASPECT_FORM_INSTANCE_DATA = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "forminstancedata");
- static final QName PROP_PARENT_FORM_NAME = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "parentformname");
- static final QName PROP_RENDITIONS = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "renditions");
- static final QName PROP_ORIGINAL_PARENT_PATH = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "orginalparentpath");
-
- static final QName ASPECT_RENDITION = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "rendition");
- static final QName PROP_PARENT_RENDERING_ENGINE_TEMPLATE = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "parentrenderingenginetemplate");
- static final QName PROP_PARENT_RENDITION_PROPERTIES = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "parentrenditionproperties");
- static final QName PROP_PRIMARY_FORM_INSTANCE_DATA = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "primaryforminstancedata");
-
- static final QName TYPE_RENDITION_PROPERTIES = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "renditionproperties");
- static final QName PROP_MIMETYPE_FOR_RENDITION = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "mimetypeforrendition");
-
- // Aspect to track content that expires
- static final QName ASPECT_EXPIRES = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "expires");
- static final QName PROP_EXPIRATIONDATE = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "expirationDate");
-
- // Aspect to track dm deployed content
- static final QName ASPECT_DEPLOYED = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "deployed");
- static final QName PROP_GUID = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "guid");
-
-}
diff --git a/source/java/org/alfresco/model/WCMModel.java b/source/java/org/alfresco/model/WCMModel.java
deleted file mode 100644
index 929d9c3467..0000000000
--- a/source/java/org/alfresco/model/WCMModel.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-package org.alfresco.model;
-
-import org.alfresco.service.namespace.NamespaceService;
-import org.alfresco.service.namespace.QName;
-
-/**
- * QName definitions for WCM.
- * @author britt
- */
-public interface WCMModel
-{
- // content
- static final QName TYPE_AVM_CONTENT = QName.createQName(NamespaceService.WCM_MODEL_1_0_URI, "avmcontent");
- static final QName TYPE_AVM_PLAIN_CONTENT = QName.createQName(NamespaceService.WCM_MODEL_1_0_URI, "avmplaincontent");
- static final QName TYPE_AVM_LAYERED_CONTENT = QName.createQName(NamespaceService.WCM_MODEL_1_0_URI, "avmlayeredcontent");
- static final QName PROP_AVM_FILE_INDIRECTION = QName.createQName(NamespaceService.WCM_MODEL_1_0_URI, "avmfileindirection");
-
- // folders
- static final QName TYPE_AVM_FOLDER = QName.createQName(NamespaceService.WCM_MODEL_1_0_URI, "avmfolder");
- static final QName TYPE_AVM_PLAIN_FOLDER = QName.createQName(NamespaceService.WCM_MODEL_1_0_URI, "avmplainfolder");
- static final QName TYPE_AVM_LAYERED_FOLDER = QName.createQName(NamespaceService.WCM_MODEL_1_0_URI, "avmlayeredfolder");
- static final QName PROP_AVM_DIR_INDIRECTION = QName.createQName(NamespaceService.WCM_MODEL_1_0_URI, "avmdirindirection");
-
- // Reverted Aspect.
- static final QName ASPECT_REVERTED = QName.createQName(NamespaceService.WCM_MODEL_1_0_URI, "reverted");
- static final QName PROP_REVERTED_ID = QName.createQName(NamespaceService.WCM_MODEL_1_0_URI, "revertedid");
-}
diff --git a/source/java/org/alfresco/model/WCMWorkflowModel.java b/source/java/org/alfresco/model/WCMWorkflowModel.java
deleted file mode 100644
index ea15e0e693..0000000000
--- a/source/java/org/alfresco/model/WCMWorkflowModel.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see .
- */
-package org.alfresco.model;
-
-import org.alfresco.service.namespace.NamespaceService;
-import org.alfresco.service.namespace.QName;
-
-/**
- * @author Gavin Cornwell
- */
-public interface WCMWorkflowModel
-{
- // submission workflow properties and aspects
- static final QName PROP_FROM_PATH = QName.createQName(NamespaceService.WCMWF_MODEL_1_0_URI, "fromPath");
- static final QName PROP_LABEL = QName.createQName(NamespaceService.WCMWF_MODEL_1_0_URI, "label");
- static final QName PROP_LAUNCH_DATE = QName.createQName(NamespaceService.WCMWF_MODEL_1_0_URI, "launchDate");
- static final QName PROP_AUTO_DEPLOY = QName.createQName(NamespaceService.WCMWF_MODEL_1_0_URI, "autoDeploy");
- static final QName PROP_WEBAPP = QName.createQName(NamespaceService.WCMWF_MODEL_1_0_URI, "webapp");
- static final QName ASSOC_WEBPROJECT = QName.createQName(NamespaceService.WCMWF_MODEL_1_0_URI, "webproject");
-}
diff --git a/source/java/org/alfresco/repo/admin/IndexConfigurationCheckerImpl.java b/source/java/org/alfresco/repo/admin/IndexConfigurationCheckerImpl.java
index f1b3a37dd4..bf45a6cfbe 100644
--- a/source/java/org/alfresco/repo/admin/IndexConfigurationCheckerImpl.java
+++ b/source/java/org/alfresco/repo/admin/IndexConfigurationCheckerImpl.java
@@ -81,22 +81,6 @@ public class IndexConfigurationCheckerImpl implements IndexConfigurationChecker
this.searchService = searchService;
}
- /**
- * avm trigger
- * @param avmSnapShotTriggeredIndexingMethodInterceptor
- */
- /* Sparta: remove WCM/AVM
- public void setAvmSnapShotTriggeredIndexingMethodInterceptor(AVMSnapShotTriggeredIndexingMethodInterceptor avmSnapShotTriggeredIndexingMethodInterceptor)
- {
- this.avmSnapShotTriggeredIndexingMethodInterceptor = avmSnapShotTriggeredIndexingMethodInterceptor;
- }
- */
-
-
-
- /* (non-Javadoc)
- * @see org.alfresco.repo.admin.IndexConfigurationChecker#checkIndexConfiguration()
- */
@Override
public List checkIndexConfiguration()
{
@@ -105,7 +89,6 @@ public class IndexConfigurationCheckerImpl implements IndexConfigurationChecker
List missingIndexStoreRefs = new ArrayList(0);
for (StoreRef storeRef : storeRefs)
{
- @SuppressWarnings("unused")
NodeRef rootNodeRef = null;
try
{
@@ -127,32 +110,6 @@ public class IndexConfigurationCheckerImpl implements IndexConfigurationChecker
if (indexRecoveryMode != RecoveryMode.FULL)
{
- if (storeRef.getProtocol().equals(StoreRef.PROTOCOL_AVM))
- {
- /* Sparta: remove WCM/AVM
- if (avmSnapShotTriggeredIndexingMethodInterceptor.isIndexingEnabled())
- {
- IndexMode storeIndexMode = avmSnapShotTriggeredIndexingMethodInterceptor.getIndexMode(storeRef.getIdentifier());
- if (storeIndexMode.equals(IndexMode.UNINDEXED))
- {
- if (logger.isDebugEnabled())
- {
- logger.debug("Skipping index check for store: " + storeRef + " (unindexed AVM store)");
- }
- continue;
- }
- }
- else
- {
- if (logger.isDebugEnabled())
- {
- logger.debug("Skipping index check for store: " + storeRef + " (AVM indexing is disabled)");
- }
- continue;
- }
- */
- }
-
if (logger.isDebugEnabled())
{
logger.debug("Checking index for store: " + storeRef);
diff --git a/source/java/org/alfresco/repo/admin/patch/impl/AVMPermissionDataPatch.java b/source/java/org/alfresco/repo/admin/patch/impl/AVMPermissionDataPatch.java
deleted file mode 100644
index 0d4aee2ea9..0000000000
--- a/source/java/org/alfresco/repo/admin/patch/impl/AVMPermissionDataPatch.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see .
- */
-package org.alfresco.repo.admin.patch.impl;
-
-import org.springframework.extensions.surf.util.I18NUtil;
-import org.alfresco.service.namespace.NamespaceService;
-import org.alfresco.service.namespace.QName;
-
-
-/**
- * The roles defined in permissionsDefinition.xml moved from wca:webfolder to cm:cmobject.
- * This effects the data stored in the permission table.
- *
- *
- */
-public class AVMPermissionDataPatch extends AbstractPermissionChangePatch
-{
- private static final String MSG_SUCCESS = "patch.updateAvmPermissionData.result";
-
- private static final QName TYPE_QNAME_OLD = QName.createQName(NamespaceService.WCMAPP_MODEL_1_0_URI, "webfolder");
- private static final QName TYPE_QNAME_NEW = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "cmobject");
- private static final String[] NAMES = new String[] {"ContentManager", "ContentPublisher", "ContentContributor", "ContentReviewer"};
-
- @Override
- protected String applyInternal() throws Exception
- {
- int updateCount = 0;
- for (String permissionName : NAMES)
- {
- updateCount += super.renamePermission(
- AVMPermissionDataPatch.TYPE_QNAME_OLD,
- permissionName,
- AVMPermissionDataPatch.TYPE_QNAME_NEW,
- permissionName);
- }
-
- // build the result message
- String msg = I18NUtil.getMessage(MSG_SUCCESS, updateCount);
- // done
- return msg;
- }
-}
diff --git a/source/java/org/alfresco/repo/admin/patch/impl/AVMToADMRemoteStorePatch.java b/source/java/org/alfresco/repo/admin/patch/impl/AVMToADMRemoteStorePatch.java
deleted file mode 100644
index 1537629262..0000000000
--- a/source/java/org/alfresco/repo/admin/patch/impl/AVMToADMRemoteStorePatch.java
+++ /dev/null
@@ -1,697 +0,0 @@
-/*
- * Copyright (C) 2005-2011 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see .
- */
-package org.alfresco.repo.admin.patch.impl;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.SortedMap;
-import java.util.StringTokenizer;
-import java.util.TreeMap;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.alfresco.model.ContentModel;
-import org.alfresco.repo.admin.patch.AbstractPatch;
-import org.alfresco.repo.batch.BatchProcessWorkProvider;
-import org.alfresco.repo.batch.BatchProcessor;
-import org.alfresco.repo.batch.BatchProcessor.BatchProcessWorker;
-import org.alfresco.repo.model.filefolder.HiddenAspect;
-import org.alfresco.repo.security.authentication.AuthenticationUtil;
-import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
-import org.alfresco.service.cmr.avm.AVMNodeDescriptor;
-import org.alfresco.service.cmr.avm.AVMService;
-import org.alfresco.service.cmr.model.FileExistsException;
-import org.alfresco.service.cmr.model.FileFolderService;
-import org.alfresco.service.cmr.model.FileFolderUtil;
-import org.alfresco.service.cmr.model.FileInfo;
-import org.alfresco.service.cmr.repository.ChildAssociationRef;
-import org.alfresco.service.cmr.repository.ContentService;
-import org.alfresco.service.cmr.repository.ContentWriter;
-import org.alfresco.service.cmr.repository.DuplicateChildNodeNameException;
-import org.alfresco.service.cmr.repository.InvalidNodeRefException;
-import org.alfresco.service.cmr.repository.NodeRef;
-import org.alfresco.service.cmr.rule.RuleService;
-import org.alfresco.service.cmr.site.SiteInfo;
-import org.alfresco.service.cmr.site.SiteService;
-import org.alfresco.service.namespace.NamespaceService;
-import org.alfresco.service.namespace.QName;
-import org.alfresco.util.Pair;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.springframework.dao.ConcurrencyFailureException;
-import org.springframework.extensions.surf.util.I18NUtil;
-import org.springframework.extensions.surf.util.URLDecoder;
-
-/**
- * Patch to migrate the AVM 'sitestore' Remote Store content to the new ADM
- * location for surf-configuration under the Sites folder in 4.0.
- *
- * @see org.alfresco.repo.web.scripts.bean.ADMRemoteStore
- * @author Kevin Roast
- * @since 4.0
- */
-public class AVMToADMRemoteStorePatch extends AbstractPatch
-{
- private static final Log logger = LogFactory.getLog(AVMToADMRemoteStorePatch.class);
-
- private static final String MSG_MIGRATION_COMPLETE = "patch.avmToAdmRemoteStore.complete";
- private static final String SITE_CACHE_ID = "_SITE_CACHE";
-
- // patterns used to match site and user specific configuration locations
- // @see org.alfresco.repo.web.scripts.bean.ADMRemoteStore
- private static final Pattern USER_PATTERN_1 = Pattern.compile(".*/components/.*\\.user~(.*)~.*");
- private static final Pattern USER_PATTERN_2 = Pattern.compile(".*/pages/user/(.*?)(/.*)?$");
- private static final Pattern SITE_PATTERN_1 = Pattern.compile(".*/components/.*\\.site~(.*)~.*");
- private static final Pattern SITE_PATTERN_2 = Pattern.compile(".*/pages/site/(.*?)(/.*)?$");
- // name of the surf config folder
- private static final String SURF_CONFIG = "surf-config";
-
- private static final int SITE_BATCH_THREADS = 4;
- private static final int SITE_BATCH_SIZE = 250;
- private static final int MIGRATE_BATCH_THREADS = 4;
- private static final int MIGRATE_BATCH_SIZE = 250;
-
- private static final String SEPARATOR = "@";
-
- private Map siteReferenceCache = null;
- private SortedMap paths;
- private SortedMap retryPaths;
- private NodeRef surfConfigRef = null;
- private ThreadLocal> lastFolderCache = new ThreadLocal>()
- {
- protected Pair initialValue()
- {
- return new Pair("", null);
- };
- };
-
- private ContentService contentService;
- private FileFolderService fileFolderService;
- private SiteService siteService;
- private AVMService avmService;
- private RuleService ruleService;
- private HiddenAspect hiddenAspect;
- private String avmStore;
- private String avmRootPath = "/";
-
-
- /**
- * @param contentService the ContentService to set
- */
- public void setContentService(ContentService contentService)
- {
- this.contentService = contentService;
- }
-
- /**
- * @param fileFolderService the FileFolderService to set
- */
- public void setFileFolderService(FileFolderService fileFolderService)
- {
- this.fileFolderService = fileFolderService;
- }
-
- /**
- * @param siteService the SiteService to set
- */
- public void setSiteService(SiteService siteService)
- {
- this.siteService = siteService;
- }
-
- /**
- * @param avmService the avmService to set
- */
- public void setAvmService(AVMService avmService)
- {
- this.avmService = avmService;
- }
-
- /**
- * @param ruleService the rule service to set
- */
- public void setRuleService(RuleService ruleService)
- {
- this.ruleService = ruleService;
- }
-
- /**
- * @param avmStore the avmStore to set
- */
- public void setAvmStore(String avmStore)
- {
- this.avmStore = avmStore;
- }
-
- /**
- * @param avmRootPath the avmRootPath to set
- */
- public void setAvmRootPath(String avmRootPath)
- {
- if (avmRootPath != null && avmRootPath.length() != 0)
- {
- this.avmRootPath = avmRootPath;
- }
- }
-
- public void setHiddenAspect(HiddenAspect hiddenAspect)
- {
- this.hiddenAspect = hiddenAspect;
- }
-
- @Override
- protected void checkProperties()
- {
- super.checkProperties();
- checkPropertyNotNull(avmService, "avmService");
- checkPropertyNotNull(avmStore, "avmStore");
- }
-
- /* (non-Javadoc)
- * @see org.alfresco.repo.admin.patch.AbstractPatch#applyInternal()
- */
- @Override
- protected String applyInternal() throws Exception
- {
- this.retryPaths = new TreeMap();
-
- // get user names that will be used to RunAs and set permissions later
- final String systemUser = AuthenticationUtil.getSystemUserName();
-
- // firstly retrieve all AVM paths and descriptors that we need to process
- // execute in a single transaction to retrieve the stateless object list
- RetryingTransactionCallback work = new RetryingTransactionCallback()
- {
- public String execute() throws Exception
- {
- long start = System.currentTimeMillis();
- paths = retrieveAVMPaths();
- logger.info("Retrieved: " + paths.size() + " AVM paths in " + (System.currentTimeMillis()-start) + "ms");
-
- // also calculate the surf-config reference under the Sites folder while in the txn
- surfConfigRef = getSurfConfigNodeRef(siteService.getSiteRoot());
-
- // pre-create folders that may cause contention later during multi-threaded batch processing
- List folderPath = new ArrayList(4);
- folderPath.add("components");
- FileFolderUtil.makeFolders(fileFolderService, surfConfigRef, folderPath, ContentModel.TYPE_FOLDER);
- folderPath.clear();
- folderPath.add("pages");
- folderPath.add("user");
- FileFolderUtil.makeFolders(fileFolderService, surfConfigRef, folderPath, ContentModel.TYPE_FOLDER);
-
- // return the tenant system user name while in the txn
- return tenantAdminService.getDomainUser(systemUser, tenantAdminService.getCurrentUserDomain());
- }
- };
- final String tenantSystemUser = this.transactionHelper.doInTransaction(work, false, true);
-
- try
- {
- // init the siteid to surf-config noderef cache
- this.siteReferenceCache = new ConcurrentHashMap(16384);
-
- // build a set of unique site names
- final Set sites = new HashSet(paths.size());
- Matcher matcher;
- for (String path: paths.keySet())
- {
- String siteName = null;
- if ((matcher = SITE_PATTERN_1.matcher(path)).matches())
- {
- siteName = matcher.group(1);
- }
- else if ((matcher = SITE_PATTERN_2.matcher(path)).matches())
- {
- siteName = matcher.group(1);
- }
- if (siteName != null)
- {
- sites.add(siteName);
- }
- }
-
- // retrieve the sites for the batch work provider
- final Iterator siteItr = sites.iterator();
-
- // the work provider for the site 'surf-config' folder pre-create step
- BatchProcessWorkProvider siteWorkProvider = new BatchProcessWorkProvider()
- {
- @Override
- public synchronized Collection getNextWork()
- {
- int batchCount = 0;
-
- List siteBatch = new ArrayList(SITE_BATCH_SIZE);
- while (siteItr.hasNext() && batchCount++ != SITE_BATCH_SIZE)
- {
- siteBatch.add(siteItr.next());
- }
- return siteBatch;
- }
-
- @Override
- public synchronized int getTotalEstimatedWorkSize()
- {
- return sites.size();
- }
- };
-
- // batch process the sites in the set and pre-create the 'surf-config' folders for each site
- // add each config folder noderef to our cache ready for the config file migration processing
- BatchProcessor siteBatchProcessor = new BatchProcessor(
- "AVMToADMRemoteStorePatch",
- this.transactionHelper,
- siteWorkProvider,
- SITE_BATCH_THREADS,
- SITE_BATCH_SIZE,
- this.applicationEventPublisher,
- logger,
- SITE_BATCH_SIZE * 10);
-
- BatchProcessWorker siteWorker = new BatchProcessWorker()
- {
- @Override
- public void beforeProcess() throws Throwable
- {
- ruleService.disableRules();
- AuthenticationUtil.setRunAsUser(tenantSystemUser);
- }
-
- @Override
- public void afterProcess() throws Throwable
- {
- ruleService.enableRules();
- AuthenticationUtil.clearCurrentSecurityContext();
- }
-
- @Override
- public String getIdentifier(String entry)
- {
- return entry;
- }
-
- @Override
- public void process(String siteName) throws Throwable
- {
- // get the Site NodeRef
- SiteInfo siteInfo = AVMToADMRemoteStorePatch.this.siteService.getSite(siteName);
-
- // ALF-16256: We've actually looked up the site by case insensitive name. But there may actually be
- // paths in existence for the same site name but with different cases. We are only interested in the
- // site whose name matches EXACTLY.
- if (siteInfo != null && siteInfo.getShortName().equals(siteName))
- {
- // create the 'surf-config' folder for the site and cache the NodeRef to it
- NodeRef surfConfigRef = getSurfConfigNodeRef(siteInfo.getNodeRef());
- siteReferenceCache.put(siteName, surfConfigRef);
-
- // pre-create folders that may cause contention later during multi-threaded batch processing
- List folderPath = new ArrayList(4);
- folderPath.add("components");
- FileFolderUtil.makeFolders(fileFolderService, surfConfigRef, folderPath, ContentModel.TYPE_FOLDER);
- folderPath.clear();
- folderPath.add("pages");
- folderPath.add("site");
- FileFolderUtil.makeFolders(fileFolderService, surfConfigRef, folderPath, ContentModel.TYPE_FOLDER);
- }
- else
- {
- logger.info("WARNING: unable to find site id: " + siteName);
- }
- }
- };
- long start = System.currentTimeMillis();
- siteBatchProcessor.process(siteWorker, true);
- logger.info("Created 'surf-config' folders for: " + this.siteReferenceCache.size() + " sites in " + (System.currentTimeMillis()-start) + "ms");
-
- // retrieve AVM NodeDescriptor objects for the paths
- final Iterator pathItr = this.paths.keySet().iterator();
-
- // the work provider for the config file migration
- BatchProcessWorkProvider migrateWorkProvider = new BatchProcessWorkProvider()
- {
- @Override
- public synchronized Collection getNextWork()
- {
- int batchCount = 0;
-
- List nodes = new ArrayList(MIGRATE_BATCH_SIZE);
- while (pathItr.hasNext() && batchCount++ != MIGRATE_BATCH_SIZE)
- {
- nodes.add(paths.get(pathItr.next()));
- }
- return nodes;
- }
-
- @Override
- public synchronized int getTotalEstimatedWorkSize()
- {
- return paths.size();
- }
- };
-
- // prepare the batch processor and worker object
- BatchProcessor batchProcessor = new BatchProcessor(
- "AVMToADMRemoteStorePatch",
- this.transactionHelper,
- migrateWorkProvider,
- MIGRATE_BATCH_THREADS,
- MIGRATE_BATCH_SIZE,
- this.applicationEventPublisher,
- logger,
- MIGRATE_BATCH_SIZE * 10);
-
- BatchProcessWorker worker = new BatchProcessWorker()
- {
- @Override
- public void beforeProcess() throws Throwable
- {
- ruleService.disableRules();
- AuthenticationUtil.setRunAsUser(tenantSystemUser);
- }
-
- @Override
- public void afterProcess() throws Throwable
- {
- ruleService.enableRules();
- AuthenticationUtil.clearCurrentSecurityContext();
- }
-
- @Override
- public String getIdentifier(AVMNodeDescriptor entry)
- {
- return entry.getPath();
- }
-
- @Override
- public void process(AVMNodeDescriptor entry) throws Throwable
- {
- migrateNode(entry);
- }
- };
- batchProcessor.process(worker, true);
-
- // retry the paths that were blocked due to multiple threads attemping to create
- // the same folder at the same time - these are dealt with now in a single thread!
- if (this.retryPaths.size() != 0)
- {
- logger.info("Retrying " + this.retryPaths.size() + " paths...");
- RetryingTransactionCallback retrywork = new RetryingTransactionCallback()
- {
- public Void execute() throws Exception
- {
- for (String path : retryPaths.keySet())
- {
- migrateNode(retryPaths.get(path));
- }
- return null;
- }
- };
- this.transactionHelper.doInTransaction(retrywork, false, true);
- }
-
- logger.info("Migrated: " + this.paths.size() + " AVM nodes to DM in " + (System.currentTimeMillis()-start) + "ms");
- }
- finally
- {
- // dispose of our cache
- this.siteReferenceCache = null;
- }
-
- return I18NUtil.getMessage(MSG_MIGRATION_COMPLETE);
- }
-
- /**
- * Migrate a single AVM node. Match, convert and copy the AVM surf config path to
- * the new ADM surf-config folder location, creating appropriate sub-folders and
- * finally copying the content from the AVM to the DM.
- *
- * @param avmNode AVMNodeDescriptor
- */
- private void migrateNode(final AVMNodeDescriptor avmNode)
- {
- String path = avmNode.getPath();
-
- final boolean debug = logger.isDebugEnabled();
- // what type of path is this?
- int index = path.indexOf(this.avmRootPath);
- if (index != -1)
- {
- // crop path removing the early paths we are not interested in
- path = path.substring(index + this.avmRootPath.length());
- if (debug) logger.debug("...processing path: " + path);
-
- // break down the path into its component elements to generate the parent folders
- List pathElements = new ArrayList(4);
- final StringTokenizer t = new StringTokenizer(path, "/");
- // the remainining path is of the form /[/]/.xml
- while (t.hasMoreTokens())
- {
- pathElements.add(t.nextToken());
- }
-
- // match path against generic, user and site
- String userId = null;
- String siteName = null;
- Matcher matcher;
- if ((matcher = USER_PATTERN_1.matcher(path)).matches())
- {
- userId = URLDecoder.decode(matcher.group(1));
- }
- else if ((matcher = USER_PATTERN_2.matcher(path)).matches())
- {
- userId = URLDecoder.decode(matcher.group(1));
- }
- else if ((matcher = SITE_PATTERN_1.matcher(path)).matches())
- {
- siteName = matcher.group(1);
- }
- else if ((matcher = SITE_PATTERN_2.matcher(path)).matches())
- {
- siteName = matcher.group(1);
- }
-
- NodeRef surfConfigRef;
- if (siteName != null)
- {
- if (debug) logger.debug("...resolved site id: " + siteName);
- surfConfigRef = siteReferenceCache.get(siteName);
- if (surfConfigRef == null)
- {
- logger.info("WARNING: unable to migrate path as site id cannot be found: " + siteName);
- }
- }
- else if (userId != null)
- {
- if (debug) logger.debug("...resolved user id: " + userId);
- surfConfigRef = this.surfConfigRef;
- }
- else
- {
- if (debug) logger.debug("...resolved generic path.");
- surfConfigRef = this.surfConfigRef;
- }
-
- // ensure folders exist down to the specified parent
- List folderPath = pathElements.subList(0, pathElements.size() - 1);
- NodeRef parentFolder = null;
- Pair lastFolderCache = this.lastFolderCache.get();
- String folderKey = (siteName != null) ? siteName + folderPath.toString() : folderPath.toString();
- if (folderKey.equals(lastFolderCache.getFirst()))
- {
- // found match to last used folder NodeRef
- if (debug) logger.debug("...cache hit - matched last folder reference: " + folderKey);
- parentFolder = lastFolderCache.getSecond();
- }
- if (parentFolder == null)
- {
- try
- {
- parentFolder = FileFolderUtil.makeFolders(
- this.fileFolderService,
- surfConfigRef,
- folderPath,
- ContentModel.TYPE_FOLDER).getNodeRef();
- }
- catch (FileExistsException fe)
- {
- // this occurs if a different thread running a separate txn has created a folder
- // that we expected to exist - save a reference to this path to retry it again later
- logger.warn("Unable to create folder: " + fe.getName() + " for path: " + avmNode.getPath() +
- " - as another txn is busy, will retry later.");
- retryPaths.put(avmNode.getPath(), avmNode);
- return;
- }
- // save in last folder cache
- lastFolderCache.setFirst(folderKey);
- lastFolderCache.setSecond(parentFolder);
- }
-
- try
- {
- if (userId != null)
- {
- // run as the appropriate user id to execute
- AuthenticationUtil.pushAuthentication();
- AuthenticationUtil.setFullyAuthenticatedUser(userId);
- try
- {
- // create new node and perform writer content copy of the content from the AVM to the DM store
- FileInfo fileInfo = fileFolderService.create(
- parentFolder, avmNode.getName(), ContentModel.TYPE_CONTENT);
- Map aspectProperties = new HashMap(1, 1.0f);
- aspectProperties.put(ContentModel.PROP_IS_INDEXED, false);
- nodeService.addAspect(fileInfo.getNodeRef(), ContentModel.ASPECT_INDEX_CONTROL, aspectProperties);
- ContentWriter writer = contentService.getWriter(
- fileInfo.getNodeRef(), ContentModel.PROP_CONTENT, true);
- writer.guessMimetype(fileInfo.getName());
- writer.putContent(avmService.getContentReader(-1, avmNode.getPath()));
- }
- finally
- {
- AuthenticationUtil.popAuthentication();
- }
- }
- else
- {
- // create new node and perform writer content copy of the content from the AVM to the DM store
- FileInfo fileInfo = fileFolderService.create(
- parentFolder, avmNode.getName(), ContentModel.TYPE_CONTENT);
- Map aspectProperties = new HashMap(1, 1.0f);
- aspectProperties.put(ContentModel.PROP_IS_INDEXED, false);
- nodeService.addAspect(fileInfo.getNodeRef(), ContentModel.ASPECT_INDEX_CONTROL, aspectProperties);
- ContentWriter writer = contentService.getWriter(
- fileInfo.getNodeRef(), ContentModel.PROP_CONTENT, true);
- writer.guessMimetype(fileInfo.getName());
- writer.putContent(avmService.getContentReader(-1, avmNode.getPath()));
- }
- }
- catch (InvalidNodeRefException refErr)
- {
- // this occurs if a different thread running a separate txn has not yet created a folder
- // that we expected to exist - save a reference to this path to retry it again later
- logger.warn("Parent folder does not exist yet: " + refErr.getNodeRef() + " for path: " + avmNode.getPath() +
- " - as another txn is busy, will retry later.");
- retryPaths.put(avmNode.getPath(), avmNode);
- }
- }
- }
-
- /**
- * Return the "surf-config" noderef under the given root. Create the folder if it
- * does not exist yet.
- *
- * @param rootRef Parent node reference where the "surf-config" folder should be
- *
- * @return surf-config folder ref
- */
- private NodeRef getSurfConfigNodeRef(final NodeRef rootRef)
- {
- NodeRef surfConfigRef = this.nodeService.getChildByName(
- rootRef, ContentModel.ASSOC_CONTAINS, SURF_CONFIG);
- if (surfConfigRef == null)
- {
- if (logger.isDebugEnabled())
- logger.debug("'surf-config' folder not found under current path, creating...");
- QName assocQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, SURF_CONFIG);
- Map properties = new HashMap(1, 1.0f);
- properties.put(ContentModel.PROP_NAME, (Serializable) SURF_CONFIG);
- try
- {
- ChildAssociationRef ref = this.nodeService.createNode(
- rootRef, ContentModel.ASSOC_CONTAINS, assocQName, ContentModel.TYPE_FOLDER, properties);
- surfConfigRef = ref.getChildRef();
-
- // surf-config needs to be hidden - applies index control aspect as part of the hidden aspect
- hiddenAspect.hideNode(ref.getChildRef(), false, false, false);
- }
- catch (DuplicateChildNodeNameException dupErr)
- {
- // This exception is excepted in multi-threaded creation scenarios - but since fix for
- // ALF-10280 rev 30468 - it no longer automatically retries in the txn - therefore we
- // throw out an exception that does retry instead.
- throw new ConcurrencyFailureException("Forcing batch retry due to DuplicateChildNodeNameException" , dupErr);
- }
- }
- return surfConfigRef;
- }
-
- /**
- * @return the AVM paths for surf config object in the AVM sitestore
- */
- private SortedMap retrieveAVMPaths() throws Exception
- {
- logger.info("Retrieving paths from AVM store: " + this.avmStore + ":" + this.avmRootPath);
-
- SortedMap paths = new TreeMap();
-
- String avmPath;
- if (this.tenantAdminService.getCurrentUserDomain().isEmpty())
- {
- avmPath = this.avmStore + ":" + this.avmRootPath;
- }
- else
- {
- avmPath = SEPARATOR + this.tenantAdminService.getCurrentUserDomain() + SEPARATOR + this.avmStore + ":" + this.avmRootPath;
- }
-
- AVMNodeDescriptor node = this.avmService.lookup(-1, avmPath);
- if (node != null)
- {
- traverseNode(paths, node);
- }
-
- logger.info("Found: " + paths.size() + " AVM files nodes to migrate");
-
- return paths;
- }
-
- private void traverseNode(final SortedMap paths, final AVMNodeDescriptor node)
- throws IOException
- {
- final boolean debug = logger.isDebugEnabled();
- final SortedMap listing = this.avmService.getDirectoryListing(node);
- for (final AVMNodeDescriptor n : listing.values())
- {
- if (n.isFile())
- {
- if (debug) logger.debug("...adding path: " + n.getPath());
- paths.put(n.getPath(), n);
- if (paths.size() % 10000 == 0)
- {
- logger.info("Collected " + paths.size() + " AVM paths...");
- }
- }
- else if (n.isDirectory())
- {
- traverseNode(paths, n);
- }
- }
- }
-}
diff --git a/source/java/org/alfresco/repo/admin/patch/impl/AVMWebProjectInheritPermissionsPatch.java b/source/java/org/alfresco/repo/admin/patch/impl/AVMWebProjectInheritPermissionsPatch.java
deleted file mode 100644
index 00ce065b76..0000000000
--- a/source/java/org/alfresco/repo/admin/patch/impl/AVMWebProjectInheritPermissionsPatch.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see .
- */
-package org.alfresco.repo.admin.patch.impl;
-
-import java.util.List;
-
-import org.alfresco.model.WCMAppModel;
-import org.alfresco.repo.admin.patch.AbstractPatch;
-import org.alfresco.repo.importer.ImporterBootstrap;
-import org.alfresco.service.cmr.repository.ChildAssociationRef;
-import org.alfresco.service.cmr.repository.NodeRef;
-import org.alfresco.service.cmr.search.ResultSet;
-import org.alfresco.service.cmr.search.ResultSetRow;
-import org.alfresco.service.cmr.search.SearchParameters;
-import org.alfresco.service.cmr.search.SearchService;
-import org.alfresco.service.cmr.security.PermissionService;
-import org.alfresco.service.namespace.RegexQNamePattern;
-import org.springframework.extensions.surf.util.I18NUtil;
-
-/**
- * Patch to break the inheritance of permissions on AVM Web Project Folders.
- * This removes the need for admins to write a script or similar to by default hide web folders
- * to all users except those explicitly invited (given permissions) to the project.
- *
- * @author Kevin Roast
- */
-public class AVMWebProjectInheritPermissionsPatch extends AbstractPatch
-{
- private static final String MSG_SUCCESS = "patch.avmWebProjectInheritPermissions.result";
-
- private ImporterBootstrap spacesImporterBootstrap;
- private PermissionService permissionService;
-
- public void setSpacesImporterBootstrap(ImporterBootstrap spacesImporterBootstrap)
- {
- this.spacesImporterBootstrap = spacesImporterBootstrap;
- }
-
- public void setPermissionService(PermissionService permissionService)
- {
- this.permissionService = permissionService;
- }
-
- /* (non-Javadoc)
- * @see org.alfresco.repo.admin.patch.AbstractPatch#applyInternal()
- */
- @Override
- protected String applyInternal() throws Exception
- {
- SearchParameters sp = new SearchParameters();
- sp.setLanguage(SearchService.LANGUAGE_LUCENE);
- sp.setQuery("TYPE:\"wca:webfolder\"");
- sp.addStore(spacesImporterBootstrap.getStoreRef());
- ResultSet rs = null;
- try
- {
- rs = searchService.query(sp);
- for (ResultSetRow row : rs)
- {
- // break permission inheritance for the Web Project nodes
- this.permissionService.setInheritParentPermissions(row.getNodeRef(), false);
-
- // ensure that permissions are explicitly assigned for all Content Manager roles
- List userInfoRefs = this.nodeService.getChildAssocs(
- row.getNodeRef(), WCMAppModel.ASSOC_WEBUSER, RegexQNamePattern.MATCH_ALL);
- for (ChildAssociationRef ref : userInfoRefs)
- {
- NodeRef userInfoRef = ref.getChildRef();
- String username = (String)nodeService.getProperty(userInfoRef, WCMAppModel.PROP_WEBUSERNAME);
- String userrole = (String)nodeService.getProperty(userInfoRef, WCMAppModel.PROP_WEBUSERROLE);
-
- if ("ContentManager".equals(userrole))
- {
- this.permissionService.setPermission(row.getNodeRef(), username, "ContentManager", true);
- }
- }
- }
- }
- finally
- {
- if (rs != null)
- {
- rs.close();
- }
- }
-
- return I18NUtil.getMessage(MSG_SUCCESS);
- }
-}
diff --git a/source/java/org/alfresco/repo/admin/patch/impl/AuthorityDefaultZonesPatch.java b/source/java/org/alfresco/repo/admin/patch/impl/AuthorityDefaultZonesPatch.java
index 33134be336..1ed0ac13bd 100644
--- a/source/java/org/alfresco/repo/admin/patch/impl/AuthorityDefaultZonesPatch.java
+++ b/source/java/org/alfresco/repo/admin/patch/impl/AuthorityDefaultZonesPatch.java
@@ -25,8 +25,6 @@ import java.util.Set;
import org.alfresco.repo.admin.patch.AbstractPatch;
import org.alfresco.repo.admin.patch.PatchExecuter;
-import org.alfresco.service.cmr.avm.AVMService;
-import org.alfresco.service.cmr.avm.AVMStoreDescriptor;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.service.cmr.site.SiteInfo;
@@ -50,7 +48,6 @@ public class AuthorityDefaultZonesPatch extends AbstractPatch
/** The authority service. */
private AuthorityService authorityService;
- private AVMService avmService;
private SiteService siteService;
/**
@@ -64,18 +61,8 @@ public class AuthorityDefaultZonesPatch extends AbstractPatch
this.authorityService = authorityService;
}
- /**
- * Set the avm service
- * @param avmService
- */
- public void setAvmService(AVMService avmService)
- {
- this.avmService = avmService;
- }
-
/**
* Set the site service
- * @param siteService
*/
public void setSiteService(SiteService siteService)
{
@@ -126,17 +113,9 @@ public class AuthorityDefaultZonesPatch extends AbstractPatch
shareZones.add(AuthorityService.ZONE_APP_SHARE);
shareZones.add(AuthorityService.ZONE_AUTH_ALFRESCO);
- List stores = avmService.getStores();
List sites = siteService.listSites(null, null);
- List groupActions = new ArrayList(stores.size() * 4 + sites.size() * 5 + 1);
- for (AVMStoreDescriptor store : stores)
- {
- groupActions.add(new Action("GROUP_"+store.getName()+"-ContentManager", wcmZones, ActionType.SET));
- groupActions.add(new Action("GROUP_"+store.getName()+"-ContentPublisher", wcmZones, ActionType.SET));
- groupActions.add(new Action("GROUP_"+store.getName()+"-ContentContributor", wcmZones, ActionType.SET));
- groupActions.add(new Action("GROUP_"+store.getName()+"-ContentReviewer", wcmZones, ActionType.SET));
- }
+ List groupActions = new ArrayList(sites.size() * 5 + 1);
for (SiteInfo site : sites)
{
groupActions.add(new Action("GROUP_site_" + site.getShortName(), shareZones, ActionType.SET));
diff --git a/source/java/org/alfresco/repo/admin/patch/impl/MigrateAttrAVMLocksPatch.java b/source/java/org/alfresco/repo/admin/patch/impl/MigrateAttrAVMLocksPatch.java
deleted file mode 100644
index 890c36b16e..0000000000
--- a/source/java/org/alfresco/repo/admin/patch/impl/MigrateAttrAVMLocksPatch.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see .
- */
-package org.alfresco.repo.admin.patch.impl;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.alfresco.repo.admin.patch.AbstractPatch;
-import org.alfresco.repo.avm.locking.AVMLockingServiceImpl;
-import org.alfresco.repo.domain.patch.PatchDAO;
-import org.alfresco.service.cmr.attributes.AttributeService;
-import org.alfresco.wcm.util.WCMUtil;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.ibatis.session.ResultContext;
-import org.apache.ibatis.session.ResultHandler;
-import org.springframework.extensions.surf.util.I18NUtil;
-
-/**
- * Migrate AVM lock attributes (from 'alf_*attribute*' to 'alf_prop_*')
- *
- * @author janv
- * @since 3.4
- */
-public class MigrateAttrAVMLocksPatch extends AbstractPatch
-{
- private Log logger = LogFactory.getLog(this.getClass());
-
- private static final String MSG_SUCCESS = "patch.migrateAttrAVMLocks.result";
-
- private AttributeService attributeService;
- private PatchDAO patchDAO;
-
- public void setAttributeService(AttributeService attributeService)
- {
- this.attributeService = attributeService;
- }
-
- public void setPatchDAO(PatchDAO patchDAO)
- {
- this.patchDAO = patchDAO;
- }
-
- @Override
- protected String applyInternal() throws Exception
- {
- long startTime = System.currentTimeMillis();
-
- AVMLockResultHandler handler = new AVMLockResultHandler();
- patchDAO.migrateOldAttrAVMLocks(handler);
-
- if (handler.total > 0)
- {
- logger.info("Processed "+handler.total+" AVM Lock attrs in "+(System.currentTimeMillis()-startTime)/1000+" secs");
- }
-
- // build the result message
- String msg = I18NUtil.getMessage(MSG_SUCCESS, handler.total);
- // done
- return msg;
- }
-
- /**
- * Row handler for migrating AVM Locks
- */
- private class AVMLockResultHandler implements ResultHandler
- {
- private int total = 0;
-
- private AVMLockResultHandler()
- {
- }
- @SuppressWarnings("unchecked")
- public void handleResult(ResultContext context)
- {
- Map result = (Map)context.getResultObject();
-
- String wpStoreId = (String)result.get("wpStoreId");
- String path = (String)result.get("relPath");
- String avmStore = (String)result.get("avmStore");
- String lockOwner = (String)result.get("owner1");
-
- String relPath = AVMLockingServiceImpl.normalizePath(path);
-
- HashMap lockData = new HashMap(2);
- lockData.put(AVMLockingServiceImpl.KEY_LOCK_OWNER, lockOwner);
- lockData.put(WCMUtil.LOCK_KEY_STORE_NAME, avmStore);
-
- if (!attributeService.exists(AVMLockingServiceImpl.KEY_AVM_LOCKS, wpStoreId, relPath))
- {
- attributeService.createAttribute(lockData, AVMLockingServiceImpl.KEY_AVM_LOCKS, wpStoreId, relPath);
- if (logger.isTraceEnabled())
- {
- logger.trace("Set AVM Lock attr [wpStoreId=" + wpStoreId + ", relPath=" + relPath + ", lockOwner=" + lockOwner + ", avmStore=" + avmStore + "]");
- }
- total++;
- }
- else
- {
- logger.warn("'" + path + "' path has duplicates in normalized form. AVM lock unique attribute creation has been skipped");
- }
-
- if (logger.isDebugEnabled() && (total == 0 || (total % 1000 == 0) ))
- {
- logger.debug(" Handled " + total + " AVM Lock attributes");
- }
- }
- }
-}
diff --git a/source/java/org/alfresco/repo/admin/patch/impl/MultiTShareExistingTenantsPatch.java b/source/java/org/alfresco/repo/admin/patch/impl/MultiTShareExistingTenantsPatch.java
index 00a20ccf95..e325a927cc 100644
--- a/source/java/org/alfresco/repo/admin/patch/impl/MultiTShareExistingTenantsPatch.java
+++ b/source/java/org/alfresco/repo/admin/patch/impl/MultiTShareExistingTenantsPatch.java
@@ -23,7 +23,6 @@ import java.util.Properties;
import org.springframework.extensions.surf.util.I18NUtil;
import org.alfresco.repo.admin.patch.AbstractPatch;
-import org.alfresco.repo.site.SiteAVMBootstrap;
import org.alfresco.repo.tenant.TenantService;
import org.alfresco.repo.workflow.WorkflowDeployer;
diff --git a/source/java/org/alfresco/repo/avm/AVMCrawler.java b/source/java/org/alfresco/repo/avm/AVMCrawler.java
deleted file mode 100644
index 9978f1f70b..0000000000
--- a/source/java/org/alfresco/repo/avm/AVMCrawler.java
+++ /dev/null
@@ -1,329 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-
-package org.alfresco.repo.avm;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.InputStreamReader;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-
-import net.sf.acegisecurity.Authentication;
-
-import org.alfresco.repo.security.authentication.AuthenticationUtil;
-import org.alfresco.service.cmr.avm.AVMException;
-import org.alfresco.service.cmr.avm.AVMNodeDescriptor;
-import org.alfresco.service.cmr.avm.AVMNotFoundException;
-import org.alfresco.service.cmr.avm.AVMService;
-import org.alfresco.service.cmr.avm.AVMStoreDescriptor;
-import org.alfresco.service.cmr.repository.ContentIOException;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.springframework.dao.ConcurrencyFailureException;
-
-
-/**
- * This is another tester designed to emulate more typical use patterns.
- * @author britt
- */
-class AVMCrawler implements Runnable
-{
- private static Log logger = LogFactory.getLog(AVMCrawler.class);
-
- /**
- * The AVMService to use.
- */
- private AVMService fService;
-
- private Authentication authentication;
-
- /**
- * The Operation count.
- */
- private int fOpCount;
-
- /**
- * Whether we are done.
- */
- private boolean fDone;
-
- /**
- * Whether an error has occurred.
- */
- private boolean fError;
- private String fErrorStackTrace = null;
-
- /**
- * Random number generator.
- */
- private Random fRandom;
-
- /**
- * Make up a new one.
- * @param service The AVMService.
- */
- public AVMCrawler(AVMService service, Authentication authentication)
- {
- fService = service;
- this.authentication = authentication;
- fOpCount = 0;
- fDone = false;
- fError = false;
- fRandom = new Random();
- }
-
- /**
- * Tell this thread it is done.
- */
- public void setDone()
- {
- fDone = true;
- }
-
- /**
- * Is this thread in an error state.
- */
- public boolean getError()
- {
- return fError;
- }
-
- /**
- * Get error stack trace
- */
- public String getErrorStackTrace()
- {
- return fErrorStackTrace;
- }
-
- /**
- * Implementation of run.
- */
- public void run()
- {
- try
- {
- AuthenticationUtil.setFullAuthentication(authentication);
- while (!fDone)
- {
- doCrawl();
- }
- }
- catch (Throwable t)
- {
- t.printStackTrace();
-
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- t.printStackTrace(pw);
-
- fError = true;
- fErrorStackTrace = sw.toString();
- }
- finally
- {
- AuthenticationUtil.clearCurrentSecurityContext();
- }
- }
-
- /**
- * Do one crawl.
- */
- public void doCrawl()
- {
- try
- {
- List reps = fService.getStores();
- fOpCount++;
-
- if (reps.size() == 0)
- {
- logger.warn("No AVM stores");
- return;
- }
-
- AVMStoreDescriptor repDesc = reps.get(fRandom.nextInt(reps.size()));
- Map rootListing = fService.getDirectoryListing(-1, repDesc.getName() + ":/");
- fOpCount++;
- // Get all the directories in the root.
- List dirs = new ArrayList();
- for (AVMNodeDescriptor desc : rootListing.values())
- {
- if (desc.isDirectory())
- {
- dirs.add(desc);
- }
- }
-
- if (dirs.size() == 0)
- {
- logger.warn("No dirs in root: "+repDesc.getName() + ":/");
- }
- else
- {
- AVMNodeDescriptor dir = dirs.get(fRandom.nextInt(dirs.size()));
- int depth = 1;
- while (dir != null)
- {
- Map listing = fService.getDirectoryListing(-1, dir.getPath());
- fOpCount++;
- List files = new ArrayList();
- dirs = new ArrayList();
- for (AVMNodeDescriptor desc : listing.values())
- {
- if (desc.isDirectory())
- {
- dirs.add(desc);
- }
- else
- {
- files.add(desc);
- }
- }
- // Read some files if there are any.
- if (files.size() > 0)
- {
- for (int i = 0; i < 6; i++)
- {
- String path = files.get(fRandom.nextInt(files.size())).getPath();
- logger.info("Reading: " + path);
- BufferedReader
- reader = new BufferedReader
- (new InputStreamReader
- (fService.getFileInputStream(-1, path)));
- fOpCount++;
- String line = reader.readLine();
- if (logger.isDebugEnabled())
- {
- logger.debug(line);
- }
- reader.close();
- }
- // Modify some files.
- for (int i = 0; i < 2; i++)
- {
- String path = files.get(fRandom.nextInt(files.size())).getPath();
- logger.info("Modifying: " + path);
- PrintStream out = new PrintStream(fService.getFileOutputStream(path));
- out.println("I am " + path);
- out.close();
- fOpCount++;
- }
- }
- if (fRandom.nextInt(depth) < depth - 1)
- {
- // Create some files.
- for (int i = 0; i < 1; i++)
- {
- String name = randomName();
- if (listing.containsKey(name))
- {
- break;
- }
- logger.info("Creating File: " + name);
- fService.createFile(dir.getPath(), name,
- new ByteArrayInputStream(("I am " + name).getBytes()));
- fOpCount++;
- }
- }
- // 1 in 100 times create a directory.
- if (fRandom.nextInt(100) == 0)
- {
- String name = randomName();
- if (listing.containsKey(name))
- {
- break;
- }
- logger.info("Creating Directory: " + name);
- fService.createDirectory(dir.getPath(), name);
- fOpCount++;
- }
- if (listing.size() > 0)
- {
- // 1 in 100 times remove something
- if (fRandom.nextInt(100) == 0)
- {
- List names = new ArrayList(listing.keySet());
- String name = names.get(fRandom.nextInt(names.size()));
- logger.info("Removing: " + name);
- fService.removeNode(dir.getPath(),
- name);
- fOpCount++;
- }
- }
- if (dirs.size() > 0)
- {
- dir = dirs.get(fRandom.nextInt(dirs.size()));
- }
- else
- {
- dir = null;
- }
- depth++;
- }
- }
-
- if (fRandom.nextInt(16) == 0)
- {
- logger.info("Snapshotting: " + repDesc.getName());
- fService.createSnapshot(repDesc.getName(), null, null);
- fOpCount++;
- }
- }
- catch (Exception e)
- {
- if ((e instanceof AVMNotFoundException) ||
- (e instanceof AVMException) ||
- (e instanceof ContentIOException) ||
- (e instanceof ConcurrencyFailureException))
- {
- logger.warn(e.getMessage());
- return;
- }
-
- e.printStackTrace(System.err);
- throw new AVMException("Failure", e);
- }
- }
-
- /**
- * Get a random two character string.
- * @return A random name.
- */
- private String randomName()
- {
- char [] chars = new char[2];
- chars[0] = (char)('a' + fRandom.nextInt(12));
- chars[1] = (char)('a' + fRandom.nextInt(12));
- return new String(chars);
- }
-
- /**
- * Get the operation count.
- */
- public int getOpCount()
- {
- return fOpCount;
- }
-}
diff --git a/source/java/org/alfresco/repo/avm/AVMDeploymentAttemptCleaner.java b/source/java/org/alfresco/repo/avm/AVMDeploymentAttemptCleaner.java
deleted file mode 100644
index 86ef55c6bc..0000000000
--- a/source/java/org/alfresco/repo/avm/AVMDeploymentAttemptCleaner.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see .
- */
-package org.alfresco.repo.avm;
-
-import java.util.Calendar;
-import java.util.Date;
-
-import org.alfresco.model.WCMAppModel;
-import org.alfresco.repo.importer.ImporterBootstrap;
-import org.alfresco.repo.security.authentication.AuthenticationUtil;
-import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
-import org.alfresco.service.cmr.repository.NodeRef;
-import org.alfresco.service.cmr.repository.NodeService;
-import org.alfresco.service.cmr.search.ResultSet;
-import org.alfresco.service.cmr.search.SearchService;
-import org.alfresco.service.namespace.NamespaceService;
-import org.alfresco.service.transaction.TransactionService;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * Bean that is responsible for locating expired content and routing
- * it for review to the most relevant user.
- *
- * @author gavinc
- */
-public class AVMDeploymentAttemptCleaner
-{
- // defaults in case these properties are not configured in Spring
- protected long maxAge = 180L;
-
- protected NodeService nodeService;
- protected TransactionService transactionService;
- protected SearchService searchService;
- protected ImporterBootstrap importerBootstrap;
-
- private static Log logger = LogFactory.getLog(AVMDeploymentAttemptCleaner.class);
-
- public AVMDeploymentAttemptCleaner()
- {
- }
-
- public void setMaxAge(long maxAge)
- {
- this.maxAge = new Long(maxAge);
- }
-
- public void setNodeService(NodeService nodeService)
- {
- this.nodeService = nodeService;
- }
-
- public void setTransactionService(TransactionService transactionService)
- {
- this.transactionService = transactionService;
- }
-
- public void setSearchService(SearchService searchService)
- {
- this.searchService = searchService;
- }
-
- public void setImporterBootstrap(ImporterBootstrap importerBootstrap)
- {
- this.importerBootstrap = importerBootstrap;
- }
-
- /**
- * Executes the expired content processor.
- * The work is performed within a transaction running as the system user.
- */
- public void execute()
- {
- // setup a wrapper object to run the processor within a transaction.
- AuthenticationUtil.RunAsWork authorisedWork = new AuthenticationUtil.RunAsWork()
- {
- public String doWork() throws Exception
- {
- RetryingTransactionCallback expiredContentWork = new RetryingTransactionCallback()
- {
- public String execute() throws Exception
- {
- cleanAttempts();
- return null;
- }
- };
- return transactionService.getRetryingTransactionHelper().doInTransaction(expiredContentWork);
- }
- };
-
- // perform the work as the system user
- AuthenticationUtil.runAs(authorisedWork, AuthenticationUtil.getAdminUserName());
- }
-
- /**
- * Entry point.
- */
- private void cleanAttempts()
- {
- // calculate the date 'maxAge' days before today
- long daysInMs = 1000L*60L*60L*24L*this.maxAge;
- Date toDate = new Date(new Date().getTime() - daysInMs);
-
- // build the query to find deployment attempts older than this.maxAge
- Calendar cal = Calendar.getInstance();
- cal.setTime(toDate);
- StringBuilder query = new StringBuilder("@");
- query.append(NamespaceService.WCMAPP_MODEL_PREFIX);
- query.append("\\:");
- query.append(WCMAppModel.PROP_DEPLOYATTEMPTTIME.getLocalName());
- query.append(":[0001\\-01\\-01T00:00:00 TO ");
- query.append(cal.get(Calendar.YEAR));
- query.append("\\-");
- query.append((cal.get(Calendar.MONTH)+1));
- query.append("\\-");
- query.append(cal.get(Calendar.DAY_OF_MONTH));
- query.append("T00:00:00]");
-
- if (logger.isDebugEnabled())
- logger.debug("Finding old deploymentattempt nodes using query: " + query.toString());
-
- // do the query
- ResultSet results = null;
- try
- {
- // execute the query
- results = searchService.query(this.importerBootstrap.getStoreRef(),
- SearchService.LANGUAGE_LUCENE, query.toString());
-
- if (logger.isDebugEnabled())
- logger.debug("Deleting " + results.length() + " old deployment attempts");
-
- // iterate through the attempt nodes and delete them
- for (NodeRef attempt : results.getNodeRefs())
- {
- this.nodeService.deleteNode(attempt);
-
- if (logger.isDebugEnabled())
- logger.debug("Deleted deployment attempt: " + attempt);
- }
- }
- finally
- {
- if (results != null)
- {
- results.close();
- }
- }
- }
-}
diff --git a/source/java/org/alfresco/repo/avm/AVMDeploymentAttemptCleanerJob.java b/source/java/org/alfresco/repo/avm/AVMDeploymentAttemptCleanerJob.java
deleted file mode 100644
index 8281760a9f..0000000000
--- a/source/java/org/alfresco/repo/avm/AVMDeploymentAttemptCleanerJob.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see .
- */
-package org.alfresco.repo.avm;
-
-import org.quartz.Job;
-import org.quartz.JobExecutionContext;
-import org.quartz.JobExecutionException;
-
-/**
- * Job to periodically execute the deployment attempt cleaner.
- *
- *
- * The following parameters are required:
- *
- * - deploymentAttemptCleaner: The deployment attempt cleaner instance
- *
- *
- * @author gavinc
- */
-public class AVMDeploymentAttemptCleanerJob implements Job
-{
- /**
- * Searches for old deployment attempts and removes them.
- *
- * @param context The job context
- */
- public void execute(JobExecutionContext context) throws JobExecutionException
- {
- // get the expired content processor bean from the job context
- AVMDeploymentAttemptCleaner cleaner =
- (AVMDeploymentAttemptCleaner)context.getJobDetail().getJobDataMap().get("deploymentAttemptCleaner");
- if (cleaner == null)
- {
- throw new JobExecutionException("Missing job data: deploymentAttemptCleaner");
- }
-
- // execute the cleaner to do the actual work
- cleaner.execute();
- }
-}
diff --git a/source/java/org/alfresco/repo/avm/AVMExpiredContentJob.java b/source/java/org/alfresco/repo/avm/AVMExpiredContentJob.java
deleted file mode 100644
index 6d68137aba..0000000000
--- a/source/java/org/alfresco/repo/avm/AVMExpiredContentJob.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see .
- */
-package org.alfresco.repo.avm;
-
-import org.quartz.Job;
-import org.quartz.JobExecutionContext;
-import org.quartz.JobExecutionException;
-
-/**
- * Job to periodically execute the expired content processor.
- *
- *
- * The following parameters are required:
- *
- * - expiredContent: The expired content processor instance
- *
- *
- * @author gavinc
- */
-public class AVMExpiredContentJob implements Job
-{
- /**
- * Searches for expired content in web project's staging area and
- * prompt the last modifier of the content to review it.
- *
- * @param context The job context
- */
- public void execute(JobExecutionContext context) throws JobExecutionException
- {
- // get the expired content processor bean from the job context
- AVMExpiredContentProcessor expiredContentProcessor =
- (AVMExpiredContentProcessor)context.getJobDetail().getJobDataMap().get("expiredContentProcessor");
- if (expiredContentProcessor == null)
- {
- throw new JobExecutionException("Missing job data: expiredContentProcessor");
- }
-
- // execute the processor to do the actual work
- expiredContentProcessor.execute();
- }
-}
diff --git a/source/java/org/alfresco/repo/avm/AVMExpiredContentProcessor.java b/source/java/org/alfresco/repo/avm/AVMExpiredContentProcessor.java
deleted file mode 100644
index 77edbb402c..0000000000
--- a/source/java/org/alfresco/repo/avm/AVMExpiredContentProcessor.java
+++ /dev/null
@@ -1,492 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see .
- */
-package org.alfresco.repo.avm;
-
-import java.io.Serializable;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.alfresco.config.JNDIConstants;
-import org.alfresco.mbeans.VirtServerRegistry;
-import org.alfresco.model.ContentModel;
-import org.alfresco.model.WCMAppModel;
-import org.alfresco.repo.domain.PropertyValue;
-import org.alfresco.repo.security.authentication.AuthenticationUtil;
-import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
-import org.alfresco.repo.workflow.WorkflowModel;
-import org.alfresco.service.cmr.avm.AVMNodeDescriptor;
-import org.alfresco.service.cmr.avm.AVMService;
-import org.alfresco.service.cmr.avm.AVMStoreDescriptor;
-import org.alfresco.service.cmr.avm.locking.AVMLockingService;
-import org.alfresco.service.cmr.avmsync.AVMSyncService;
-import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
-import org.alfresco.service.cmr.repository.NodeRef;
-import org.alfresco.service.cmr.repository.NodeService;
-import org.alfresco.service.cmr.repository.StoreRef;
-import org.alfresco.service.cmr.search.ResultSet;
-import org.alfresco.service.cmr.search.SearchService;
-import org.alfresco.service.cmr.security.PermissionService;
-import org.alfresco.service.cmr.security.PersonService;
-import org.alfresco.service.cmr.workflow.WorkflowDefinition;
-import org.alfresco.service.cmr.workflow.WorkflowPath;
-import org.alfresco.service.cmr.workflow.WorkflowService;
-import org.alfresco.service.cmr.workflow.WorkflowTask;
-import org.alfresco.service.cmr.workflow.WorkflowTaskState;
-import org.alfresco.service.namespace.QName;
-import org.alfresco.service.transaction.TransactionService;
-import org.alfresco.util.Pair;
-import org.alfresco.wcm.sandbox.SandboxConstants;
-import org.alfresco.wcm.sandbox.SandboxFactory;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.springframework.extensions.surf.util.I18NUtil;
-
-/**
- * Bean that is responsible for locating expired content and routing
- * it for review to the most relevant user.
- *
- * @author gavinc
- */
-public class AVMExpiredContentProcessor
-{
- // defaults in case these properties are not configured in Spring
- protected String workflowName = "jbpm$wcmwf:changerequest";
-
- protected List workflowStores;
- protected Map>> expiredContent;
- protected AVMService avmService;
- protected AVMSyncService avmSyncService;
- protected AVMService avmLockingAwareService;
- protected AVMLockingService avmLockingService;
- protected NodeService nodeService;
- protected WorkflowService workflowService;
- protected PersonService personService;
- protected PermissionService permissionService;
- protected TransactionService transactionService;
- protected VirtServerRegistry virtServerRegistry;
- protected SearchService searchService;
- private SandboxFactory sandboxFactory;
-
- private static Log logger = LogFactory.getLog(AVMExpiredContentProcessor.class);
-
- private static final String STORE_SEPARATOR = "--";
- private final static Pattern STORE_RELATIVE_PATH_PATTERN = Pattern.compile("[^:]+:(.+)");
-
- public AVMExpiredContentProcessor()
- {
- }
-
- public void setAdminUserName(String adminUserName)
- {
- // NOTE: ignore, just for backwards compatible Spring config
- }
-
- public void setWorkflowName(String workflowName)
- {
- this.workflowName = workflowName;
- }
-
- public void setAvmService(AVMService avmService)
- {
- this.avmService = avmService;
- }
-
- public void setAvmLockingService(AVMLockingService avmLockingService)
- {
- this.avmLockingService = avmLockingService;
- }
-
- public void setAvmSyncService(AVMSyncService avmSyncService)
- {
- this.avmSyncService = avmSyncService;
- }
-
- public void setNodeService(NodeService nodeService)
- {
- this.nodeService = nodeService;
- }
-
- public void setPermissionService(PermissionService permissionService)
- {
- this.permissionService = permissionService;
- }
-
- public void setPersonService(PersonService personService)
- {
- this.personService = personService;
- }
-
- public void setWorkflowService(WorkflowService workflowService)
- {
- this.workflowService = workflowService;
- }
-
- public void setTransactionService(TransactionService transactionService)
- {
- this.transactionService = transactionService;
- }
-
- public void setVirtServerRegistry(VirtServerRegistry virtServerRegistry)
- {
- this.virtServerRegistry = virtServerRegistry;
- }
-
- public void setSearchService(SearchService searchService)
- {
- this.searchService = searchService;
- }
-
- public void setAvmLockingAwareService(AVMService avmLockingAwareService)
- {
- this.avmLockingAwareService = avmLockingAwareService;
- }
-
- public void setSandboxFactory(SandboxFactory sandboxFactory)
- {
- this.sandboxFactory = sandboxFactory;
- }
-
- /**
- * Executes the expired content processor.
- * The work is performed within a transaction running as the system user.
- */
- public void execute()
- {
- // setup a wrapper object to run the processor within a transaction.
- AuthenticationUtil.RunAsWork authorisedWork = new AuthenticationUtil.RunAsWork()
- {
- public String doWork() throws Exception
- {
- RetryingTransactionCallback expiredContentWork = new RetryingTransactionCallback()
- {
- public String execute() throws Exception
- {
- processExpiredContent();
- return null;
- }
- };
- return transactionService.getRetryingTransactionHelper().doInTransaction(expiredContentWork);
- }
- };
-
- // perform the work as the system user
- AuthenticationUtil.runAs(authorisedWork, AuthenticationUtil.getAdminUserName());
-
- // now we know everything worked ok, let the virtualisation server
- // know about all the new workflow sandboxes created (just the main stores)
- for (String path : this.workflowStores)
- {
- this.virtServerRegistry.updateAllWebapps(-1, path, true);
- }
- }
-
- /**
- * Entry point.
- */
- private void processExpiredContent()
- {
- // create the maps to hold the expired content for each user in each web project
- this.expiredContent = new HashMap>>(8);
- this.workflowStores = new ArrayList(4);
-
- // iterate through all AVM stores and focus only on staging main stores
- List stores = avmService.getStores();
- if (logger.isDebugEnabled())
- logger.debug("Checking " + stores.size() + " AVM stores...");
-
- for (AVMStoreDescriptor storeDesc : stores)
- {
- String storeName = storeDesc.getName();
- PropertyValue val = avmService.getStoreProperty(storeName, SandboxConstants.PROP_SANDBOX_STAGING_MAIN);
-
- if (val != null)
- {
- if (logger.isDebugEnabled())
- logger.debug("Searching store '" + storeName + "' for expired content...");
-
- // find ant nodes with an expiration *date* of today or before
- Calendar cal = Calendar.getInstance();
- StringBuilder query = new StringBuilder("@wca\\:expirationDate:[0001\\-01\\-01T00:00:00 TO ");
- query.append(cal.get(Calendar.YEAR));
- query.append("\\-");
- query.append((cal.get(Calendar.MONTH)+1));
- query.append("\\-");
- query.append(cal.get(Calendar.DAY_OF_MONTH));
- query.append("T00:00:00]");
-
- // do the query
- StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_AVM, storeName);
- ResultSet results = this.searchService.query(storeRef, SearchService.LANGUAGE_LUCENE,
- query.toString());
- try
- {
- if (logger.isDebugEnabled())
- logger.debug("Found " + results.length() + " potential expired item(s) in store '" + storeName + "'");
-
- if (results.length() > 0)
- {
- for (NodeRef resultNode : results.getNodeRefs())
- {
- // get the AVMNodeDescriptor object for each node found
- Pair path = AVMNodeConverter.ToAVMVersionPath(resultNode);
- AVMNodeDescriptor node = this.avmService.lookup(path.getFirst(), path.getSecond());
-
- // process the node to see whether the date and time has passed
- processNode(storeName, node);
- }
- }
- }
- finally
- {
- results.close();
- }
- }
- else
- {
- if (logger.isDebugEnabled())
- logger.debug("Skipping store '" + storeName + "' as it is not a main staging store");
- }
- }
-
- // show all the expired content if debug is on
- if (logger.isDebugEnabled())
- logger.debug("Expired content to action:\n" + this.expiredContent);
-
- // iterate through each store that has expired content, then iterate through
- // each user that has expired content in that store. For each user start
- // a workflow assigned to them to review the expired content.
- for (String storeName: this.expiredContent.keySet())
- {
- // get the name of the store and create the workflow title
- // using it's name
- NodeRef webProjectNodeRef = (NodeRef)avmService.getStoreProperty(storeName,
- SandboxConstants.PROP_WEB_PROJECT_NODE_REF).getValue(DataTypeDefinition.NODE_REF);
- String webProjectName = (String)this.nodeService.getProperty(webProjectNodeRef,
- ContentModel.PROP_NAME);
- String pattern = I18NUtil.getMessage("expiredcontent.workflow.title");
- String workflowTitle = MessageFormat.format(pattern, new Object[] {webProjectName});
-
- Map> users = this.expiredContent.get(storeName);
- for (String userName: users.keySet())
- {
- List expiredContent = users.get(userName);
- startWorkflow(userName, storeName, expiredContent, workflowTitle);
- }
- }
- }
-
- /**
- * Processes the given node.
- *
- * This method is called if the node has been identified as being expired,
- * the date and time is checked to make sure it has actually passed i.e. the
- * date maybe todat but the time set to later in the day. If the item is
- * indeed expired it's added to the expired list and the date reset.
- *
- *
- * @param storeName The name of the store the folder belongs to
- * @param node The node to examine
- */
- private void processNode(String storeName, AVMNodeDescriptor node)
- {
- // check supplied node is a file
- if (node.isFile())
- {
- // check for existence of expires aspect
- String nodePath = node.getPath();
- PropertyValue expirationDateProp = this.avmService.getNodeProperty(-1, nodePath,
- WCMAppModel.PROP_EXPIRATIONDATE);
-
- if (logger.isDebugEnabled())
- logger.debug("Examining expiration date for '" + nodePath + "': " +
- expirationDateProp);
-
- if (expirationDateProp != null)
- {
- Date now = new Date();
- Date expirationDate = (Date)expirationDateProp.getValue(DataTypeDefinition.DATETIME);
-
- if (expirationDate != null && expirationDate.before(now))
- {
- // before doing anything else see whether the item is locked by any user,
- // if it is then just log a warning messge and wait until the next time around
- String[] splitPath = nodePath.split(":");
- String lockOwner = this.avmLockingService.getLockOwner(storeName, splitPath[1]);
-
- if (logger.isDebugEnabled())
- logger.debug("lock details for '" + nodePath + "': " + lockOwner);
-
- if (lockOwner == null)
- {
- // get the map of expired content for the store
- Map> storeExpiredContent = this.expiredContent.get(storeName);
- if (storeExpiredContent == null)
- {
- storeExpiredContent = new HashMap>(4);
- this.expiredContent.put(storeName, storeExpiredContent);
- }
-
- // get the list of expired content for the last modifier of the node
- String modifier = node.getLastModifier();
- List userExpiredContent = storeExpiredContent.get(modifier);
- if (userExpiredContent == null)
- {
- userExpiredContent = new ArrayList(4);
- storeExpiredContent.put(modifier, userExpiredContent);
- }
-
- // add the content to the user's list for the current store
- userExpiredContent.add(nodePath);
-
- if (logger.isDebugEnabled())
- logger.debug("Added " + nodePath + " to " + modifier + "'s list of expired content");
-
- // reset the expiration date
- this.avmService.setNodeProperty(nodePath, WCMAppModel.PROP_EXPIRATIONDATE,
- new PropertyValue(DataTypeDefinition.DATETIME, null));
-
- if (logger.isDebugEnabled())
- logger.debug("Reset expiration date for: " + nodePath);
- }
- else
- {
- if (logger.isWarnEnabled())
- {
- logger.warn("ignoring '" + nodePath + "', although it has expired, it's currently locked");
- }
- }
- }
- }
- }
- }
-
- /**
- * Starts a workflow for the given user prompting them to review the list of given
- * expired content in the given store.
- *
- * @param userName The user the expired content should be sent to
- * @param storeName The store the expired content is in
- * @param expiredContent List of paths to expired content
- * @param workflowTitle The title to apply to the workflow
- */
- private void startWorkflow(String userName, String storeName, List expiredContent,
- String workflowTitle)
- {
- // find the 'Change Request' workflow
- WorkflowDefinition wfDef = workflowService.getDefinitionByName(this.workflowName);
- WorkflowPath path = this.workflowService.startWorkflow(wfDef.id, null);
- if (path != null)
- {
- // extract the start task
- List tasks = this.workflowService.getTasksForWorkflowPath(path.id);
- if (tasks.size() == 1)
- {
- WorkflowTask startTask = tasks.get(0);
-
- if (startTask.state == WorkflowTaskState.IN_PROGRESS)
- {
- // determine the user to assign the workflow to
- String userStore = storeName + STORE_SEPARATOR + userName;
- if (this.avmService.getStore(userStore) == null)
- {
- // use the creator of the store (the web project creator) to assign the
- // workflow to
- String storeCreator = this.avmService.getStore(storeName).getCreator();
-
- if (logger.isDebugEnabled())
- logger.debug("'" + userName + "' is no longer assigned to web project. Using '" +
- storeCreator + "' as they created store '" + storeName + "'");
-
- userName = storeCreator;
- userStore = storeName + STORE_SEPARATOR + userName;
- }
-
- // lookup the NodeRef for the user
- NodeRef assignee = this.personService.getPerson(userName);
-
- // create a workflow store layered over the users store
- String workflowStoreName = sandboxFactory.createUserWorkflowSandbox(storeName, userStore);
-
- // create a workflow package with all the expired items
- NodeRef workflowPackage = setupWorkflowPackage(workflowStoreName, expiredContent);
-
- // create the workflow parameters map
- Map params = new HashMap(5);
- params.put(WorkflowModel.ASSOC_PACKAGE, workflowPackage);
- params.put(WorkflowModel.ASSOC_ASSIGNEE, assignee);
- params.put(WorkflowModel.PROP_WORKFLOW_DESCRIPTION, workflowTitle);
-
- // transition the workflow to send it to the users inbox
- this.workflowService.updateTask(startTask.id, params, null, null);
- this.workflowService.endTask(startTask.id, null);
-
- // remember the root path of the workflow sandbox so we can inform
- // the virtualisation server later
- this.workflowStores.add(workflowStoreName + ":/" +
- JNDIConstants.DIR_DEFAULT_WWW + "/" +
- JNDIConstants.DIR_DEFAULT_APPBASE + "/ROOT");
-
- if (logger.isDebugEnabled())
- logger.debug("Started '" + this.workflowName + "' workflow for user '" +
- userName + "' in store '" + storeName + "'");
- }
- }
- }
- }
-
- /**
- * Sets up a workflow package from the given main workflow store and applies
- * the list of paths as modified items within the main workflow store.
- *
- * @param workflowStoreName The main workflow store to setup
- * @param expiredContent The expired content
- * @return The NodeRef representing the workflow package
- */
- private NodeRef setupWorkflowPackage(String workflowStoreName, List expiredContent)
- {
- // create package paths (layered to user sandbox area as target)
- String packagesPath = workflowStoreName + ":/" + JNDIConstants.DIR_DEFAULT_WWW;
-
- for (final String srcPath : expiredContent)
- {
- final Matcher m = STORE_RELATIVE_PATH_PATTERN.matcher(srcPath);
- String relPath = m.matches() && m.group(1).length() != 0 ? m.group(1) : null;
- String pathInWorkflowStore = workflowStoreName + ":" + relPath;
-
- // call forceCopy to make sure the path appears modified in the workflow
- // sandbox, if the item is already modified or deleted this call has no effect.
- this.avmLockingAwareService.forceCopy(pathInWorkflowStore);
- }
-
- // convert package to workflow package
- AVMNodeDescriptor packageDesc = avmService.lookup(-1, packagesPath);
- NodeRef packageNodeRef = workflowService.createPackage(
- AVMNodeConverter.ToNodeRef(-1, packageDesc.getPath()));
- this.nodeService.setProperty(packageNodeRef, WorkflowModel.PROP_IS_SYSTEM_PACKAGE, true);
-
- return packageNodeRef;
- }
-}
diff --git a/source/java/org/alfresco/repo/avm/AVMInterpreter.java b/source/java/org/alfresco/repo/avm/AVMInterpreter.java
deleted file mode 100644
index 0b274e091f..0000000000
--- a/source/java/org/alfresco/repo/avm/AVMInterpreter.java
+++ /dev/null
@@ -1,970 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see .
- */
-
-package org.alfresco.repo.avm;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.regex.Pattern;
-
-import org.alfresco.repo.avm.util.BulkLoader;
-import org.alfresco.repo.domain.PropertyValue;
-import org.alfresco.service.cmr.avm.AVMNodeDescriptor;
-import org.alfresco.service.cmr.avm.AVMNotFoundException;
-import org.alfresco.service.cmr.avm.AVMService;
-import org.alfresco.service.cmr.avm.AVMStoreDescriptor;
-import org.alfresco.service.cmr.avm.VersionDescriptor;
-import org.alfresco.service.cmr.avm.locking.AVMLockingService;
-import org.alfresco.service.cmr.avmsync.AVMDifference;
-import org.alfresco.service.cmr.avmsync.AVMSyncService;
-import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
-import org.alfresco.service.cmr.repository.NodeRef;
-import org.alfresco.service.cmr.repository.StoreRef;
-import org.alfresco.service.cmr.security.PermissionService;
-import org.alfresco.service.namespace.QName;
-import org.alfresco.wcm.util.WCMUtil;
-import org.springframework.context.support.FileSystemXmlApplicationContext;
-import org.springframework.extensions.surf.util.ISO8601DateFormat;
-
-/**
- * An interactive console for the AVM repository.
- *
- * @author britt
- * @author Gavin Cornwell
- * @author janv
- */
-public class AVMInterpreter
-{
- private static final Pattern collectionPattern = Pattern.compile("^\\[(.*)\\]$");
- private static final Pattern nodeRefPattern = Pattern.compile("^\\w+://\\w+\\w+$");
- private static final Pattern integerPattern = Pattern.compile("^\\d+$");
- private static final Pattern dateTimePattern = Pattern.compile("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$");
-
- /**
- * The service interface.
- */
- private AVMService fService;
-
- /**
- * The sync service.
- */
- private AVMSyncService fSyncService;
-
- /**
- * The locking service.
- */
- private AVMLockingService fLockingService;
-
- /**
- * The permission service.
- */
- private PermissionService fPermissionService;
-
- /**
- * The reader for interaction.
- */
- private BufferedReader fIn;
-
- /**
- * The Bulk Loader.
- */
- private BulkLoader fLoader;
-
- /**
- * Main entry point.
- * Syntax: AVMInteractiveConsole storage (new|old).
- */
- public static void main(String[] args)
- {
- FileSystemXmlApplicationContext context =
- new FileSystemXmlApplicationContext("config/alfresco/application-context.xml");
- AVMInterpreter console = new AVMInterpreter();
- console.setAvmService((AVMService)context.getBean("AVMService"));
- console.setAvmSyncService((AVMSyncService)context.getBean("AVMSyncService"));
- console.setAvmLockingService((AVMLockingService)context.getBean("AVMLockingService"));
- console.setPermissionService((PermissionService)context.getBean("PermissionService"));
- BulkLoader loader = new BulkLoader();
- loader.setAvmService((AVMService)context.getBean("AVMService"));
- console.setBulkLoader(loader);
- console.rep();
- context.close();
- }
-
- /**
- * Make up a new console.
- */
- public AVMInterpreter()
- {
- fIn = new BufferedReader(new InputStreamReader(System.in));
- }
-
- /**
- * Set the AVMService.
- * @param service The AVMService instance.
- */
- public void setAvmService(AVMService service)
- {
- fService = service;
- }
-
- /**
- * Set the AVM sync service.
- * @param syncService
- */
- public void setAvmSyncService(AVMSyncService syncService)
- {
- fSyncService = syncService;
- }
-
- /**
- * Set the AVM locking service.
- * @param lockService
- */
- public void setAvmLockingService(AVMLockingService lockService)
- {
- fLockingService = lockService;
- }
-
- /**
- * Set the PermissionService.
- * @param service The PermissionService instance.
- */
- public void setPermissionService(PermissionService service)
- {
- fPermissionService = service;
- }
-
- /**
- * Set the bulk loader.
- * @param loader
- */
- public void setBulkLoader(BulkLoader loader)
- {
- fLoader = loader;
- }
-
- /**
- * A Read-Eval-Print loop.
- */
- public void rep()
- {
- while (true)
- {
- System.out.print("> ");
- try
- {
- String line = fIn.readLine();
- if (line.equals("exit"))
- {
- return;
- }
- System.out.println(interpretCommand(line, fIn));
- }
- catch (IOException ie)
- {
- ie.printStackTrace(System.err);
- System.exit(2);
- }
- }
- }
-
- /**
- * Interpret a single command using the BufferedReader passed in for any data needed.
- * @param line The unparsed command
- * @param in A Reader to be used for commands that need input data.
- * @return The textual output of the command.
- */
- public String interpretCommand(String line, BufferedReader in)
- {
- String[] command = line.split(",\\s+");
- if (command.length == 0)
- {
- command = new String[1];
- command[0] = line;
- }
- try
- {
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- PrintStream out = new PrintStream(bout);
- if (command[0].equals("ls"))
- {
- if (command.length < 2)
- {
- return "Syntax Error.";
- }
- int version = (command.length == 2) ? -1 : Integer.parseInt(command[2]);
- AVMNodeDescriptor desc = fService.lookup(version, command[1]);
- if (desc == null)
- {
- return "Not Found.";
- }
- Map listing =
- fService.getDirectoryListing(desc, true);
- for (String name : listing.keySet())
- {
- out.println(name + " " + listing.get(name));
- }
- }
- else if (command[0].equals("lsr"))
- {
- if (command.length < 2)
- {
- return "Syntax Error.";
- }
- int version = (command.length == 2) ? -1 : Integer.parseInt(command[2]);
- AVMNodeDescriptor desc = fService.lookup(version, command[1]);
- recursiveList(out, desc, 0);
- }
- else if (command[0].equals("lsrep"))
- {
- List repos = fService.getStores();
- for (AVMStoreDescriptor repo : repos)
- {
- out.println(repo);
- }
- }
- else if (command[0].equals("lsver"))
- {
- if ((command.length < 2) || (command.length > 4))
- {
- return "Syntax Error.";
- }
-
- List listing = null;
- String storeName = command[1];
- if (command.length == 2)
- {
- listing = fService.getStoreVersions(storeName);
- }
- else
- {
- Date fromDate = ISO8601DateFormat.parse(command[2]);
- Date toDate = new Date();
- if (command.length == 4)
- {
- toDate = ISO8601DateFormat.parse(command[3]);
- }
- listing = fService.getStoreVersions(storeName, fromDate, toDate);
- }
-
- for (VersionDescriptor desc : listing)
- {
- out.println(desc);
- }
- }
- else if (command[0].equals("mkrep"))
- {
- if (command.length != 2)
- {
- return "Syntax Error.";
- }
- fService.createStore(command[1]);
- }
- else if (command[0].equals("load"))
- {
- if (command.length != 3)
- {
- return "Syntax Error.";
- }
- fLoader.recursiveLoad(command[1], command[2]);
- }
- else if (command[0].equals("mkdir"))
- {
- if (command.length != 3)
- {
- return "Syntax Error.";
- }
- fService.createDirectory(command[1], command[2]);
- }
- else if (command[0].equals("mkbr"))
- {
- if (command.length != 5)
- {
- return "Syntax Error.";
- }
- fService.createBranch(Integer.parseInt(command[4]), command[1], command[2], command[3]);
- }
- else if (command[0].equals("mkldir"))
- {
- if (command.length != 4)
- {
- return "Syntax Error.";
- }
- fService.createLayeredDirectory(command[1], command[2], command[3]);
- }
- else if (command[0].equals("setopacity"))
- {
- if (command.length != 3)
- {
- return "Syntax Error.";
- }
- boolean isOpaque = new Boolean(command[2]);
- fService.setOpacity(command[1], isOpaque);
- }
- else if (command[0].equals("rename"))
- {
- if (command.length != 5)
- {
- return "Syntax Error.";
- }
- fService.rename(command[1], command[2], command[3], command[4]);
- }
- else if (command[0].equals("cp"))
- {
- if (command.length != 5)
- {
- return "Syntax Error.";
- }
- InputStream fin = fService.getFileInputStream(Integer.parseInt(command[2]), command[1]);
- OutputStream fout = fService.createFile(command[3], command[4]);
- byte [] buff = new byte[8192];
- int read;
- while ((read = fin.read(buff)) != -1)
- {
- fout.write(buff, 0, read);
- }
- fin.close();
- fout.close();
- }
- else if (command[0].equals("retarget"))
- {
- if (command.length != 3)
- {
- return "Syntax Error.";
- }
- fService.retargetLayeredDirectory(command[1], command[2]);
- }
- else if (command[0].equals("mkprimary"))
- {
- if (command.length != 2)
- {
- return "Syntax Error.";
- }
- fService.makePrimary(command[1]);
- }
- else if (command[0].equals("mklfile"))
- {
- if (command.length != 4)
- {
- return "Syntax Error.";
- }
- fService.createLayeredFile(command[1], command[2], command[3]);
- }
- else if (command[0].equals("snap"))
- {
- if ((command.length < 2) || (command.length > 4))
- {
- return "Syntax Error.";
- }
-
- String tag = (command.length > 2) ? command[2] : null;
- String description = (command.length > 3) ? command[3] : null;
-
- fService.createSnapshot(command[1], tag, description);
- }
- else if (command[0].equals("cat"))
- {
- if (command.length < 2)
- {
- return "Syntax Error.";
- }
- int version = (command.length == 2) ? -1 : Integer.parseInt(command[2]);
- BufferedReader reader =
- new BufferedReader(
- new InputStreamReader(fService.getFileInputStream(version, command[1])));
- String l;
- while ((l = reader.readLine()) != null)
- {
- out.println(l);
- }
- reader.close();
- }
- else if (command[0].equals("rm"))
- {
- if (command.length != 3)
- {
- return "Syntax Error.";
- }
- fService.removeNode(command[1], command[2]);
- }
- else if (command[0].equals("rmrep"))
- {
- if (command.length != 2)
- {
- return "Syntax Error.";
- }
- fService.purgeStore(command[1]);
- }
- else if (command[0].equals("rmver"))
- {
- if (command.length != 3)
- {
- return "Syntax Error.";
- }
-
- String storeName = command[1];
- int ver =Integer.parseInt(command[2]);
- String wpStoreId = WCMUtil.getWebProject(fService, storeName);
- if ((wpStoreId != null) && (ver <= 2))
- {
- return "WCM store - cannot delete versions 0-2";
- }
- fService.purgeVersion(ver, storeName);
- }
- else if (command[0].equals("rmvers"))
- {
- if (command.length != 4)
- {
- return "Syntax Error.";
- }
- String storeName = command[1];
- String wpStoreId = WCMUtil.getWebProject(fService, storeName);
-
- Date fromDate = ISO8601DateFormat.parse(command[2]);
- Date toDate = ISO8601DateFormat.parse(command[3]);
-
- List listing = fService.getStoreVersions(storeName, fromDate, toDate);
- for (VersionDescriptor desc : listing)
- {
- int ver = desc.getVersionID();
- if ((wpStoreId != null) && (ver <= 2))
- {
- return "WCM store - cannot delete versions 0-2";
- }
- fService.purgeVersion(ver, storeName);
- }
- }
- else if (command[0].equals("write"))
- {
- if (command.length != 2)
- {
- return "Syntax Error.";
- }
- PrintStream ps =
- new PrintStream(fService.getFileOutputStream(command[1]));
- String l;
- while (!(l = in.readLine()).equals(""))
- {
- ps.println(l);
- }
- ps.close();
- }
- else if (command[0].equals("create"))
- {
- if (command.length != 3)
- {
- return "Syntax Error.";
- }
- PrintStream ps =
- new PrintStream(fService.createFile(command[1], command[2]));
- String l;
- while (!(l = in.readLine()).equals(""))
- {
- ps.println(l);
- }
- ps.close();
- }
- else if (command[0].equals("stat"))
- {
- if (command.length < 2)
- {
- return "Syntax Error.";
- }
- int version = (command.length == 2) ? -1 : Integer.parseInt(command[2]);
- AVMNodeDescriptor desc = fService.lookup(version, command[1]);
- out.println(desc);
- out.println("Version: " + desc.getVersionID());
- out.println("Owner: " + desc.getOwner());
- out.println("Mod Time: " + new Date(desc.getModDate()));
- }
- else if (command[0].equals("getnodeproperties"))
- {
- if (command.length < 2)
- {
- return "Syntax Error.";
- }
- int version = (command.length == 2) ? -1 : Integer.parseInt(command[2]);
- final Map properties = fService.getNodeProperties(version, command[1]);
- for (final Map.Entry p : properties.entrySet())
- {
- out.println(p.getKey() + ": " + p.getValue());
- }
- }
- else if (command[0].equals("setnodepermission"))
- {
- if (command.length != 4)
- {
- return "Syntax Error.";
- }
-
- fPermissionService.setPermission(
- AVMNodeConverter.ToNodeRef(-1, command[1]), command[2], command[3], true);
- }
- else if (command[0].equals("clearnodepermission"))
- {
- if (command.length != 3)
- {
- return "Syntax Error.";
- }
-
- fPermissionService.clearPermission(
- AVMNodeConverter.ToNodeRef(-1, command[1]), command[2]);
- }
- else if (command[0].equals("descnode"))
- {
- if (command.length < 2)
- {
- return "Syntax Error.";
- }
-
- String path = command[1];
- int version = (command.length == 2) ? -1 : Integer.parseInt(command[2]);
- AVMNodeDescriptor nodeDesc = fService.lookup(version, path);
- if (nodeDesc == null)
- {
- return "Path Not Found.";
- }
-
- out.println(nodeDesc.toString());
- out.println("isDirectory: " + nodeDesc.isDirectory());
- out.println("isFile: " + nodeDesc.isFile());
- out.println("isPrimary: " + nodeDesc.isPrimary());
- out.println("isOpaque: " + nodeDesc.getOpacity());
- out.println("creator: " + nodeDesc.getCreator());
- out.println("owner: " + nodeDesc.getOwner());
- out.println("lastModifier: " + nodeDesc.getLastModifier());
- out.println("created: " + new Date(nodeDesc.getCreateDate()));
- out.println("modified: " + new Date(nodeDesc.getModDate()));
- out.println("lastAccess: " + new Date(nodeDesc.getAccessDate()));
-
- // get lock information
- String lockPath = path.substring(path.indexOf("/"));
- String store = path.substring(0, path.indexOf(":"));
- String mainStore = store;
- if (store.indexOf("--") != -1)
- {
- mainStore = store.substring(0, store.indexOf("--"));
- }
-
- try
- {
- String lockOwner = fLockingService.getLockOwner(mainStore, lockPath);
- if (lockOwner != null)
- {
- out.println("lock: " + lockOwner);
- }
- else
- {
- out.println("No locks found");
- }
- }
- catch (AVMNotFoundException avmerr)
- {
- out.println("No locks found");
- }
- }
- else if (command[0].equals("deletenodeproperty"))
- {
- if (command.length != 3)
- {
- return "Syntax Error.";
- }
-
- fService.deleteNodeProperty(command[1], QName.createQName(command[2]));
- out.println("deleted property " + command[2] + " of " + command[1]);
- }
- else if (command[0].equals("history"))
- {
- if (command.length != 4)
- {
- return "Syntax Error.";
- }
- AVMNodeDescriptor desc = fService.lookup(Integer.parseInt(command[2]), command[1]);
- List history = fService.getHistory(desc, Integer.parseInt(command[3]));
- for (AVMNodeDescriptor node : history)
- {
- out.println(node);
- out.println("Version: " + node.getVersionID());
- out.println("Owner: " + node.getOwner());
- out.println("Mod Time: " + new Date(node.getModDate()));
- }
- }
- /*
- else if (command[0].equals("catver"))
- {
- if (command.length != 4)
- {
- return "Syntax Error.";
- }
- AVMNodeDescriptor desc = fService.lookup(Integer.parseInt(command[2]), command[1]);
- List history = fService.getHistory(desc, Integer.parseInt(command[3]));
- if (history.size() == 0)
- {
- return "No History.";
- }
- BufferedReader reader =
- new BufferedReader(
- new InputStreamReader(
- fService.getFileInputStream(history.get(history.size() - 1))));
- String l;
- while ((l = reader.readLine()) != null)
- {
- out.println(l);
- }
- reader.close();
- }
- */
- else if (command[0].equals("ca"))
- {
- if (command.length != 5)
- {
- return "Syntax Error.";
- }
- AVMNodeDescriptor left = fService.lookup(Integer.parseInt(command[2]), command[1]);
- AVMNodeDescriptor right = fService.lookup(Integer.parseInt(command[4]), command[3]);
- AVMNodeDescriptor ca = fService.getCommonAncestor(left, right);
- out.println(ca);
- }
- else if (command[0].equals("statstore"))
- {
- if (command.length != 2)
- {
- return "Syntax Error.";
- }
- AVMStoreDescriptor desc = fService.getStore(command[1]);
- if (desc == null)
- {
- return "Not Found.";
- }
- out.println(desc);
- Map props =
- fService.getStoreProperties(command[1]);
- for (QName name : props.keySet())
- {
- out.println(name + ": " + props.get(name));
- }
- }
- else if (command[0].equals("compare"))
- {
- if (command.length != 5)
- {
- return "Syntax Error.";
- }
- List diffs = fSyncService.compare(Integer.parseInt(command[2]),
- command[1],
- Integer.parseInt(command[4]),
- command[3],
- null);
- for (AVMDifference diff : diffs)
- {
- out.println(diff);
- }
- }
- else if (command[0].equals("update"))
- {
- if (command.length != 4)
- {
- return "Syntax Error.";
- }
- AVMDifference diff = new AVMDifference(Integer.parseInt(command[2]), command[1],
- -1, command[3], AVMDifference.NEWER);
- List diffs = new ArrayList();
- diffs.add(diff);
- fSyncService.update(diffs, null, false, false, false, false, null, null);
- }
- else if (command[0].equals("resetLayer"))
- {
- if (command.length != 2)
- {
- return "Syntax Error.";
- }
- fSyncService.resetLayer(command[1]);
- }
- else if (command[0].equals("flatten"))
- {
- if (command.length != 3)
- {
- return "Syntax Error.";
- }
- fSyncService.flatten(command[1], command[2]);
- }
- else if (command[0].equals("getnodeaspects"))
- {
- if (command.length != 3)
- {
- return "Syntax Error.";
- }
-
- final Set aspects = fService.getAspects(Integer.parseInt(command[2]), command[1]);
- for (final QName qn : aspects)
- {
- out.println(qn.toString());
- }
- }
- else if (command[0].equals("addnodeaspect"))
- {
- if (command.length != 3)
- {
- return "Syntax Error.";
- }
-
- fService.addAspect(command[1], QName.createQName(command[2]));
- }
- else if (command[0].equals("deletenodeaspect"))
- {
- if (command.length != 3)
- {
- return "Syntax Error.";
- }
-
- fService.removeAspect(command[1], QName.createQName(command[2]));
- }
- else if (command[0].equals("setnodeproperty"))
- {
- if (command.length < 4)
- {
- return "Syntax Error.";
- }
-
- QName valueQName = QName.createQName(command[2]);
-
- String propertyValue = "";
-
- // If multiple values are specified then concatenate the values
- if (command.length > 4)
- {
- StringBuffer sb = new StringBuffer();
- for (int i=3; i 4)
- {
- StringBuffer sb = new StringBuffer();
- for (int i=3; i listing = fService.getDirectoryListing(dir, true);
- for (String name : listing.keySet())
- {
- AVMNodeDescriptor child = listing.get(name);
- for (int i = 0; i < indent; i++)
- {
- out.print(' ');
- }
- out.println(name + " " + child);
- if (child.isDirectory())
- {
- recursiveList(out, child, indent + 2);
- }
- }
- }
-
- private static Serializable convertValueFromSring(String sValue)
- {
- Serializable retValue = "";
-
- CharSequence seq = sValue.subSequence(0, sValue.length());
-
- if (collectionPattern.matcher(seq).matches())
- {
- String[] elements = getCSVArray(sValue.substring(1, sValue.length()-1));
-
- // Should this be an ArrayList or a HashSet?
- Collection propValues = new HashSet(elements.length);
- for (int i=0; i.
- */
-package org.alfresco.repo.avm;
-
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.SortedMap;
-
-import org.alfresco.repo.avm.util.AVMUtil;
-import org.alfresco.repo.domain.PropertyValue;
-import org.alfresco.repo.security.authentication.AuthenticationUtil;
-import org.alfresco.repo.security.permissions.AccessDeniedException;
-import org.alfresco.service.cmr.avm.AVMExistsException;
-import org.alfresco.service.cmr.avm.AVMNodeDescriptor;
-import org.alfresco.service.cmr.avm.AVMService;
-import org.alfresco.service.cmr.avm.AVMStoreDescriptor;
-import org.alfresco.service.cmr.avm.LayeringDescriptor;
-import org.alfresco.service.cmr.avm.VersionDescriptor;
-import org.alfresco.service.cmr.avm.locking.AVMLockingException;
-import org.alfresco.service.cmr.avm.locking.AVMLockingService;
-import org.alfresco.service.cmr.avm.locking.AVMLockingService.LockState;
-import org.alfresco.service.cmr.repository.ContentData;
-import org.alfresco.service.cmr.repository.ContentReader;
-import org.alfresco.service.cmr.repository.ContentWriter;
-import org.alfresco.service.cmr.repository.NodeRef;
-import org.alfresco.service.cmr.security.AccessStatus;
-import org.alfresco.service.cmr.security.PermissionService;
-import org.alfresco.service.namespace.QName;
-import org.alfresco.util.Pair;
-import org.alfresco.wcm.util.WCMUtil;
-import org.alfresco.wcm.webproject.WebProjectService;
-import org.springframework.beans.BeansException;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-import org.springframework.extensions.surf.util.I18NUtil;
-
-/**
- * An AVMLockingService aware implementation of AVMService.
- * @author britt
- */
-public class AVMLockingAwareService implements AVMService, ApplicationContextAware
-{
- public static final String STORE_SEPARATOR = "--";
-
- public static final String STORE_WORKFLOW = "workflow";
-
- public static final String STORE_PREVIEW = "preview";
-
- private AVMService fService;
-
- private AVMLockingService fLockingService;
-
- private PermissionService permissionService;
-
- private ApplicationContext fContext;
-
- private WebProjectService wpService;
-
- public AVMLockingAwareService()
- {
- }
-
- public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
- {
- fContext = applicationContext;
- }
-
- public void init()
- {
- fService = (AVMService)fContext.getBean("avmService");
- fLockingService = (AVMLockingService)fContext.getBean("avmLockingService");
- permissionService = (PermissionService) fContext.getBean("PermissionService");
- wpService = (WebProjectService) fContext.getBean("WebProjectService");
- }
-
- public void addAspect(String path, QName aspectName)
- {
- grabLock(path);
- fService.addAspect(path, aspectName);
- }
-
- public void copy(int srcVersion, String srcPath, String dstPath, String name)
- {
- fService.copy(srcVersion, srcPath, dstPath, name);
- }
-
- public void createBranch(int version, String srcPath, String dstPath,
- String name)
- {
- fService.createBranch(version, srcPath, dstPath, name);
- }
-
- public void createDirectory(String path, String name)
- {
- fService.createDirectory(path, name);
- }
-
- public OutputStream createFile(String path, String name)
- {
- grabLock(AVMUtil.extendAVMPath(path, name));
- return fService.createFile(path, name);
- }
-
- public void createFile(String path, String name, InputStream in)
- {
- grabLock(AVMUtil.extendAVMPath(path, name));
- fService.createFile(path, name, in);
- }
-
- public void createLayeredDirectory(String targetPath, String parent,
- String name)
- {
- fService.createLayeredDirectory(targetPath, parent, name);
- }
-
- public void createLayeredFile(String targetPath, String parent, String name)
- {
- grabLock(AVMUtil.extendAVMPath(parent, name));
- fService.createLayeredFile(targetPath, parent, name);
- }
-
- public Map createSnapshot(String store, String tag, String description)
- {
- return fService.createSnapshot(store, tag, description);
- }
-
- public void createStore(String name)
- {
- fService.createStore(name);
- }
-
- public void createStore(String name, Map props)
- {
- fService.createStore(name, props);
- }
-
- public void deleteNodeProperties(String path)
- {
- grabLock(path);
- fService.deleteNodeProperties(path);
- }
-
- public void deleteNodeProperty(String path, QName name)
- {
- grabLock(path);
- fService.deleteNodeProperty(path, name);
- }
-
- public void deleteStoreProperty(String store, QName name)
- {
- fService.deleteStoreProperty(store, name);
- }
-
- public AVMNodeDescriptor forceCopy(String path)
- {
- grabLock(path);
- return fService.forceCopy(path);
- }
-
- public Pair getAPath(AVMNodeDescriptor desc)
- {
- return fService.getAPath(desc);
- }
-
- public List getPathsInStoreVersion(AVMNodeDescriptor desc, String store, int version)
- {
- return fService.getPathsInStoreVersion(desc, store, version);
- }
-
- public Set getAspects(int version, String path)
- {
- return fService.getAspects(version, path);
- }
-
- public Set getAspects(AVMNodeDescriptor desc)
- {
- return fService.getAspects(desc);
- }
-
- public AVMNodeDescriptor getCommonAncestor(AVMNodeDescriptor left,
- AVMNodeDescriptor right)
- {
- return fService.getCommonAncestor(left, right);
- }
-
- public ContentData getContentDataForRead(int version, String path)
- {
- return fService.getContentDataForRead(version, path);
- }
-
- public ContentData getContentDataForRead(AVMNodeDescriptor desc)
- {
- return fService.getContentDataForRead(desc);
- }
-
- public ContentData getContentDataForWrite(String path)
- {
- grabLock(path);
- return fService.getContentDataForWrite(path);
- }
-
- public ContentReader getContentReader(int version, String path)
- {
- return fService.getContentReader(version, path);
- }
-
- public ContentWriter getContentWriter(String path, boolean update)
- {
- grabLock(path);
- return fService.getContentWriter(path, update);
- }
-
- public List getDeleted(int version, String path)
- {
- return fService.getDeleted(version, path);
- }
-
- public SortedMap getDirectoryListing(int version, String path)
- {
- return fService.getDirectoryListing(version, path);
- }
-
- public SortedMap getDirectoryListing(int version, String path, boolean includeDeleted)
- {
- return fService.getDirectoryListing(version, path, includeDeleted);
- }
-
- public SortedMap getDirectoryListing(AVMNodeDescriptor dir)
- {
- return fService.getDirectoryListing(dir);
- }
-
- public SortedMap getDirectoryListing(AVMNodeDescriptor dir, String childNamePattern)
- {
- return fService.getDirectoryListing(dir, childNamePattern);
- }
-
- public SortedMap getDirectoryListing(AVMNodeDescriptor dir, boolean includeDeleted)
- {
- return fService.getDirectoryListing(dir, includeDeleted);
- }
-
- public AVMNodeDescriptor[] getDirectoryListingArray(int version, String path, boolean includeDeleted)
- {
- return fService.getDirectoryListingArray(version, path, includeDeleted);
- }
-
- public AVMNodeDescriptor[] getDirectoryListingArray(AVMNodeDescriptor dir, boolean includeDeleted)
- {
- return fService.getDirectoryListingArray(dir, includeDeleted);
- }
-
- public SortedMap getDirectoryListingDirect(int version, String path)
- {
- return fService.getDirectoryListingDirect(version, path);
- }
-
- public SortedMap getDirectoryListingDirect(int version, String path, boolean includeDeleted)
- {
- return fService.getDirectoryListingDirect(version, path, includeDeleted);
- }
-
- public SortedMap getDirectoryListingDirect(
- AVMNodeDescriptor dir, boolean includeDeleted)
- {
- return fService.getDirectoryListingDirect(dir, includeDeleted);
- }
-
- public InputStream getFileInputStream(int version, String path)
- {
- return fService.getFileInputStream(version, path);
- }
-
- public InputStream getFileInputStream(AVMNodeDescriptor desc)
- {
- return fService.getFileInputStream(desc);
- }
-
- public OutputStream getFileOutputStream(String path)
- {
- grabLock(path);
- return fService.getFileOutputStream(path);
- }
-
- public List> getHeadPaths(AVMNodeDescriptor desc)
- {
- return fService.getHeadPaths(desc);
- }
-
- public List getHistory(AVMNodeDescriptor desc, int count)
- {
- return fService.getHistory(desc, count);
- }
-
- public String getIndirectionPath(int version, String path)
- {
- return fService.getIndirectionPath(version, path);
- }
-
- public int getLatestSnapshotID(String storeName)
- {
- return fService.getLatestSnapshotID(storeName);
- }
-
- public LayeringDescriptor getLayeringInfo(int version, String path)
- {
- return fService.getLayeringInfo(version, path);
- }
-
- public int getNextVersionID(String storeName)
- {
- return fService.getNextVersionID(storeName);
- }
-
- public Map getNodeProperties(int version, String path)
- {
- return fService.getNodeProperties(version, path);
- }
-
- public Map getNodeProperties(AVMNodeDescriptor desc)
- {
- return fService.getNodeProperties(desc);
- }
-
- public PropertyValue getNodeProperty(int version, String path, QName name)
- {
- return fService.getNodeProperty(version, path, name);
- }
-
- public List> getPaths(AVMNodeDescriptor desc)
- {
- return fService.getPaths(desc);
- }
-
- public List> getPathsInStoreHead(
- AVMNodeDescriptor desc, String store)
- {
- return fService.getPathsInStoreHead(desc, store);
- }
-
- public AVMStoreDescriptor getStore(String name)
- {
- return fService.getStore(name);
- }
-
- public Map getStoreProperties(String store)
- {
- return fService.getStoreProperties(store);
- }
-
- public PropertyValue getStoreProperty(String store, QName name)
- {
- return fService.getStoreProperty(store, name);
- }
-
- public AVMNodeDescriptor getStoreRoot(int version, String name)
- {
- return fService.getStoreRoot(version, name);
- }
-
- public List getStoreVersions(String name)
- {
- return fService.getStoreVersions(name);
- }
-
- public List getStoreVersions(String name, Date from, Date to)
- {
- return fService.getStoreVersions(name, from, to);
- }
-
- public List getStores()
- {
- return fService.getStores();
- }
-
- public AVMStoreDescriptor getSystemStore()
- {
- return fService.getSystemStore();
- }
-
- public boolean hasAspect(int version, String path, QName aspectName)
- {
- return fService.hasAspect(version, path, aspectName);
- }
-
- public void link(String parentPath, String name, AVMNodeDescriptor toLink)
- {
- // TODO Does this need a lock? I don't think so, but revisit.
- fService.link(parentPath, name, toLink);
- }
-
- public void updateLink(String parentPath, String name, AVMNodeDescriptor toLink)
- {
- // TODO Does this need a lock? I don't think so, but revisit.
- fService.updateLink(parentPath, name, toLink);
- }
-
- public AVMNodeDescriptor lookup(int version, String path)
- {
- return fService.lookup(version, path);
- }
-
- public AVMNodeDescriptor lookup(int version, String path,
- boolean includeDeleted)
- {
- return fService.lookup(version, path, includeDeleted);
- }
-
- public AVMNodeDescriptor lookup(AVMNodeDescriptor dir, String name)
- {
- return fService.lookup(dir, name);
- }
-
- public AVMNodeDescriptor lookup(AVMNodeDescriptor dir, String name,
- boolean includeDeleted)
- {
- return fService.lookup(dir, name, includeDeleted);
- }
-
- public void makePrimary(String path)
- {
- fService.makePrimary(path);
- }
-
- public void makeTransparent(String dirPath, String name)
- {
- fService.makeTransparent(dirPath, name);
- }
-
- public void purgeStore(String name)
- {
- fService.purgeStore(name);
-
- String webProject = WCMUtil.getWebProject(fService, name);
- if (webProject != null)
- {
- fLockingService.removeLocks(name);
- }
- }
-
- public void purgeVersion(int version, String name)
- {
- fService.purgeVersion(version, name);
- }
-
- public Map queryStorePropertyKey(String store, QName keyPattern)
- {
- return fService.queryStorePropertyKey(store, keyPattern);
- }
-
- public Map> queryStoresPropertyKeys(QName keyPattern)
- {
- return fService.queryStoresPropertyKeys(keyPattern);
- }
-
- public void removeAspect(String path, QName aspectName)
- {
- grabLock(path);
- fService.removeAspect(path, aspectName);
- }
-
- public void removeNode(String parent, String name)
- {
- String path = AVMUtil.extendAVMPath(parent, name);
- grabLock(path);
- fService.removeNode(parent, name);
- String[] storePath = AVMUtil.splitPath(parent);
- String avmStore = storePath[0];
- fService.createSnapshot(avmStore, null, "Removed "+path);
- String webProject = WCMUtil.getWebProject(fService, avmStore);
- if (webProject != null)
- {
- Map lockDataToMatch = Collections.singletonMap(WCMUtil.LOCK_KEY_STORE_NAME, avmStore);
- String relPath = AVMUtil.extendAVMPath(storePath[1], name); // store-relative path, eg. /www/avm_webapps/ROOT/my.txt
- fLockingService.removeLocks(webProject, relPath, lockDataToMatch);
- }
- }
-
- public void removeNode(String path)
- {
- grabLock(path);
- fService.removeNode(path);
- String[] storePath = AVMUtil.splitPath(path);
- String avmStore = storePath[0];
- String relPath = storePath[1]; // store-relative path, eg. /www/avm_webapps/ROOT/my.txt
- fService.createSnapshot(avmStore, null, "Removed "+path);
- String webProject = WCMUtil.getWebProject(fService, avmStore);
- if (webProject != null)
- {
- Map lockDataToMatch = Collections.singletonMap(WCMUtil.LOCK_KEY_STORE_NAME, avmStore);
- fLockingService.removeLocks(webProject, relPath, lockDataToMatch);
- }
- }
-
- public void rename(String srcParent, String srcName, String dstParent, String dstName)
- {
- String srcPath = AVMUtil.extendAVMPath(srcParent, srcName);
- String dstPath = AVMUtil.extendAVMPath(dstParent, dstName);
-
- AVMNodeDescriptor desc = fService.lookup(-1, srcPath, false);
- if (! (desc != null && desc.isDirectory()))
- {
- grabLock(srcPath);
- }
-
- fService.rename(srcParent, srcName, dstParent, dstName);
-
- if (! (desc != null && desc.isDirectory()))
- {
- String[] srcStorePath = AVMUtil.splitPath(srcPath);
- String[] dstStorePath = AVMUtil.splitPath(dstPath);
-
- String srcWebProject = WCMUtil.getWebProject(fService, srcStorePath[0]);
- String dstWebProject = WCMUtil.getWebProject(fService, dstStorePath[0]);
-
- if ((dstWebProject != null) && (dstWebProject.equals(srcWebProject)))
- {
- // Make sure we hold the lock already
- grabLock(dstPath);
- }
- else
- {
- // Remove the old lock and take the new
- fLockingService.removeLock(srcWebProject, srcStorePath[1]);
- grabLock(dstPath);
- }
- }
- }
-
- public void renameStore(String sourceName, String destName)
- {
- fService.renameStore(sourceName, destName);
- }
-
- public void retargetLayeredDirectory(String path, String target)
- {
- // TODO This assumes that directories are not locked.
- fService.retargetLayeredDirectory(path, target);
- }
-
- public void revert(String path, AVMNodeDescriptor toRevertTo)
- {
- grabLock(path);
- fService.revert(path, toRevertTo);
- }
-
- public void setContentData(String path, ContentData data)
- {
- grabLock(path);
- fService.setContentData(path, data);
- }
-
- public void setEncoding(String path, String encoding)
- {
- grabLock(path);
- fService.setEncoding(path, encoding);
- }
-
- public void setGuid(String path, String guid)
- {
- grabLock(path);
- fService.setGuid(path, guid);
- }
-
- public void setMetaDataFrom(String path, AVMNodeDescriptor from)
- {
- grabLock(path);
- fService.setMetaDataFrom(path, from);
- }
-
- public void setMimeType(String path, String mimeType)
- {
- grabLock(path);
- fService.setMimeType(path, mimeType);
- }
-
- public void setNodeProperties(String path,
- Map properties)
- {
- grabLock(path);
- fService.setNodeProperties(path, properties);
- }
-
- public void setNodeProperty(String path, QName name, PropertyValue value)
- {
- grabLock(path);
- fService.setNodeProperty(path, name, value);
- }
-
- public void setOpacity(String path, boolean opacity)
- {
- // TODO Assumes no directory locking.
- fService.setOpacity(path, opacity);
- }
-
- public void setStoreProperties(String store, Map props)
- {
- fService.setStoreProperties(store, props);
- }
-
- public void setStoreProperty(String store, QName name, PropertyValue value)
- {
- fService.setStoreProperty(store, name, value);
- }
-
- public void uncover(String dirPath, String name)
- {
- // TODO What about when this is a directory?
- grabLock(AVMUtil.extendAVMPath(dirPath, name));
- fService.uncover(dirPath, name);
- }
-
- public void createDirectory(String path, String name, List aspects, Map properties)
- {
- fService.createDirectory(path, name, aspects, properties);
- }
-
- public void createFile(String path, String name, InputStream in, List aspects, Map properties)
- {
- grabLock(AVMUtil.extendAVMPath(path, name));
- fService.createFile(path, name, in, aspects, properties);
- }
-
- private void grabLock(String path)
- {
- AVMNodeDescriptor desc = fService.lookup(-1, path, false);
- if (desc != null && desc.isDirectory())
- {
- return;
- }
- String[] storePath = AVMUtil.splitPath(path);
- String avmStore = storePath[0];
- String webProject = WCMUtil.getWebProject(fService, storePath[0]);
- if (webProject != null && webProject.equals(avmStore))
- {
- // Don't do locking in staging.
- return;
- }
- if (avmStore.indexOf(STORE_SEPARATOR + STORE_WORKFLOW) != -1)
- {
- //Allow lock in workflow store if user has "Write" permission
- NodeRef nodeRef = AVMNodeConverter.ToNodeRef(-1, path);
- if (permissionService.hasPermission(nodeRef, PermissionService.WRITE) == AccessStatus.DENIED)
- {
- String errorMessage = I18NUtil.getMessage("avmlockservice.accessdenied", AuthenticationUtil.getFullyAuthenticatedUser());
- throw new AccessDeniedException(errorMessage);
- }
- }
- else if (webProject != null)
- {
- String userName = AuthenticationUtil.getFullyAuthenticatedUser();
- LockState lockState = fLockingService.getLockState(webProject, storePath[1], userName);
- String wpStoreId = WCMUtil.getWebProjectStoreId(webProject);
-
- // ALF-11440 PM 18-Dec-2011:
- // 1. Managers may edit any unlocked file - it becomes locked.
- // 2. Managers may edit any locked file in any sandbox in which it is locked
- // but not in sandboxes where it is unlocked.
- // ALF-8787 and ALF-12766 are consistent with 2.
- // A Manager should only be able to create a file in a sandbox
- // if it is NOT locked somewhere else.
- switch (lockState)
- {
- case LOCK_NOT_OWNER:
- String lockOwner = fLockingService.getLockOwner(webProject, storePath[1]);
- if ((wpService.isContentManager(wpStoreId, userName)) &&
- (avmStore.equals(wpStoreId + STORE_SEPARATOR + lockOwner) ||
- avmStore.equals(wpStoreId + STORE_SEPARATOR + lockOwner
- + STORE_SEPARATOR + STORE_PREVIEW)))
- {
- // Handle as if LOCK_OWNER
- break;
- }
- throw new AVMLockingException("avmlockservice.locked", path, lockOwner);
- case NO_LOCK:
- Map lockAttributes = Collections.singletonMap(WCMUtil.LOCK_KEY_STORE_NAME, avmStore);
- fLockingService.lock(webProject, storePath[1], userName, lockAttributes);
- break;
- case LOCK_OWNER:
- // Nothing to do
- break;
- }
- }
- }
-
- public List getStoreVersionsTo(String name, int version)
- {
- return fService.getStoreVersionsTo(name, version);
- }
-
- public List getStoreVersionsFrom(String name, int version)
- {
- return fService.getStoreVersionsFrom(name, version);
- }
-
- public List getStoreVersionsBetween(String name, int from, int to)
- {
- return fService.getStoreVersionsBetween(name, from, to);
- }
-
-}
diff --git a/source/java/org/alfresco/repo/avm/AVMNodeConverter.java b/source/java/org/alfresco/repo/avm/AVMNodeConverter.java
deleted file mode 100644
index c05d7e9489..0000000000
--- a/source/java/org/alfresco/repo/avm/AVMNodeConverter.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-
-package org.alfresco.repo.avm;
-
-import org.alfresco.repo.avm.util.AVMUtil;
-import org.alfresco.service.cmr.avm.AVMException;
-import org.alfresco.service.cmr.repository.NodeRef;
-import org.alfresco.service.cmr.repository.StoreRef;
-import org.alfresco.util.Pair;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * Utility for going back and forth between the AVM world and
- * the StoreRef
, NodeRef
world.
- * @author britt
- */
-public class AVMNodeConverter
-{
- private static Log fgLogger = LogFactory.getLog(AVMNodeConverter.class);
-
- /**
- * Get a NodeRef corresponding to the given path and version.
- * @param version The version id.
- * @param avmPath The AVM path.
- * @return A NodeRef with AVM info stuffed inside.
- */
- public static NodeRef ToNodeRef(int version, String avmPath)
- {
- String [] pathParts = AVMUtil.splitPath(avmPath);
- while (pathParts[1].endsWith(AVMUtil.AVM_PATH_SEPARATOR) && pathParts[1].length() > 1)
- {
- pathParts[1] = pathParts[1].substring(0, pathParts[1].length() - 1);
- }
- StoreRef storeRef = ToStoreRef(pathParts[0]);
- String translated = version + pathParts[1];
- translated = translated.replaceAll("/+", "|");
- return new NodeRef(storeRef, translated);
- }
-
- /**
- * Get a StoreRef that corresponds to a given AVMStore name.
- * @param avmStore The name of the AVMStore.
- * @return A working StoreRef.
- */
- public static StoreRef ToStoreRef(String avmStore)
- {
- return new StoreRef(StoreRef.PROTOCOL_AVM, avmStore);
- }
-
- /**
- * Convert a NodeRef into a version, AVMPath pair.
- * @param nodeRef The NodeRef to convert.
- * @return An Integer, String array.
- */
- public static Pair ToAVMVersionPath(NodeRef nodeRef)
- {
- StoreRef store = nodeRef.getStoreRef();
- String translated = nodeRef.getId();
-
- if (translated.indexOf('|') != -1)
- {
- // we assume that this is the new style avm path
- translated = translated.replace('|', AVMUtil.AVM_PATH_SEPARATOR_CHAR);
- }
- else
- {
- // this is the old style avm path
- translated = translated.replace(';', AVMUtil.AVM_PATH_SEPARATOR_CHAR);
- }
- int off = translated.indexOf(AVMUtil.AVM_PATH_SEPARATOR_CHAR);
- if (off == -1)
- {
- fgLogger.error(translated);
- throw new AVMException("Bad Node Reference: " + nodeRef.getId());
- }
- int version = Integer.parseInt(translated.substring(0, off));
- String path = translated.substring(off);
- return new Pair(version, AVMUtil.buildAVMPath(store.getIdentifier(), path));
- }
-
- /**
- * Extend an already valid AVM path by one more component.
- * @param path The starting AVM path.
- * @param name The name to add to it.
- * @return The extended path.
- */
- public static String ExtendAVMPath(String path, String name)
- {
- return AVMUtil.extendAVMPath(path, name);
- }
-
- /**
- * Split a path into its parent path and its base name.
- * @param path The initial AVM path.
- * @return An array of 2 Strings containing the parent path and the base
- * name.
- */
- public static String[] SplitBase(String path)
- {
- return AVMUtil.splitBase(path);
- }
-
- /**
- * Normalize an AVM path.
- * @param path The incoming path.
- * @return The normalized path.
- *
- * @deprecated see org.alfresco.repo.avm.util.AVMUtil.normalizePath
- */
- public static String NormalizePath(String path)
- {
- return AVMUtil.normalizePath(path);
- }
-}
diff --git a/source/java/org/alfresco/repo/avm/AVMNodeService.java b/source/java/org/alfresco/repo/avm/AVMNodeService.java
deleted file mode 100644
index 1bc231e19b..0000000000
--- a/source/java/org/alfresco/repo/avm/AVMNodeService.java
+++ /dev/null
@@ -1,2090 +0,0 @@
-/*
- * Copyright (C) 2005-2010 Alfresco Software Limited.
- *
- * This file is part of Alfresco
- *
- * Alfresco 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 3 of the License, or
- * (at your option) any later version.
- *
- * Alfresco 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.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with Alfresco. If not, see . */
-
-package org.alfresco.repo.avm;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.SortedMap;
-
-import org.alfresco.model.ContentModel;
-import org.alfresco.model.WCMModel;
-import org.alfresco.repo.avm.util.AVMUtil;
-import org.alfresco.repo.domain.PropertyValue;
-import org.alfresco.repo.node.AbstractNodeServiceImpl;
-import org.alfresco.service.cmr.avm.AVMException;
-import org.alfresco.service.cmr.avm.AVMExistsException;
-import org.alfresco.service.cmr.avm.AVMNodeDescriptor;
-import org.alfresco.service.cmr.avm.AVMNotFoundException;
-import org.alfresco.service.cmr.avm.AVMService;
-import org.alfresco.service.cmr.avm.AVMStoreDescriptor;
-import org.alfresco.service.cmr.avm.AVMWrongTypeException;
-import org.alfresco.service.cmr.dictionary.AspectDefinition;
-import org.alfresco.service.cmr.dictionary.ClassDefinition;
-import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
-import org.alfresco.service.cmr.dictionary.DictionaryException;
-import org.alfresco.service.cmr.dictionary.InvalidAspectException;
-import org.alfresco.service.cmr.dictionary.InvalidTypeException;
-import org.alfresco.service.cmr.dictionary.PropertyDefinition;
-import org.alfresco.service.cmr.dictionary.TypeDefinition;
-import org.alfresco.service.cmr.repository.AssociationExistsException;
-import org.alfresco.service.cmr.repository.AssociationRef;
-import org.alfresco.service.cmr.repository.ChildAssociationRef;
-import org.alfresco.service.cmr.repository.ContentData;
-import org.alfresco.service.cmr.repository.CyclicChildRelationshipException;
-import org.alfresco.service.cmr.repository.InvalidChildAssociationRefException;
-import org.alfresco.service.cmr.repository.InvalidNodeRefException;
-import org.alfresco.service.cmr.repository.InvalidStoreRefException;
-import org.alfresco.service.cmr.repository.NodeRef;
-import org.alfresco.service.cmr.repository.NodeService;
-import org.alfresco.service.cmr.repository.Path;
-import org.alfresco.service.cmr.repository.StoreExistsException;
-import org.alfresco.service.cmr.repository.StoreRef;
-import org.alfresco.service.cmr.repository.datatype.TypeConversionException;
-import org.alfresco.service.namespace.NamespaceService;
-import org.alfresco.service.namespace.QName;
-import org.alfresco.service.namespace.QNamePattern;
-import org.alfresco.util.Pair;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * NodeService implementing facade over AVMService.
- * @author britt
- */
-public class AVMNodeService extends AbstractNodeServiceImpl implements NodeService
-{
- private static Log logger = LogFactory.getLog(AVMNodeService.class);
-
- /**
- * Flag for whether policy callbacks are made.
- */
- private boolean fInvokePolicies = false;
-
- /**
- * Reference to AVMService.
- */
- private AVMService fAVMService;
-
- /**
- * Set the AVMService. For Spring.
- * @param service The AVMService instance.
- */
- public void setAvmService(AVMService service)
- {
- fAVMService = service;
- }
-
- /**
- * Default constructor.
- */
- public AVMNodeService()
- {
- }
-
- public void setInvokePolicies(boolean invoke)
- {
- fInvokePolicies = invoke;
- }
-
- /**
- * Helper method to convert the Serializable
value into a full,
- * persistable {@link PropertyValue}.
- *
- * Where the property definition is null, the value will take on the
- * {@link DataTypeDefinition#ANY generic ANY} value.
- *
- * Where the property definition specifies a multi-valued property but the
- * value provided is not a collection, the value will be wrapped in a collection.
- *
- * @param propertyDef the property dictionary definition, may be null
- * @param value the value, which will be converted according to the definition -
- * may be null
- * @return Returns the persistable property value
- */
- protected PropertyValue makePropertyValue(PropertyDefinition propertyDef, Serializable value)
- {
- // get property attributes
- QName propertyTypeQName = null;
- if (propertyDef == null) // property not recognised
- {
- // allow it for now - persisting excess properties can be useful sometimes
- propertyTypeQName = DataTypeDefinition.ANY;
- }
- else
- {
- propertyTypeQName = propertyDef.getDataType().getName();
- // check that multi-valued properties are allowed
- boolean isMultiValued = propertyDef.isMultiValued();
- if (isMultiValued && !(value instanceof Collection>))
- {
- if (value != null)
- {
- // put the value into a collection
- // the implementation gives back a Serializable list
- value = (Serializable) Collections.singletonList(value);
- }
- }
- else if (!isMultiValued && (value instanceof Collection>))
- {
- // we only allow this case if the property type is ANY
- if (!propertyTypeQName.equals(DataTypeDefinition.ANY))
- {
- throw new DictionaryException(
- "A single-valued property of this type may not be a collection: \n" +
- " Property: " + propertyDef + "\n" +
- " Type: " + propertyTypeQName + "\n" +
- " Value: " + value);
- }
- }
- }
- try
- {
- PropertyValue propertyValue = new PropertyValue(propertyTypeQName, value);
- // done
- return propertyValue;
- }
- catch (TypeConversionException e)
- {
- throw new TypeConversionException(
- "The property value is not compatible with the type defined for the property: \n" +
- " property: " + (propertyDef == null ? "unknown" : propertyDef) + "\n" +
- " value: " + value + "\n" +
- " value type: " + value.getClass(),
- e);
- }
- }
-
- /**
- * Extracts the externally-visible property from the {@link PropertyValue propertyValue}.
- *
- * @param propertyDef the model property definition - may be null
- * @param propertyValue the persisted property
- * @return Returns the value of the property in the format dictated by the property
- * definition, or null if the property value is null
- */
- protected Serializable makeSerializableValue(PropertyDefinition propertyDef, PropertyValue propertyValue)
- {
- if (propertyValue == null)
- {
- return null;
- }
- // get property attributes
- QName propertyTypeQName = null;
- if (propertyDef == null)
- {
- // allow this for now
- propertyTypeQName = DataTypeDefinition.ANY;
- }
- else
- {
- propertyTypeQName = propertyDef.getDataType().getName();
- }
- try
- {
- Serializable value = propertyValue.getValue(propertyTypeQName);
- // done
- return value;
- }
- catch (TypeConversionException e)
- {
- throw new TypeConversionException(
- "The property value is not compatible with the type defined for the property: \n" +
- " property: " + (propertyDef == null ? "unknown" : propertyDef) + "\n" +
- " property value: " + propertyValue,
- e);
- }
- }
-
- /**
- * Gets a list of all available node store references
- *
- * @return Returns a list of store references
- */
- public List getStores()
- {
- /* Sparta: disable/remove WCM/AVM
- // For AVM stores we fake up StoreRefs.
- List stores = fAVMService.getStores();
- List result = new ArrayList();
- for (AVMStoreDescriptor desc : stores)
- {
- String name = desc.getName();
- result.add(new StoreRef(StoreRef.PROTOCOL_AVM, name));
- }
- return result;
- */
- return Collections.emptyList();
- }
-
- /**
- * Create a new AVM store.
- * @param protocol the implementation protocol
- * @param identifier the protocol-specific identifier
- * @return Returns a reference to the store
- * @throws StoreExistsException
- */
- public StoreRef createStore(String protocol, String identifier) throws StoreExistsException
- {
- StoreRef result = new StoreRef(StoreRef.PROTOCOL_AVM, identifier);
- // invokeBeforeCreateStore(ContentModel.TYPE_STOREROOT, result);
- try
- {
- fAVMService.createStore(identifier);
- NodeRef rootRef = getRootNode(result);
- addAspect(rootRef, ContentModel.ASPECT_ROOT,
- Collections.emptyMap());
- // invokeOnCreateStore(rootRef);
- return result;
- }
- catch (AVMExistsException e)
- {
- throw new StoreExistsException(result, e);
- }
- }
-
- /**
- * @throws UnsupportedOperationException Always
- */
- public void deleteStore(StoreRef storeRef) throws InvalidStoreRefException
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Does the indicated store exist?
- * @param storeRef a reference to the store to look for
- * @return Returns true if the store exists, otherwise false
- */
- public boolean exists(StoreRef storeRef)
- {
- return fAVMService.getStore(storeRef.getIdentifier()) != null;
- }
-
- /**
- * @param nodeRef a reference to the node to look for
- * @return Returns true if the node exists, otherwise false
- */
- public boolean exists(NodeRef nodeRef)
- {
- Pair avmInfo = AVMNodeConverter.ToAVMVersionPath(nodeRef);
- int version = avmInfo.getFirst();
- String avmPath = avmInfo.getSecond();
- return fAVMService.lookup(version, avmPath) != null;
- }
-
- /**
- * Gets the ID of the last transaction that caused the node to change. This includes
- * deletions, so it is possible that the node being referenced no longer exists.
- * If the node never existed, then null is returned.
- *
- * @param nodeRef a reference to a current or previously existing node
- * @return Returns the status of the node, or null if the node never existed
- */
- public NodeRef.Status getNodeStatus(NodeRef nodeRef)
- {
- // TODO Need to find out if this is important and if so
- // need to capture Transaction IDs.
- return new NodeRef.Status(null, nodeRef, "Unknown", null, !exists(nodeRef));
- }
-
- /**
- * @throws UnsupportedOperationException always
- */
- @Override
- public NodeRef getNodeRef(Long nodeId)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @param storeRef a reference to an existing store
- * @return Returns a reference to the root node of the store
- * @throws InvalidStoreRefException if the store could not be found
- */
- public NodeRef getRootNode(StoreRef storeRef) throws InvalidStoreRefException
- {
- String storeName = storeRef.getIdentifier();
- if (fAVMService.getStore(storeName) != null)
- {
- return AVMNodeConverter.ToNodeRef(-1, storeName + ":/");
- }
- else
- {
- throw new InvalidStoreRefException(storeName +":/" + " not found.", storeRef);
- }
- }
-
- public Set getAllRootNodes(StoreRef storeRef)
- {
- return Collections.singleton(getRootNode(storeRef));
- }
-
- /**
- * @see #createNode(NodeRef, QName, QName, QName, Map)
- */
- public ChildAssociationRef createNode(
- NodeRef parentRef,
- QName assocTypeQName,
- QName assocQName,
- QName nodeTypeQName)
- throws InvalidNodeRefException, InvalidTypeException
- {
- return createNode(parentRef,
- assocTypeQName,
- assocQName,
- nodeTypeQName,
- new HashMap());
- }
-
- /**
- * Creates a new, non-abstract, real node as a primary child of the given parent node.
- *
- * @param parentRef the parent node
- * @param assocTypeQName the type of the association to create. This is used
- * for verification against the data dictionary.
- * @param assocQName the qualified name of the association
- * @param nodeTypeQName a reference to the node type
- * @param properties optional map of properties to keyed by their qualified names
- * @return Returns a reference to the newly created child association
- * @throws InvalidNodeRefException if the parent reference is invalid
- * @throws InvalidTypeException if the node type reference is not recognised
- *
- * @see org.alfresco.service.cmr.dictionary.DictionaryService
- */
- @SuppressWarnings("deprecation")
- public ChildAssociationRef createNode(
- NodeRef parentRef,
- QName assocTypeQName,
- QName assocQName,
- QName nodeTypeQName,
- Map properties)
- throws InvalidNodeRefException, InvalidTypeException
- {
- // AVM stores only allow simple child associations.
- if (!assocTypeQName.equals(ContentModel.ASSOC_CONTAINS))
- {
- throw new InvalidTypeException(assocTypeQName);
- }
- String nodeName = assocQName.getLocalName();
- Pair avmVersionPath = AVMNodeConverter.ToAVMVersionPath(parentRef);
- int version = avmVersionPath.getFirst();
- if (version >= 0)
- {
- throw new InvalidNodeRefException("Read only store.", parentRef);
- }
- String avmPath = avmVersionPath.getSecond();
- // Invoke policy behavior.
- // invokeBeforeUpdateNode(parentRef);
- // invokeBeforeCreateNode(parentRef, assocTypeQName, assocQName, nodeTypeQName);
- // Look up the type definition in the dictionary.
- TypeDefinition nodeTypeDef = dictionaryService.getType(nodeTypeQName);
- // Do the creates for supported types, or error out.
- try
- {
- if (nodeTypeQName.equals(WCMModel.TYPE_AVM_PLAIN_FOLDER) ||
- nodeTypeQName.equals(ContentModel.TYPE_FOLDER))
- {
- fAVMService.createDirectory(avmPath, nodeName);
- }
- else if (nodeTypeQName.equals(WCMModel.TYPE_AVM_PLAIN_CONTENT) ||
- nodeTypeQName.equals(ContentModel.TYPE_CONTENT))
- {
- OutputStream os = fAVMService.createFile(avmPath, nodeName);
- try
- {
- if (os != null) { os.close(); }
- }
- catch (IOException ioe)
- {
- logger.warn("Failed to close output stream when creating file '"+AVMUtil.extendAVMPath(avmPath, nodeName)+"'"+ioe.getMessage());
- }
- }
- else if (nodeTypeQName.equals(WCMModel.TYPE_AVM_LAYERED_CONTENT))
- {
- NodeRef indirection = (NodeRef)properties.get(WCMModel.PROP_AVM_FILE_INDIRECTION);
- if (indirection == null)
- {
- throw new InvalidTypeException("No Indirection Property", nodeTypeQName);
- }
- Pair indVersionPath = AVMNodeConverter.ToAVMVersionPath(indirection);
- fAVMService.createLayeredFile(indVersionPath.getSecond(), avmPath, nodeName);
- }
- else if (nodeTypeQName.equals(WCMModel.TYPE_AVM_LAYERED_FOLDER))
- {
- NodeRef indirection = (NodeRef)properties.get(WCMModel.PROP_AVM_DIR_INDIRECTION);
- if (indirection == null)
- {
- throw new InvalidTypeException("No Indirection Property.", nodeTypeQName);
- }
- Pair indVersionPath = AVMNodeConverter.ToAVMVersionPath(indirection);
- fAVMService.createLayeredDirectory(indVersionPath.getSecond(), avmPath, nodeName);
- }
- else
- {
- throw new InvalidTypeException("Invalid node type for AVM.", nodeTypeQName);
- }
- properties.putAll(getDefaultProperties(nodeTypeDef));
- addDefaultAspects(nodeTypeDef, avmPath, properties);
- }
- catch (AVMNotFoundException e)
- {
- throw new InvalidNodeRefException(avmPath + " not found.", parentRef);
- }
- catch (AVMExistsException e)
- {
- throw new InvalidNodeRefException("Child " + nodeName + " exists", parentRef);
- }
- String newAVMPath = AVMNodeConverter.ExtendAVMPath(avmPath, nodeName);
- NodeRef childRef = AVMNodeConverter.ToNodeRef(-1, newAVMPath);
- properties.putAll(getDefaultProperties(nodeTypeDef));
- addDefaultAspects(nodeTypeDef, newAVMPath, properties);
- Map props = new HashMap();
- for (Map.Entry entry : properties.entrySet())
- {
- QName propertyQName = entry.getKey();
- if (isBuiltInProperty(propertyQName))
- {
- continue;
- }
- Serializable value = entry.getValue();
- PropertyDefinition propertyDef = dictionaryService.getProperty(propertyQName);
- PropertyValue propertyValue = makePropertyValue(propertyDef, value);
- props.put(propertyQName, propertyValue);
- }
- fAVMService.setNodeProperties(newAVMPath, props);
- ChildAssociationRef ref =
- new ChildAssociationRef(assocTypeQName,
- parentRef,
- assocQName,
- childRef,
- true,
- -1);
-// invokeOnCreateNode(ref);
-// invokeOnUpdateNode(parentRef);
-// if (properties.size() != 0)
-// {
-// invokeOnUpdateProperties(childRef, new HashMap(), properties);
-// }
- return ref;
- }
-
- /**
- * Moves the primary location of the given node.
- *
- * This involves changing the node's primary parent and possibly the name of the
- * association referencing it.
- *
- * If the new parent is in a different store from the original, then the entire
- * node hierarchy is moved to the new store. Inter-store associations are not
- * affected.
- *
- * @param nodeToMoveRef the node to move
- * @param newParentRef the new parent of the moved node
- * @param assocTypeQName the type of the association to create. This is used
- * for verification against the data dictionary.
- * @param assocQName the qualified name of the new child association
- * @return Returns a reference to the newly created child association
- * @throws InvalidNodeRefException if either the parent node or move node reference is invalid
- * @throws CyclicChildRelationshipException if the child partakes in a cyclic relationship after the add
- *
- * @see #getPrimaryParent(NodeRef)
- */
- public ChildAssociationRef moveNode(
- NodeRef nodeToMoveRef,
- NodeRef newParentRef,
- QName assocTypeQName,
- QName assocQName)
- throws InvalidNodeRefException
- {
- // AVM stores only allow simple child associations.
- if (!assocTypeQName.equals(ContentModel.ASSOC_CONTAINS))
- {
- throw new InvalidTypeException(assocTypeQName);
- }
- // Extract the parts from the source.
- Pair src = AVMNodeConverter.ToAVMVersionPath(nodeToMoveRef);
- int srcVersion = src.getFirst();
- if (srcVersion >= 0)
- {
- throw new InvalidNodeRefException("Read Only Store.", nodeToMoveRef);
- }
- String srcPath = src.getSecond();
- String [] splitSrc = null;
- try
- {
- splitSrc = AVMNodeConverter.SplitBase(srcPath);
- }
- catch (AVMException e)
- {
- throw new InvalidNodeRefException("Invalid src path.", nodeToMoveRef);
- }
- String srcParent = splitSrc[0];
- if (srcParent == null)
- {
- throw new InvalidNodeRefException("Cannot rename root node.", nodeToMoveRef);
- }
- String srcName = splitSrc[1];
- // Extract and setup the parts of the destination.
- Pair dst = AVMNodeConverter.ToAVMVersionPath(newParentRef);
- if (dst.getFirst() >= 0)
- {
- throw new InvalidNodeRefException("Read Only Store.", newParentRef);
- }
- String dstParent = dst.getSecond();
- String dstName = assocQName.getLocalName();
- // TODO Invoke policy behavior. Not quite sure how to translate this.
- NodeRef oldParentRef = AVMNodeConverter.ToNodeRef(-1, srcParent);
- ChildAssociationRef oldAssocRef =
- new ChildAssociationRef(assocTypeQName,
- oldParentRef,
- QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, srcName),
- nodeToMoveRef,
- true,
- -1);
-// invokeBeforeDeleteChildAssociation(oldAssocRef);
- String dstPath = AVMNodeConverter.ExtendAVMPath(dstParent, dstName);
- NodeRef newChildRef = AVMNodeConverter.ToNodeRef(-1, dstPath);
-// invokeBeforeUpdateNode(oldParentRef);
-// invokeBeforeUpdateNode(newParentRef);
- // Actually perform the rename and return a pseudo
- // ChildAssociationRef.
- try
- {
- fAVMService.rename(srcParent, srcName, dstParent, dstName);
- ChildAssociationRef newAssocRef =
- new ChildAssociationRef(assocTypeQName,
- newParentRef,
- assocQName,
- newChildRef,
- true,
- -1);
- invokeOnMoveNode(oldAssocRef, newAssocRef);
-// invokeOnCreateChildAssociation(newAssocRef);
-// invokeOnDeleteChildAssociation(oldAssocRef);
-// invokeOnUpdateNode(oldParentRef);
-// invokeOnUpdateNode(newParentRef);
- return newAssocRef;
- }
- catch (AVMNotFoundException e)
- {
- throw new InvalidNodeRefException("Non existent node.", nodeToMoveRef);
- }
- catch (AVMExistsException e)
- {
- throw new InvalidNodeRefException("Target already exists.", newParentRef);
- }
- catch (AVMException e)
- {
- throw new InvalidNodeRefException("Illegal move.", nodeToMoveRef);
- }
- }
-
- /**
- * Set the ordering index of the child association. This affects the ordering of
- * of the return values of methods that return a set of children or child
- * associations.
- *
- * @param childAssocRef the child association that must be moved in the order
- * @param index an arbitrary index that will affect the return order
- *
- * @see #getChildAssocs(NodeRef)
- * @see #getChildAssocs(NodeRef, QNamePattern, QNamePattern)
- * @see ChildAssociationRef#getNthSibling()
- */
- public void setChildAssociationIndex(
- ChildAssociationRef childAssocRef,
- int index)
- throws InvalidChildAssociationRefException
- {
- // TODO We'll keep this a no-op unless there's a
- // compelling reason to implement this capability
- // for the AVM repository.
- }
-
- /**
- * @param nodeRef
- * @return Returns the type name
- * @throws InvalidNodeRefException if the node could not be found
- *
- * @see org.alfresco.service.cmr.dictionary.DictionaryService
- */
- public QName getType(NodeRef nodeRef) throws InvalidNodeRefException
- {
- Pair avmVersionPath = AVMNodeConverter.ToAVMVersionPath(nodeRef);
- AVMNodeDescriptor desc = fAVMService.lookup(avmVersionPath.getFirst(),
- avmVersionPath.getSecond());
- if (desc == null)
- {
- throw new InvalidNodeRefException(avmVersionPath.getSecond() + " not found.", nodeRef);
- }
- if (desc.isPlainDirectory())
- {
- return WCMModel.TYPE_AVM_PLAIN_FOLDER;
- }
- else if (desc.isPlainFile())
- {
- return WCMModel.TYPE_AVM_PLAIN_CONTENT;
- }
- else if (desc.isLayeredDirectory())
- {
- return WCMModel.TYPE_AVM_LAYERED_FOLDER;
- }
- else
- {
- return WCMModel.TYPE_AVM_LAYERED_CONTENT;
- }
- }
-
- /**
- * Re-sets the type of the node. Can be called in order specialise a node to a sub-type.
- *
- * This should be used with caution since calling it changes the type of the node and thus
- * implies a different set of aspects, properties and associations. It is the calling codes
- * responsibility to ensure that the node is in a approriate state after changing the type.
- *
- * @param nodeRef the node reference
- * @param typeQName the type QName
- *
- * @since 1.1
- */
- public void setType(NodeRef nodeRef, QName typeQName) throws InvalidNodeRefException
- {
- throw new UnsupportedOperationException("AVM Types are immutable.");
- }
-
- /**
- * Applies an aspect to the given node. After this method has been called,
- * the node with have all the aspect-related properties present
- *
- * @param nodeRef
- * @param aspectTypeQName the aspect to apply to the node
- * @param aspectProperties a minimum of the mandatory properties required for
- * the aspect
- * @throws InvalidNodeRefException
- * @throws InvalidAspectException if the class reference is not to a valid aspect
- *
- * @see org.alfresco.service.cmr.dictionary.DictionaryService#getAspect(QName)
- * @see org.alfresco.service.cmr.dictionary.ClassDefinition#getProperties()
- */
- public void addAspect(
- NodeRef nodeRef,
- QName aspectTypeQName,
- Map aspectProperties)
- throws InvalidNodeRefException, InvalidAspectException
- {
- // Check that the aspect exists.
- AspectDefinition aspectDef = this.dictionaryService.getAspect(aspectTypeQName);
- if (aspectDef == null)
- {
- throw new InvalidAspectException("The aspect is invalid: " + aspectTypeQName,
- aspectTypeQName);
- }
- // Invoke policy behaviors.
-// invokeBeforeUpdateNode(nodeRef);
-// invokeBeforeAddAspect(nodeRef, aspectTypeQName);
- // Crack the nodeRef.
- Pair avmVersionPath = AVMNodeConverter.ToAVMVersionPath(nodeRef);
- int version = avmVersionPath.getFirst();
- if (version >= 0)
- {
- throw new InvalidNodeRefException("Read Only node.", nodeRef);
- }
- String avmPath = avmVersionPath.getSecond();
- // Accumulate properties.
- Map properties = new HashMap();
- // Add the supplied properties.
- if (aspectProperties != null)
- {
- properties.putAll(aspectProperties);
- }
- // Now set any unspecified default properties for the aspect.
- Map defaultProperties = getDefaultProperties(aspectDef);
- properties.putAll(defaultProperties);
- // Now add any cascading aspects.
- addDefaultAspects(aspectDef, avmPath, properties);
- // Set the property values on the AVM Node.
- if (properties.size() != 0)
- {
- Map props = new HashMap();
- for (Map.Entry entry : properties.entrySet())
- {
- QName propertyQName = entry.getKey();
- if (isBuiltInProperty(propertyQName))
- {
- continue;
- }
- Serializable value = entry.getValue();
- PropertyDefinition propertyDef = dictionaryService.getProperty(propertyQName);
- PropertyValue propertyValue = makePropertyValue(propertyDef, value);
- props.put(propertyQName, propertyValue);
- }
- if (props.size() != 0)
- {
- fAVMService.setNodeProperties(avmPath, props);
- }
- }
- if (isBuiltinAspect(aspectTypeQName))
- {
- // No more work to do in this case.
- return;
- }
- try
- {
- fAVMService.addAspect(avmPath, aspectTypeQName);
- // Invoke policy behaviors.
-// invokeOnUpdateNode(nodeRef);
-// invokeOnAddAspect(nodeRef, aspectTypeQName);
- }
- catch (AVMNotFoundException e)
- {
- throw new InvalidNodeRefException(nodeRef);
- }
- }
-
- /**
- * Add any aspects that are mandatory for the ClassDefinition.
- * @param classDef The ClassDefinition.
- * @param path The path to the AVMNode.
- * @param properties The in/out map of accumulated properties.
- */
- private void addDefaultAspects(ClassDefinition classDef, String path,
- Map properties)
- {
- NodeRef nodeRef = AVMNodeConverter.ToNodeRef(-1, path);
- // Get mandatory aspects.
- List defaultAspectDefs = classDef.getDefaultAspects();
- // add all the aspects (and there dependent aspects recursively).
- for (AspectDefinition def : defaultAspectDefs)
- {
-// invokeBeforeAddAspect(nodeRef, def.getName());
- addAspect(nodeRef, def.getName(), Collections.emptyMap());
- properties.putAll(getDefaultProperties(def));
-// invokeOnAddAspect(nodeRef, def.getName());
- // recurse
- addDefaultAspects(def, path, properties);
- }
- }
-
- /**
- * Remove an aspect and all related properties from a node
- *
- * @param nodeRef
- * @param aspectTypeQName the type of aspect to remove
- * @throws InvalidNodeRefException if the node could not be found
- * @throws InvalidAspectException if the the aspect is unknown or if the
- * aspect is mandatory for the class of the node
- */
- public void removeAspect(NodeRef nodeRef, QName aspectTypeQName)
- throws InvalidNodeRefException, InvalidAspectException
- {
- // Invoke policy behaviors.
-// invokeBeforeUpdateNode(nodeRef);
-// invokeBeforeRemoveAspect(nodeRef, aspectTypeQName);
- AspectDefinition def = dictionaryService.getAspect(aspectTypeQName);
- if (def == null)
- {
- throw new InvalidAspectException(aspectTypeQName);
- }
- if (isBuiltinAspect(aspectTypeQName))
- {
- // TODO shouldn't we be throwing some kind of exception here.
- return;
- }
- Pair avmVersionPath = AVMNodeConverter.ToAVMVersionPath(nodeRef);
- int version = avmVersionPath.getFirst();
- if (version >= 0)
- {
- throw new InvalidNodeRefException("Read Only Node.", nodeRef);
- }
- String path = avmVersionPath.getSecond();
- try
- {
- if (fAVMService.hasAspect(-1, path, aspectTypeQName))
- {
- fAVMService.removeAspect(path, aspectTypeQName);
- Map