Search in sources :

Example 1 with FileExistsException

use of org.alfresco.jlan.server.filesys.FileExistsException in project alfresco-repository by Alfresco.

the class CifsHelper method relinkNode.

/**
 * Relink the content data from a new node to an existing node to preserve the version history.
 *
 * @param tempNodeRef temp nodeRef
 * @param nodeToMoveRef NodeRef
 * @param newParentNodeRef NodeRef
 * @param newName new name
 */
public void relinkNode(NodeRef tempNodeRef, NodeRef nodeToMoveRef, NodeRef newParentNodeRef, String newName) throws FileNotFoundException, FileExistsException {
    // Get the properties for the old and new nodes
    org.alfresco.service.cmr.model.FileInfo tempFileInfo = fileFolderService.getFileInfo(tempNodeRef);
    org.alfresco.service.cmr.model.FileInfo fileToMoveInfo = fileFolderService.getFileInfo(nodeToMoveRef);
    // Save the current name of the old node
    String tempName = tempFileInfo.getName();
    try {
        // Rename operation will add or remove the sys:temporary aspect appropriately
        // rename temp file to the new name
        fileFolderService.rename(tempNodeRef, newName);
        // rename new file to old name
        fileFolderService.rename(nodeToMoveRef, tempName);
    } catch (org.alfresco.service.cmr.model.FileNotFoundException e) {
        throw new FileNotFoundException(e.getMessage());
    } catch (org.alfresco.service.cmr.model.FileExistsException e) {
        throw new FileExistsException(e.getMessage());
    }
    if (!tempFileInfo.isFolder() && !fileToMoveInfo.isFolder()) {
        // swap the content between the two
        ContentData oldContentData = tempFileInfo.getContentData();
        if (oldContentData == null) {
            String mimetype = mimetypeService.guessMimetype(tempName);
            oldContentData = ContentData.setMimetype(null, mimetype);
        }
        ContentData newContentData = fileToMoveInfo.getContentData();
        // Reset the mime type
        // TODO Pass the content along when guessing the mime type, so we're more accurate
        String mimetype = mimetypeService.guessMimetype(newName);
        newContentData = ContentData.setMimetype(newContentData, mimetype);
        nodeService.setProperty(tempNodeRef, ContentModel.PROP_CONTENT, newContentData);
        nodeService.setProperty(nodeToMoveRef, ContentModel.PROP_CONTENT, oldContentData);
    }
}
Also used : ContentData(org.alfresco.service.cmr.repository.ContentData) FileNotFoundException(java.io.FileNotFoundException) FileInfo(org.alfresco.service.cmr.model.FileInfo) FileExistsException(org.alfresco.jlan.server.filesys.FileExistsException)

Example 2 with FileExistsException

use of org.alfresco.jlan.server.filesys.FileExistsException in project alfresco-repository by Alfresco.

the class ContentDiskDriver method createFile.

