Search in sources :

Example 21 with FileNotFoundException

use of org.alfresco.service.cmr.model.FileNotFoundException in project alfresco-remote-api by Alfresco.

the class BulkFilesystemImportWebScript method executeImpl.

/**
 * @see org.springframework.extensions.webscripts.DeclarativeWebScript#executeImpl(org.springframework.extensions.webscripts.WebScriptRequest, org.springframework.extensions.webscripts.Status, org.springframework.extensions.webscripts.Cache)
 */
@Override
protected Map<String, Object> executeImpl(final WebScriptRequest request, final Status status, final Cache cache) {
    Map<String, Object> model = new HashMap<String, Object>();
    String targetNodeRefStr = null;
    String targetPath = null;
    String sourceDirectoryStr = null;
    @Deprecated String replaceExistingStr = null;
    String existingFileModeStr = null;
    String batchSizeStr = null;
    String numThreadsStr = null;
    String disableRulesStr = null;
    cache.setNeverCache(true);
    try {
        if (!bulkImporter.getStatus().inProgress()) {
            NodeRef targetNodeRef = null;
            File sourceDirectory = null;
            boolean replaceExisting = false;
            BulkImportParameters.ExistingFileMode existingFileMode = null;
            int batchSize = bulkImporter.getDefaultBatchSize();
            int numThreads = bulkImporter.getDefaultNumThreads();
            boolean disableRules = false;
            // Retrieve, validate and convert parameters
            targetNodeRefStr = request.getParameter(PARAMETER_TARGET_NODEREF);
            targetPath = request.getParameter(PARAMETER_TARGET_PATH);
            sourceDirectoryStr = request.getParameter(PARAMETER_SOURCE_DIRECTORY);
            replaceExistingStr = request.getParameter(PARAMETER_REPLACE_EXISTING);
            existingFileModeStr = request.getParameter(PARAMETER_EXISTING_FILE_MODE);
            batchSizeStr = request.getParameter(PARAMETER_BATCH_SIZE);
            numThreadsStr = request.getParameter(PARAMETER_NUM_THREADS);
            disableRulesStr = request.getParameter(PARAMETER_DISABLE_RULES);
            targetNodeRef = getTargetNodeRef(targetNodeRefStr, targetPath);
            if (sourceDirectoryStr == null || sourceDirectoryStr.trim().length() == 0) {
                throw new RuntimeException("Error: mandatory parameter '" + PARAMETER_SOURCE_DIRECTORY + "' was not provided.");
            }
            sourceDirectory = new File(sourceDirectoryStr.trim());
            if (replaceExistingStr != null && existingFileModeStr != null) {
                // parameters supplied.
                throw new IllegalStateException(String.format("Only one of these parameters may be used, not both: %s, %s", PARAMETER_REPLACE_EXISTING, PARAMETER_EXISTING_FILE_MODE));
            }
            if (replaceExistingStr != null && replaceExistingStr.trim().length() > 0) {
                replaceExisting = PARAMETER_VALUE_REPLACE_EXISTING.equals(replaceExistingStr);
            }
            if (existingFileModeStr != null && existingFileModeStr.trim().length() > 0) {
                existingFileMode = BulkImportParameters.ExistingFileMode.valueOf(existingFileModeStr);
            }
            if (disableRulesStr != null && disableRulesStr.trim().length() > 0) {
                disableRules = PARAMETER_VALUE_DISABLE_RULES.equals(disableRulesStr);
            }
            // Initiate the import
            NodeImporter nodeImporter = nodeImporterFactory.getNodeImporter(sourceDirectory);
            BulkImportParameters bulkImportParameters = new BulkImportParameters();
            if (numThreadsStr != null && numThreadsStr.trim().length() > 0) {
                try {
                    numThreads = Integer.parseInt(numThreadsStr);
                    if (numThreads < 1) {
                        throw new RuntimeException("Error: parameter '" + PARAMETER_NUM_THREADS + "' must be an integer > 0.");
                    }
                    bulkImportParameters.setNumThreads(numThreads);
                } catch (NumberFormatException e) {
                    throw new RuntimeException("Error: parameter '" + PARAMETER_NUM_THREADS + "' must be an integer > 0.");
                }
            }
            if (batchSizeStr != null && batchSizeStr.trim().length() > 0) {
                try {
                    batchSize = Integer.parseInt(batchSizeStr);
                    if (batchSize < 1) {
                        throw new RuntimeException("Error: parameter '" + PARAMETER_BATCH_SIZE + "' must be an integer > 0.");
                    }
                    bulkImportParameters.setBatchSize(batchSize);
                } catch (NumberFormatException e) {
                    throw new RuntimeException("Error: parameter '" + PARAMETER_BATCH_SIZE + "' must be an integer > 0.");
                }
            }
            if (existingFileMode != null) {
                bulkImportParameters.setExistingFileMode(existingFileMode);
            } else {
                // Fall back to the old/deprecated way.
                bulkImportParameters.setReplaceExisting(replaceExisting);
            }
            bulkImportParameters.setTarget(targetNodeRef);
            bulkImportParameters.setDisableRulesService(disableRules);
            bulkImporter.asyncBulkImport(bulkImportParameters, nodeImporter);
            // ACE-3047 fix, since bulk import is started asynchronously there is a chance that client
            // will get into the status page before import is actually started.
            // In this case wrong information (for previous import) will be displayed.
            // So lets ensure that import started before redirecting client to status page.
            int i = 0;
            while (!bulkImporter.getStatus().inProgress() && i < 10) {
                Thread.sleep(100);
                i++;
            }
            // redirect to the status Web Script
            status.setCode(Status.STATUS_MOVED_TEMPORARILY);
            status.setRedirect(true);
            status.setLocation(request.getServiceContextPath() + WEB_SCRIPT_URI_BULK_FILESYSTEM_IMPORT_STATUS);
        } else {
            model.put(IMPORT_ALREADY_IN_PROGRESS_MODEL_KEY, I18NUtil.getMessage(IMPORT_ALREADY_IN_PROGRESS_ERROR_KEY));
        }
    } catch (WebScriptException wse) {
        status.setCode(Status.STATUS_BAD_REQUEST, wse.getMessage());
        status.setRedirect(true);
    } catch (FileNotFoundException fnfe) {
        status.setCode(Status.STATUS_BAD_REQUEST, "The repository path '" + targetPath + "' does not exist !");
        status.setRedirect(true);
    } catch (IllegalArgumentException iae) {
        status.setCode(Status.STATUS_BAD_REQUEST, iae.getMessage());
        status.setRedirect(true);
    } catch (Throwable t) {
        throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, buildTextMessage(t), t);
    }
    return model;
}
Also used : BulkImportParameters(org.alfresco.repo.bulkimport.BulkImportParameters) HashMap(java.util.HashMap) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) NodeRef(org.alfresco.service.cmr.repository.NodeRef) NodeImporter(org.alfresco.repo.bulkimport.NodeImporter) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) File(java.io.File)

