Search in sources :

Example 6 with FileNotFoundException

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

the class NodesImpl method resolveNodeByPath.

protected NodeRef resolveNodeByPath(final NodeRef parentNodeRef, String path, boolean checkForCompanyHome) {
    final List<String> pathElements = getPathElements(path);
    if (!pathElements.isEmpty() && checkForCompanyHome) {
    /*
            if (nodeService.getRootNode(parentNodeRef.getStoreRef()).equals(parentNodeRef))
            {
                // special case
                NodeRef chNodeRef = repositoryHelper.getCompanyHome();
                String chName = (String) nodeService.getProperty(chNodeRef, ContentModel.PROP_NAME);
                if (chName.equals(pathElements.get(0)))
                {
                    pathElements = pathElements.subList(1, pathElements.size());
                    parentNodeRef = chNodeRef;
                }
            }
            */
    }
    FileInfo fileInfo = null;
    try {
        if (!pathElements.isEmpty()) {
            fileInfo = fileFolderService.resolveNamePath(parentNodeRef, pathElements);
        } else {
            fileInfo = fileFolderService.getFileInfo(parentNodeRef);
            if (fileInfo == null) {
                throw new EntityNotFoundException(parentNodeRef.getId());
            }
        }
    } catch (FileNotFoundException fnfe) {
        // convert checked exception
        throw new NotFoundException("The entity with relativePath: " + path + " was not found.");
    } catch (AccessDeniedException ade) {
        // return 404 instead of 403 (as per security review - uuid vs path)
        throw new NotFoundException("The entity with relativePath: " + path + " was not found.");
    }
    return fileInfo.getNodeRef();
}
Also used : AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) FileInfo(org.alfresco.service.cmr.model.FileInfo) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) NotFoundException(org.alfresco.rest.framework.core.exceptions.NotFoundException) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException)

Example 7 with FileNotFoundException

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

the class NodesImpl method listChildren.