/**
 * Create a new file on the file system.
 *
 * <p>
 * WARNING : side effect - closes current transaction context.
 *
 * @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(SrvSession sess, final TreeConnection tree, final FileOpenParams params) throws IOException {
    final ContentContext ctx = (ContentContext) tree.getContext();
    try {
        // Access the repository in a retryable write transaction
        Pair<String, NodeRef> result = doInWriteTransaction(sess, new CallableIO<Pair<String, NodeRef>>() {

            public Pair<String, NodeRef> call() throws IOException {
                // Get the device root
                NodeRef deviceRootNodeRef = ctx.getRootNode();
                String path = params.getPath();
                String parentPath = null;
                if (ctx.hasStateCache()) {
                    // See if the parent folder has a file state, we can avoid having to walk the path
                    String[] paths = FileName.splitPath(path);
                    if (paths[0] != null && paths[0].length() > 1) {
                        // Find the node ref for the folder being searched
                        NodeRef nodeRef = getNodeForPath(tree, paths[0]);
                        if (nodeRef != null) {
                            deviceRootNodeRef = nodeRef;
                            path = paths[1];
                            if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_FILE))
                                logger.debug("Create file using cached noderef for path " + paths[0]);
                        }
                        parentPath = paths[0];
                    }
                }
                // Create it - the path will be created, if necessary
                if (logger.isDebugEnabled()) {
                    logger.debug("create new file" + path);
                }
                NodeRef nodeRef = null;
                try {
                    nodeRef = cifsHelper.createNode(deviceRootNodeRef, path, ContentModel.TYPE_CONTENT);
                    nodeService.addAspect(nodeRef, ContentModel.ASPECT_NO_CONTENT, null);
                } catch (FileExistsException ex) {
                    nodeRef = cifsHelper.getNodeRef(deviceRootNodeRef, path);
                    if (!nodeService.hasAspect(nodeRef, ContentModel.ASPECT_SOFT_DELETE)) {
                        throw ex;
                    }
                }
                return new Pair<String, NodeRef>(parentPath, nodeRef);
            }
        });
        // Get or create the file state for the parent folder
        FileState parentState = null;
        String parentPath = result.getFirst();
        if (parentPath != null) {
            parentState = getStateForPath(tree, parentPath);
            if (parentState == null && ctx.hasStateCache())
                parentState = ctx.getStateCache().findFileState(parentPath, true);
        }
        NodeRef nodeRef = result.getSecond();
        if (nodeRef != null && nodeService.hasAspect(nodeRef, ContentModel.ASPECT_SOFT_DELETE)) {
            nodeService.removeAspect(nodeRef, ContentModel.ASPECT_SOFT_DELETE);
        }
        // Create the network file
        ContentNetworkFile netFile = ContentNetworkFile.createFile(nodeService, contentService, mimetypeService, cifsHelper, result.getSecond(), params.getPath(), params.isReadOnlyAccess(), params.isAttributesOnlyAccess(), sess);
        // Always allow write access to a newly created file
        netFile.setGrantedAccess(NetworkFile.READWRITE);
        // Set the owner process id for this open file
        netFile.setProcessId(params.getProcessId());
        // Truncate the file so that the content stream is created
        netFile.truncateFile(0L);
        // Indicate the file is open
        netFile.setClosed(false);
        if (netFile != null) {
            long id = DefaultTypeConverter.INSTANCE.convert(Long.class, nodeService.getProperty(netFile.getNodeRef(), ContentModel.PROP_NODE_DBID));
            netFile.setFileId((int) (id & 0xFFFFFFFFL));
        }
        if (ctx.hasStateCache()) {
            FileState fstate = ctx.getStateCache().findFileState(params.getPath(), true);
            if (fstate != null) {
                // Save the file sharing mode, needs to be done before the open count is incremented
                fstate.setSharedAccess(params.getSharedAccess());
                fstate.setProcessId(params.getProcessId());
                // Indicate that the file is open
                fstate.setFileStatus(FileExists);
                fstate.incrementOpenCount();
                fstate.setFilesystemObject(result.getSecond());
                // Track the intial allocation size
                fstate.setAllocationSize(params.getAllocationSize());
                // Store the file state with the file
                netFile.setFileState(fstate);
                if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_FILE))
                    logger.debug("Create file, state=" + fstate);
            }
            if (parentState != null)
                parentState.updateModifyDateTime();
        }
        if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_FILE))
            logger.debug("Created file: path=" + params.getPath() + " file open parameters=" + params + " node=" + result.getSecond() + " network file=" + netFile);
        return netFile;
    } catch (org.alfresco.repo.security.permissions.AccessDeniedException ex) {
        if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_FILE))
            logger.debug("Create file - access denied, " + params.getFullPath());
        throw new AccessDeniedException("Create file " + params.getFullPath());
    } catch (ContentIOException ex) {
        if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_FILE))
            logger.debug("Create file - content I/O error, " + params.getFullPath());
        throw new DiskFullException("Create file " + params.getFullPath());
    } catch (RuntimeException ex) {
        if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_FILE))
            logger.debug("Create file error", ex);
        throw new IOException("Create file " + params.getFullPath(), ex);
    }
}
Also used : FileState(org.alfresco.jlan.server.filesys.cache.FileState) AccessDeniedException(org.alfresco.jlan.server.filesys.AccessDeniedException) ContentIOException(org.alfresco.service.cmr.repository.ContentIOException) IOException(java.io.IOException) ContentIOException(org.alfresco.service.cmr.repository.ContentIOException) NodeRef(org.alfresco.service.cmr.repository.NodeRef) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) DiskFullException(org.alfresco.jlan.server.filesys.DiskFullException) Pair(org.alfresco.util.Pair) FileExistsException(org.alfresco.jlan.server.filesys.FileExistsException)

Example 3 with FileExistsException

use of org.alfresco.jlan.server.filesys.FileExistsException in project alfresco-repository by Alfresco.

the class CifsHelper method createNode.

/**
 * Creates a file or directory using the given paths.
 * <p>
 * If the directory path doesn't exist, then all the parent directories will be created.
 * If the file path is <code>null</code>, then the file will not be created
 *
 * @param rootNodeRef the root node of the path
 * @param path the path to a node
 * @param typeQName type of fole
 * @return Returns a newly created file or folder node
 * @throws FileExistsException if the file or folder already exists
 */