Example 22 with FileNotFoundException

use of org.alfresco.service.cmr.model.FileNotFoundException in project alfresco-remote-api by Alfresco.

the class LockMethod method attemptLock.

/**
 * The main lock implementation method.
 *
 * @throws WebDAVServerException
 * @throws Exception
 */
protected void attemptLock() throws WebDAVServerException, Exception {
    FileFolderService fileFolderService = getFileFolderService();
    final String path = getPath();
    NodeRef rootNodeRef = getRootNodeRef();
    // Get the active user
    final String userName = getDAVHelper().getAuthenticationService().getCurrentUserName();
    if (logger.isDebugEnabled()) {
        logger.debug("Locking node: \n" + "   user: " + userName + "\n" + "   path: " + path);
    }
    FileInfo lockNodeInfo = null;
    try {
        // Check if the path exists
        lockNodeInfo = getNodeForPath(getRootNodeRef(), getPath());
    } catch (FileNotFoundException e) {
        if (m_conditions != null) {
            // MNT-12303 fix, check whether this is a refresh lock request
            for (Condition condition : m_conditions) {
                List<String> lockTolensMatch = condition.getLockTokensMatch();
                List<String> etagsMatch = condition.getETagsMatch();
                if (m_request.getContentLength() == -1 && (lockTolensMatch != null && !lockTolensMatch.isEmpty()) || (etagsMatch != null && !etagsMatch.isEmpty())) {
                    // so there is nothing to refresh. Return 403 Forbidden as original SharePoint Server.
                    throw new WebDAVServerException(HttpServletResponse.SC_FORBIDDEN);
                }
            }
        }
        // need to create it
        String[] splitPath = getDAVHelper().splitPath(path);
        // check
        if (splitPath[1].length() == 0) {
            throw new WebDAVServerException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        FileInfo dirInfo = null;
        List<String> dirPathElements = getDAVHelper().splitAllPaths(splitPath[0]);
        if (dirPathElements.size() == 0) {
            // if there are no path elements we are at the root so get the root node
            dirInfo = fileFolderService.getFileInfo(getRootNodeRef());
        } else {
            // make sure folder structure is present
            dirInfo = FileFolderUtil.makeFolders(fileFolderService, rootNodeRef, dirPathElements, ContentModel.TYPE_FOLDER);
        }
        if (dirInfo == null) {
            throw new WebDAVServerException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        // create the file
        lockNodeInfo = createNode(dirInfo.getNodeRef(), splitPath[1], ContentModel.TYPE_CONTENT);
        // ALF-10309 fix, mark created node with webdavNoContent aspect, we assume that save operation
        // is performed by client, webdavNoContent aspect normally removed in put method unless there
        // is a cancel before the PUT request takes place
        int lockTimeout = getLockTimeout();
        if (lockTimeout > 0 && !getNodeService().hasAspect(lockNodeInfo.getNodeRef(), ContentModel.ASPECT_WEBDAV_NO_CONTENT)) {
            final NodeRef nodeRef = lockNodeInfo.getNodeRef();
            getNodeService().addAspect(nodeRef, ContentModel.ASPECT_WEBDAV_NO_CONTENT, null);
            // Remove node after the timeout (MS Office 2003 requests 3 minutes) if the PUT or UNLOCK has not taken place
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    // run as current user
                    AuthenticationUtil.runAs(new RunAsWork<Void>() {

                        @Override
                        public Void doWork() throws Exception {
                            try {
                                if (getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_WEBDAV_NO_CONTENT)) {
                                    getTransactionService().getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>() {

                                        public String execute() throws Throwable {
                                            getNodeService().deleteNode(nodeRef);
                                            if (logger.isDebugEnabled()) {
                                                logger.debug("Timer DELETE " + path);
                                            }
                                            return null;
                                        }
                                    }, false, true);
                                } else if (logger.isDebugEnabled()) {
                                    logger.debug("Timer IGNORE " + path);
                                }
                            } catch (InvalidNodeRefException e) {
                                // Might get this if the node is deleted. If so just ignore.
                                if (logger.isDebugEnabled()) {
                                    logger.debug("Timer DOES NOT EXIST " + path);
                                }
                            }
                            return null;
                        }
                    }, userName);
                }
            }, lockTimeout * 1000);
            if (logger.isDebugEnabled()) {
                logger.debug("Timer START in " + lockTimeout + " seconds " + path);
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Created new node for lock: \n" + "   path: " + path + "\n" + "   node: " + lockNodeInfo);
        }
        m_response.setStatus(HttpServletResponse.SC_CREATED);
    }
    // Check if this is a new lock or a lock refresh
    if (hasLockToken()) {
        lockInfo = checkNode(lockNodeInfo);
        if (!lockInfo.isLocked() && m_request.getContentLength() == -1) {
            // see http://www.ics.uci.edu/~ejw/authoring/protocol/rfc2518.html#rfc.section.7.8
            throw new WebDAVServerException(HttpServletResponse.SC_BAD_REQUEST);
        }
        // If a request body is not defined and "If" header is sent we have createExclusive as false,
        // but we need to check a previous LOCK was an exclusive. I.e. get the property for node. It
        // is already has got in a checkNode method, so we need just get a scope from lockInfo.
        // This particular case was raised as ALF-4008.
        this.createExclusive = WebDAV.XML_EXCLUSIVE.equals(this.lockInfo.getScope());
        // Refresh an existing lock
        refreshLock(lockNodeInfo, userName);
    } else {
        lockInfo = checkNode(lockNodeInfo, true, createExclusive);
        // Create a new lock
        createLock(lockNodeInfo, userName);
    }
    m_response.setHeader(WebDAV.HEADER_LOCK_TOKEN, "<" + WebDAV.makeLockToken(lockNodeInfo.getNodeRef(), userName) + ">");
    m_response.setHeader(WebDAV.HEADER_CONTENT_TYPE, WebDAV.XML_CONTENT_TYPE);
    // We either created a new lock or refreshed an existing lock, send back the lock details
    generateResponse(lockNodeInfo, userName);
}
Also used : FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) FileFolderService(org.alfresco.service.cmr.model.FileFolderService) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException) NodeRef(org.alfresco.service.cmr.repository.NodeRef) FileInfo(org.alfresco.service.cmr.model.FileInfo) TimerTask(java.util.TimerTask) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) List(java.util.List) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException)