@Override
public CollectionWithPagingInfo<Node> listChildren(String parentFolderNodeId, Parameters parameters) {
    String path = parameters.getParameter(PARAM_RELATIVE_PATH);
    final NodeRef parentNodeRef = validateOrLookupNode(parentFolderNodeId, path);
    final List<String> includeParam = parameters.getInclude();
    QName assocTypeQNameParam = null;
    Query q = parameters.getQuery();
    if (q != null) {
        // filtering via "where" clause
        MapBasedQueryWalker propertyWalker = createListChildrenQueryWalker();
        QueryHelper.walk(q, propertyWalker);
        String assocTypeQNameStr = propertyWalker.getProperty(PARAM_ASSOC_TYPE, WhereClauseParser.EQUALS, String.class);
        if (assocTypeQNameStr != null) {
            assocTypeQNameParam = getAssocType(assocTypeQNameStr);
        }
    }
    List<Pair<QName, Boolean>> sortProps = getListChildrenSortProps(parameters);
    List<FilterProp> filterProps = getListChildrenFilterProps(parameters);
    Paging paging = parameters.getPaging();
    PagingRequest pagingRequest = Util.getPagingRequest(paging);
    final PagingResults<FileInfo> pagingResults;
    Pair<Set<QName>, Set<QName>> pair = buildSearchTypesAndIgnoreAspects(parameters);
    Set<QName> searchTypeQNames = pair.getFirst();
    Set<QName> ignoreAspectQNames = pair.getSecond();
    Set<QName> assocTypeQNames = buildAssocTypes(assocTypeQNameParam);
    // call GetChildrenCannedQuery (via FileFolderService)
    if (((filterProps == null) || (filterProps.size() == 0)) && ((assocTypeQNames == null) || (assocTypeQNames.size() == 0)) && (smartStore.isVirtual(parentNodeRef) || (smartStore.canVirtualize(parentNodeRef)))) {
        pagingResults = fileFolderService.list(parentNodeRef, searchTypeQNames, ignoreAspectQNames, sortProps, pagingRequest);
    } else {
        // TODO smart folders (see REPO-1173)
        pagingResults = fileFolderService.list(parentNodeRef, assocTypeQNames, searchTypeQNames, ignoreAspectQNames, sortProps, filterProps, pagingRequest);
    }
    final Map<String, UserInfo> mapUserInfo = new HashMap<>(10);
    final List<FileInfo> page = pagingResults.getPage();
    List<Node> nodes = new AbstractList<Node>() {

        @Override
        public Node get(int index) {
            FileInfo fInfo = page.get(index);
            // minimal info by default (unless "include"d otherwise)
            // (pass in null as parentNodeRef to force loading of primary
            // parent node as parentId)
            Node node = getFolderOrDocument(fInfo.getNodeRef(), null, fInfo.getType(), includeParam, mapUserInfo);
            if (node.getPath() != null) {
                calculateRelativePath(parentFolderNodeId, node);
            }
            return node;
        }

        private void calculateRelativePath(String parentFolderNodeId, Node node) {
            NodeRef rootNodeRef = validateOrLookupNode(parentFolderNodeId, null);
            try {
                // get the path elements
                List<String> pathInfos = fileFolderService.getNameOnlyPath(rootNodeRef, node.getNodeRef());
                int sizePathInfos = pathInfos.size();
                if (sizePathInfos > 1) {
                    // remove the current child
                    pathInfos.remove(sizePathInfos - 1);
                    // build the path string
                    StringBuilder sb = new StringBuilder(pathInfos.size() * 20);
                    for (String fileInfo : pathInfos) {
                        sb.append("/");
                        sb.append(fileInfo);
                    }
                    node.getPath().setRelativePath(sb.toString());
                }
            } catch (FileNotFoundException e) {
            // NOTE: return null as relativePath
            }
        }

        @Override
        public int size() {
            return page.size();
        }
    };
    Node sourceEntity = null;
    if (parameters.includeSource()) {
        sourceEntity = getFolderOrDocumentFullInfo(parentNodeRef, null, null, null, mapUserInfo);
    }
    return CollectionWithPagingInfo.asPaged(paging, nodes, pagingResults.hasMoreItems(), pagingResults.getTotalResultCount().getFirst(), sourceEntity);
}
Also used : Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) Query(org.alfresco.rest.framework.resource.parameters.where.Query) GetChildrenCannedQuery(org.alfresco.repo.node.getchildren.GetChildrenCannedQuery) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Node(org.alfresco.rest.api.model.Node) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) UserInfo(org.alfresco.rest.api.model.UserInfo) NodeRef(org.alfresco.service.cmr.repository.NodeRef) FileInfo(org.alfresco.service.cmr.model.FileInfo) MapBasedQueryWalker(org.alfresco.rest.workflow.api.impl.MapBasedQueryWalker) Pair(org.alfresco.util.Pair) AbstractList(java.util.AbstractList) FilterProp(org.alfresco.repo.node.getchildren.FilterProp) QName(org.alfresco.service.namespace.QName) Paging(org.alfresco.rest.framework.resource.parameters.Paging) PagingRequest(org.alfresco.query.PagingRequest)

Example 8 with FileNotFoundException

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

the class DeleteMethod method postActivity.

/**
 * Create a deletion activity post.
 *
 * @param parent The FileInfo for the deleted file's parent.
 * @param deletedFile The FileInfo for the deleted file.
 * @throws WebDAVServerException
 */
protected void postActivity(FileInfo parent, FileInfo deletedFile, String siteId) throws WebDAVServerException {
    WebDavService davService = getDAVHelper().getServiceRegistry().getWebDavService();
    if (!davService.activitiesEnabled()) {
        // Don't post activities if this behaviour is disabled.
        return;
    }
    String tenantDomain = getTenantDomain();
    // Check there is enough information to publish site activity.
    if (!siteId.equals(WebDAVHelper.EMPTY_SITE_ID)) {
        SiteService siteService = getServiceRegistry().getSiteService();
        NodeRef documentLibrary = siteService.getContainer(siteId, SiteService.DOCUMENT_LIBRARY);
        String parentPath = "/";
        try {
            parentPath = getDAVHelper().getPathFromNode(documentLibrary, parent.getNodeRef());
        } catch (FileNotFoundException error) {
            if (logger.isDebugEnabled()) {
                logger.debug("No " + SiteService.DOCUMENT_LIBRARY + " container found.");
            }
        }
        activityPoster.postFileFolderDeleted(siteId, tenantDomain, parentPath, parent, deletedFile);
    }
}
Also used : WebDavService(org.alfresco.service.cmr.webdav.WebDavService) NodeRef(org.alfresco.service.cmr.repository.NodeRef) SiteService(org.alfresco.service.cmr.site.SiteService) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException)

Example 9 with FileNotFoundException

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

the class DeleteMethod method executeImpl.

/**
 * Execute the request
 *
 * @exception WebDAVServerException
 */