public NodeRef createNode(NodeRef rootNodeRef, String path, QName typeQName) throws FileExistsException {
    // split the path up into its constituents
    StringTokenizer tokenizer = new StringTokenizer(path, FileName.DOS_SEPERATOR_STR, false);
    List<String> folderPathElements = new ArrayList<String>(10);
    String name = null;
    while (tokenizer.hasMoreTokens()) {
        String pathElement = tokenizer.nextToken();
        if (!tokenizer.hasMoreTokens()) {
            // the last token becomes the name
            name = pathElement;
        } else {
            // add the path element to the parent folder path
            folderPathElements.add(pathElement);
        }
    }
    // ensure that the folder path exists
    NodeRef parentFolderNodeRef = rootNodeRef;
    if (folderPathElements.size() > 0) {
        parentFolderNodeRef = FileFolderUtil.makeFolders(fileFolderService, rootNodeRef, folderPathElements, ContentModel.TYPE_FOLDER).getNodeRef();
    }
    try {
        NodeRef nodeRef = fileFolderService.create(parentFolderNodeRef, name, typeQName).getNodeRef();
        // done
        if (logger.isDebugEnabled()) {
            logger.debug("Created node: \n" + "   device root: " + rootNodeRef + "\n" + "   path: " + path + "\n" + "   type: " + typeQName + "\n" + "   new node: " + nodeRef);
        }
        return nodeRef;
    } catch (org.alfresco.service.cmr.model.FileExistsException e) {
        throw new FileExistsException(path);
    }
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) StringTokenizer(java.util.StringTokenizer) ArrayList(java.util.ArrayList) FileExistsException(org.alfresco.jlan.server.filesys.FileExistsException)

Example 4 with FileExistsException

use of org.alfresco.jlan.server.filesys.FileExistsException in project alfresco-repository by Alfresco.

the class ContentDiskDriverTest method testCreateFile.

/**
 * Test Create File
 */