Example 23 with FileNotFoundException

use of org.alfresco.service.cmr.model.FileNotFoundException in project alfresco-remote-api by Alfresco.

the class MkcolMethod method executeImpl.

/**
 * Execute the request
 *
 * @exception WebDAVServerException
 */
protected void executeImpl() throws WebDAVServerException, Exception {
    FileFolderService fileFolderService = getFileFolderService();
    // see if it exists
    try {
        getDAVHelper().getNodeForPath(getRootNodeRef(), getPath());
        // already exists
        throw new WebDAVServerException(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } catch (FileNotFoundException e) {
    // it doesn't exist
    }
    // Trim the last path component and check if the parent path exists
    String parentPath = getPath();
    int lastPos = parentPath.lastIndexOf(WebDAVHelper.PathSeperator);
    NodeRef parentNodeRef = null;
    if (lastPos == 0) {
        // Create new folder at root
        parentPath = WebDAVHelper.PathSeperator;
        parentNodeRef = getRootNodeRef();
    } else if (lastPos != -1) {
        // Trim the last path component
        parentPath = parentPath.substring(0, lastPos + 1);
        try {
            FileInfo parentFileInfo = getDAVHelper().getNodeForPath(getRootNodeRef(), parentPath);
            parentNodeRef = parentFileInfo.getNodeRef();
        } catch (FileNotFoundException e) {
            // parent path is missing
            throw new WebDAVServerException(HttpServletResponse.SC_CONFLICT);
        }
    } else {
        // Looks like a bad path
        throw new WebDAVServerException(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }
    // Get the new folder name
    String folderName = getPath().substring(lastPos + 1);
    // Create the new folder node
    FileInfo fileInfo = fileFolderService.create(parentNodeRef, folderName, ContentModel.TYPE_FOLDER);
    // Don't post activity data for hidden folder
    if (!fileInfo.isHidden()) {
        postActivity(fileInfo);
    }
    // Return a success status
    m_response.setStatus(HttpServletResponse.SC_CREATED);
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) FileInfo(org.alfresco.service.cmr.model.FileInfo) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) FileFolderService(org.alfresco.service.cmr.model.FileFolderService)

Example 24 with FileNotFoundException

use of org.alfresco.service.cmr.model.FileNotFoundException in project alfresco-remote-api by Alfresco.

the class WebDAVHelperIntegrationTest method cannotGetNodeForPathWithIncorrectCase.

@Test
public void cannotGetNodeForPathWithIncorrectCase() throws FileNotFoundException {
    FileInfo folderInfo = fileFolderService.create(rootFolder, "my_folder", ContentModel.TYPE_FOLDER);
    fileFolderService.create(folderInfo.getNodeRef(), "my_file.txt", ContentModel.TYPE_CONTENT);
    try {
        webDAVHelper.getNodeForPath(rootFolder, "My_Folder/My_File.txt");
        fail("FileNotFoundException should have been thrown.");
    } catch (FileNotFoundException e) {
    // Got here, good.
    }
}
Also used : FileInfo(org.alfresco.service.cmr.model.FileInfo) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) Test(org.junit.Test)