protected void executeImpl() throws WebDAVServerException, Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("WebDAV DELETE: " + getPath());
    }
    final FileFolderService fileFolderService = getFileFolderService();
    final PermissionService permissionService = getPermissionService();
    NodeRef rootNodeRef = getRootNodeRef();
    String path = getPath();
    FileInfo fileInfo = null;
    try {
        // get the node to delete
        fileInfo = getNodeForPath(rootNodeRef, path);
    } catch (FileNotFoundException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Node not found: " + getPath());
        }
        throw new WebDAVServerException(HttpServletResponse.SC_NOT_FOUND);
    }
    checkNode(fileInfo);
    final NodeService nodeService = getNodeService();
    final NodeRef nodeRef = fileInfo.getNodeRef();
    if (permissionService.hasPermission(nodeRef, PermissionService.DELETE) == AccessStatus.ALLOWED) {
        // As this content will be deleted, we need to extract some info before it's no longer available.
        String siteId = getSiteId();
        NodeRef deletedNodeRef = fileInfo.getNodeRef();
        FileInfo parentFile = getDAVHelper().getParentNodeForPath(getRootNodeRef(), path);
        // Don't post activity data for hidden files, resource forks etc.
        if (!getDAVHelper().isRenameShuffle(path)) {
            postActivity(parentFile, fileInfo, siteId);
        }
        // MNT-181: working copies and versioned nodes are hidden rather than deleted
        if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_WORKING_COPY) || nodeService.hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)) {
            // Mark content as hidden.  This breaks many contracts and will be fixed for "ALF-18619 WebDAV/SPP file shuffles"
            fileFolderService.setHidden(nodeRef, true);
            {
                // Workaround for MNT-8704: WebDAV:Content does not disappear after being deleted
                // Get the current user
                final String deleteDelayUser = AuthenticationUtil.getFullyAuthenticatedUser();
                // Add a timed task to really delete the file
                TimerTask deleteDelayTask = new TimerTask() {

                    @Override
                    public void run() {
                        RunAsWork<Void> deleteDelayRunAs = new RunAsWork<Void>() {

                            @Override
                            public Void doWork() throws Exception {
                                // Ignore if it is NOT hidden: the shuffle may have finished; the operation may have failed
                                if (!nodeService.exists(nodeRef) || !fileFolderService.isHidden(nodeRef)) {
                                    return null;
                                }
                                // Since this will run in a different thread, the client thread-local must be set
                                // or else unhiding the node will not unhide it for WebDAV.
                                FileFilterMode.setClient(FileFilterMode.Client.webdav);
                                // Unhide the node, e.g. for archiving
                                fileFolderService.setHidden(nodeRef, false);
                                // This is the transaction-aware service
                                fileFolderService.delete(nodeRef);
                                return null;
                            }
                        };
                        try {
                            AuthenticationUtil.runAs(deleteDelayRunAs, deleteDelayUser);
                        } catch (Throwable e) {
                            // consume exception to avoid it leaking from the TimerTask and causing the Timer to
                            // no longer accept tasks to be scheduled.
                            logger.info("Exception thrown during WebDAV delete timer task.", e);
                        }
                    }
                };
                // Schedule a real delete 5 seconds after the current time
                deleteDelayTimer.schedule(deleteDelayTask, 5000L);
            }
            // node is is actually locked before unlocking to avoid access denied
            if (getDAVLockService().getLockInfo(nodeRef).isLocked()) {
                getDAVLockService().unlock(nodeRef);
            }
        } else // We just ensure already-hidden nodes are left unlocked
        if (fileFolderService.isHidden(nodeRef)) {
            getDAVLockService().unlock(nodeRef);
        } else // A 'real' delete
        {
            // Delete it
            fileFolderService.delete(deletedNodeRef);
        }
    } else {
        // access denied
        throw new WebDAVServerException(HttpServletResponse.SC_FORBIDDEN);
    }
}
Also used : RunAsWork(org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork) NodeService(org.alfresco.service.cmr.repository.NodeService) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) FileFolderService(org.alfresco.service.cmr.model.FileFolderService) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) PermissionService(org.alfresco.service.cmr.security.PermissionService) NodeRef(org.alfresco.service.cmr.repository.NodeRef) FileInfo(org.alfresco.service.cmr.model.FileInfo) TimerTask(java.util.TimerTask)

Example 10 with FileNotFoundException

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

the class GetMethod method executeImpl.