public void testCreateFile() throws Exception {
    logger.debug("testCreatedFile");
    ServerConfiguration scfg = new ServerConfiguration("testServer");
    TestServer testServer = new TestServer("testServer", scfg);
    final SrvSession testSession = new TestSrvSession(666, testServer, "test", "remoteName");
    DiskSharedDevice share = getDiskSharedDevice();
    final TreeConnection testConnection = testServer.getTreeConnection(share);
    final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();
    class TestContext {

        NodeRef testNodeRef;
    }
    ;
    final TestContext testContext = new TestContext();
    /**
     * Step 1 : Create a new file in read/write mode and add some content.
     */
    int openAction = FileAction.CreateNotExist;
    final String FILE_NAME = "testCreateFileX.new";
    final String FILE_PATH = "\\" + FILE_NAME;
    FileOpenParams params = new FileOpenParams(FILE_PATH, openAction, AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
    final NetworkFile file = driver.createFile(testSession, testConnection, params);
    assertNotNull("file is null", file);
    assertFalse("file is read only, should be read-write", file.isReadOnly());
    assertFalse("file is not closed ", file.isClosed());
    RetryingTransactionCallback<Void> writeStuffCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            byte[] stuff = "Hello World".getBytes();
            driver.writeFile(testSession, testConnection, file, stuff, 0, stuff.length, 0);
            driver.closeFile(testSession, testConnection, file);
            return null;
        }
    };
    tran.doInTransaction(writeStuffCB);
    RetryingTransactionCallback<Void> validateCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            NodeRef companyHome = repositoryHelper.getCompanyHome();
            NodeRef newNode = nodeService.getChildByName(companyHome, ContentModel.ASSOC_CONTAINS, FILE_NAME);
            testContext.testNodeRef = newNode;
            assertNotNull("can't find new node", newNode);
            Serializable content = nodeService.getProperty(newNode, ContentModel.PROP_CONTENT);
            assertNotNull("content is null", content);
            return null;
        }
    };
    tran.doInTransaction(validateCB);
    // now validate that the new node is in the correct location and has the correct name
    FileInfo info = driver.getFileInformation(testSession, testConnection, FILE_PATH);
    assertNotNull("info is null", info);
    NodeRef n2 = getNodeForPath(testConnection, FILE_PATH);
    assertEquals("get Node For Path returned different node", testContext.testNodeRef, n2);
    /**
     * Step 2 : Negative Test Attempt to create the same file again
     */
    try {
        driver.createFile(testSession, testConnection, params);
        fail("File exists not detected");
    } catch (FileExistsException fe) {
    // expect to go here
    }
    // Clean up so we could run the test again
    driver.deleteFile(testSession, testConnection, FILE_PATH);
    /**
     * Step 3 : create a file in a new directory in read only mode
     */
    String FILE2_PATH = TEST_ROOT_DOS_PATH + FILE_PATH;
    FileOpenParams dirParams = new FileOpenParams(TEST_ROOT_DOS_PATH, openAction, AccessMode.ReadOnly, FileAttribute.NTDirectory, 0);
    driver.createDirectory(testSession, testConnection, dirParams);
    FileOpenParams file2Params = new FileOpenParams(FILE2_PATH, openAction, AccessMode.ReadOnly, FileAttribute.NTNormal, 0);
    NetworkFile file2 = driver.createFile(testSession, testConnection, file2Params);
    // clean up so we could run the test again
    driver.deleteFile(testSession, testConnection, FILE2_PATH);
}
Also used : Serializable(java.io.Serializable) SrvSession(org.alfresco.jlan.server.SrvSession) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) ServerConfiguration(org.alfresco.jlan.server.config.ServerConfiguration) NodeRef(org.alfresco.service.cmr.repository.NodeRef) FileOpenParams(org.alfresco.jlan.server.filesys.FileOpenParams) FileInfo(org.alfresco.jlan.server.filesys.FileInfo) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) TreeConnection(org.alfresco.jlan.server.filesys.TreeConnection) NetworkFile(org.alfresco.jlan.server.filesys.NetworkFile) DiskSharedDevice(org.alfresco.jlan.server.filesys.DiskSharedDevice) FileExistsException(org.alfresco.jlan.server.filesys.FileExistsException)

Aggregations

FileExistsException (org.alfresco.jlan.server.filesys.FileExistsException)4 NodeRef (org.alfresco.service.cmr.repository.NodeRef)3 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 Serializable (java.io.Serializable)1 ArrayList (java.util.ArrayList)1 StringTokenizer (java.util.StringTokenizer)1 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)1 SrvSession (org.alfresco.jlan.server.SrvSession)1 ServerConfiguration (org.alfresco.jlan.server.config.ServerConfiguration)1 AccessDeniedException (org.alfresco.jlan.server.filesys.AccessDeniedException)1 DiskFullException (org.alfresco.jlan.server.filesys.DiskFullException)1 DiskSharedDevice (org.alfresco.jlan.server.filesys.DiskSharedDevice)1 FileInfo (org.alfresco.jlan.server.filesys.FileInfo)1 FileOpenParams (org.alfresco.jlan.server.filesys.FileOpenParams)1 NetworkFile (org.alfresco.jlan.server.filesys.NetworkFile)1 TreeConnection (org.alfresco.jlan.server.filesys.TreeConnection)1 FileState (org.alfresco.jlan.server.filesys.cache.FileState)1 RetryingTransactionHelper (org.alfresco.repo.transaction.RetryingTransactionHelper)1 RetryingTransactionCallback (org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback)1