Example 25 with FileNotFoundException

use of org.alfresco.service.cmr.model.FileNotFoundException in project alfresco-remote-api by Alfresco.

the class WebDAVHelperIntegrationTest method cannotGetNodeForFolderPathWithIncorrectCase.

@Test
public void cannotGetNodeForFolderPathWithIncorrectCase() throws FileNotFoundException {
    FileInfo folderInfo = fileFolderService.create(rootFolder, "my_folder", ContentModel.TYPE_FOLDER);
    fileFolderService.create(folderInfo.getNodeRef(), "my_file.txt", ContentModel.TYPE_CONTENT);
    try {
        webDAVHelper.getNodeForPath(rootFolder, "My_Folder");
        fail("FileNotFoundException should have been thrown.");
    } catch (FileNotFoundException e) {
    // Got here, good.
    }
}
Also used : FileInfo(org.alfresco.service.cmr.model.FileInfo) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) Test(org.junit.Test)

Aggregations

FileNotFoundException (org.alfresco.service.cmr.model.FileNotFoundException)31 NodeRef (org.alfresco.service.cmr.repository.NodeRef)23 FileInfo (org.alfresco.service.cmr.model.FileInfo)22 FileFolderService (org.alfresco.service.cmr.model.FileFolderService)7 FileExistsException (org.alfresco.service.cmr.model.FileExistsException)6 ArrayList (java.util.ArrayList)5 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)5 RunAsWork (org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork)5 QName (org.alfresco.service.namespace.QName)4 HashMap (java.util.HashMap)3 List (java.util.List)3 RetryingTransactionCallback (org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback)3 WebDavService (org.alfresco.service.cmr.webdav.WebDavService)3 Date (java.util.Date)2 HashSet (java.util.HashSet)2 LinkedHashSet (java.util.LinkedHashSet)2 Set (java.util.Set)2 StringTokenizer (java.util.StringTokenizer)2 TimerTask (java.util.TimerTask)2 FileContentReader (org.alfresco.repo.content.filestore.FileContentReader)2