/**
 * Exceute the WebDAV request
 *
 * @exception WebDAVServerException
 */
protected void executeImpl() throws WebDAVServerException, Exception {
    FileFolderService fileFolderService = getFileFolderService();
    NodeRef rootNodeRef = getRootNodeRef();
    String path = getPath();
    if (!m_returnContent) {
        // There are multiple cases where no content is sent (due to a HEAD request).
        // All of them require that the content length is set appropriately.
        m_response.setContentLength(0);
    }
    FileInfo nodeInfo = null;
    try {
        nodeInfo = getDAVHelper().getNodeForPath(rootNodeRef, path);
    } catch (FileNotFoundException e) {
        throw new WebDAVServerException(HttpServletResponse.SC_NOT_FOUND);
    }
    FileInfo realNodeInfo = nodeInfo;
    // This is at least consistent with the way the CIFS server handles links. See org.alfresco.filesys.repo.ContentDiskDriver.openFile().
    if (realNodeInfo.isLink()) {
        Path pathToNode = getNodeService().getPath(nodeInfo.getLinkNodeRef());
        if (pathToNode.size() > 2) {
            pathToNode = pathToNode.subPath(2, pathToNode.size() - 1);
        }
        String rootURL = getDAVHelper().getURLForPath(m_request, pathToNode.toDisplayPath(getNodeService(), getPermissionService()), true);
        if (rootURL.endsWith(WebDAVHelper.PathSeperator) == false) {
            rootURL = rootURL + WebDAVHelper.PathSeperator;
        }
        String fname = (String) getNodeService().getProperty(nodeInfo.getLinkNodeRef(), ContentModel.PROP_NAME);
        StringBuilder urlStr = new StringBuilder(200);
        urlStr.append("[InternetShortcut]\r\n");
        urlStr.append("URL=file://");
        urlStr.append(m_request.getServerName());
        // Only append the port if it is non-default for compatibility with XP
        int port = m_request.getServerPort();
        if (port != 80) {
            urlStr.append(":").append(port);
        }
        urlStr.append(rootURL).append(WebDAVHelper.encodeURL(fname, m_userAgent));
        urlStr.append("\r\n");
        m_response.setHeader(WebDAV.HEADER_CONTENT_TYPE, "text/plain; charset=ISO-8859-1");
        m_response.setHeader(WebDAV.HEADER_CONTENT_LENGTH, String.valueOf(urlStr.length()));
        m_response.getWriter().write(urlStr.toString());
    } else // Check if the node is a folder
    if (realNodeInfo.isFolder()) {
        // is content required
        if (!m_returnContent) {
            // ALF-7883 fix, HEAD for collection (see http://www.webdav.org/specs/rfc2518.html#rfc.section.8.4)
            return;
        }
        // Generate a folder listing
        m_response.setContentType("text/html;charset=UTF-8");
        generateDirectoryListing(nodeInfo);
    } else {
        // Return the node details, and content if requested, check that the node passes the pre-conditions
        checkPreConditions(realNodeInfo);
        // Build the response header
        m_response.setHeader(WebDAV.HEADER_ETAG, getDAVHelper().makeQuotedETag(nodeInfo));
        Date modifiedDate = realNodeInfo.getModifiedDate();
        if (modifiedDate != null) {
            long modDate = DefaultTypeConverter.INSTANCE.longValue(modifiedDate);
            m_response.setHeader(WebDAV.HEADER_LAST_MODIFIED, WebDAV.formatHeaderDate(modDate));
        }
        m_response.setHeader("Content-Disposition", getContentDispositionHeader(nodeInfo));
        ContentReader reader = fileFolderService.getReader(realNodeInfo.getNodeRef());
        // ensure that we generate something, even if the content is missing
        reader = FileContentReader.getSafeContentReader((ContentReader) reader, I18NUtil.getMessage(FileContentReader.MSG_MISSING_CONTENT), realNodeInfo.getNodeRef(), reader);
        readContent(realNodeInfo, reader);
    }
}
Also used : Path(org.alfresco.service.cmr.repository.Path) NodeRef(org.alfresco.service.cmr.repository.NodeRef) FileInfo(org.alfresco.service.cmr.model.FileInfo) FileContentReader(org.alfresco.repo.content.filestore.FileContentReader) ContentReader(org.alfresco.service.cmr.repository.ContentReader) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) FileFolderService(org.alfresco.service.cmr.model.FileFolderService) Date(java.util.Date)

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