Search in sources :

Example 16 with FileNotFoundException

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

the class FileFolderLoaderPost method execute.

public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    FileFolderLoader loader = (FileFolderLoader) applicationContext.getBean("fileFolderLoader");
    int count = 0;
    String folderPath = "";
    try {
        JSONObject json = new JSONObject(new JSONTokener(req.getContent().getContent()));
        folderPath = json.getString(KEY_FOLDER_PATH);
        if (folderPath == null) {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, KEY_FOLDER_PATH + " not supplied.");
        }
        int fileCount = 100;
        if (json.has(KEY_FILE_COUNT)) {
            fileCount = json.getInt(KEY_FILE_COUNT);
        }
        int filesPerTxn = DEFAULT_FILES_PER_TXN;
        if (json.has(KEY_FILES_PER_TXN)) {
            filesPerTxn = json.getInt(KEY_FILES_PER_TXN);
        }
        long minFileSize = DEFAULT_MIN_FILE_SIZE;
        if (json.has(KEY_MIN_FILE_SIZE)) {
            minFileSize = json.getInt(KEY_MIN_FILE_SIZE);
        }
        long maxFileSize = DEFAULT_MAX_FILE_SIZE;
        if (json.has(KEY_MAX_FILE_SIZE)) {
            maxFileSize = json.getInt(KEY_MAX_FILE_SIZE);
        }
        long maxUniqueDocuments = DEFAULT_MAX_UNIQUE_DOCUMENTS;
        if (json.has(KEY_MAX_UNIQUE_DOCUMENTS)) {
            maxUniqueDocuments = json.getInt(KEY_MAX_UNIQUE_DOCUMENTS);
        }
        boolean forceBinaryStorage = DEFAULT_FORCE_BINARY_STORAGE;
        if (json.has(KEY_FORCE_BINARY_STORAGE)) {
            forceBinaryStorage = json.getBoolean(KEY_FORCE_BINARY_STORAGE);
        }
        int descriptionCount = DEFAULT_DESCRIPTION_COUNT;
        if (json.has(KEY_DESCRIPTION_COUNT)) {
            descriptionCount = json.getInt(KEY_DESCRIPTION_COUNT);
        }
        long descriptionSize = DEFAULT_DESCRIPTION_SIZE;
        if (json.has(KEY_DESCRIPTION_SIZE)) {
            descriptionSize = json.getLong(KEY_DESCRIPTION_SIZE);
        }
        // Perform the load
        count = loader.createFiles(folderPath, fileCount, filesPerTxn, minFileSize, maxFileSize, maxUniqueDocuments, forceBinaryStorage, descriptionCount, descriptionSize);
    } catch (FileNotFoundException e) {
        throw new WebScriptException(Status.STATUS_NOT_FOUND, "Folder not found: ", folderPath);
    } catch (IOException iox) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not read content from req.", iox);
    } catch (JSONException je) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not parse JSON from req.", je);
    }
    // Write the response
    OutputStream os = res.getOutputStream();
    try {
        JSONObject json = new JSONObject();
        json.put(KEY_COUNT, count);
        os.write(json.toString().getBytes("UTF-8"));
    } catch (JSONException e) {
        throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Failed to write JSON", e);
    } finally {
        os.close();
    }
}
Also used : JSONTokener(org.json.JSONTokener) FileFolderLoader(org.alfresco.repo.model.filefolder.FileFolderLoader) JSONObject(org.json.JSONObject) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) OutputStream(java.io.OutputStream) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) JSONException(org.json.JSONException) IOException(java.io.IOException)

Example 17 with FileNotFoundException

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

the class ADMRemoteStore method resolveNodePath.

/**
 * @param path      cm:name based root relative path
 *                  example: /alfresco/site-data/pages/customise-user-dashboard.xml
 *                           /alfresco/site-data/components
 * @param pattern   optional pattern that is used as part of the match to aquire the surf-config
 *                  folder under the appropriate sites or user location.
 * @param create    if true create the config and folder dirs for the given path returning
 *                  the FileInfo for the last parent in the path, if false only attempt to
 *                  resolve the folder path if it exists returning the last element.
 * @param isFolder  True if the path is for a folder, false if it ends in a filename
 *
 * @return FileInfo representing the file/folder at the specified path location (see create
 *         parameter above) or null if the supplied path does not exist in the store.
 */
private FileInfo resolveNodePath(final String path, final String pattern, final boolean create, final boolean isFolder) {
    if (logger.isDebugEnabled())
        logger.debug("Resolving path: " + path);
    final String adminUserName = AuthenticationUtil.getAdminUserName();
    FileInfo result = null;
    if (path != null) {
        // break down the path into its component elements
        List<String> pathElements = new ArrayList<String>(4);
        final StringTokenizer t = new StringTokenizer(path, "/");
        // the store requires paths of the form /alfresco/site-data/<objecttype>[/<folder>]/<file>.xml
        if (t.countTokens() >= 3) {
            // skip /alfresco
            t.nextToken();
            // skip /site-data
            t.nextToken();
            // collect remaining folder path (and file)
            while (t.hasMoreTokens()) {
                pathElements.add(t.nextToken());
            }
            NodeRef surfConfigRef = aquireSurfConfigRef(path + (pattern != null ? ("/" + pattern) : ""), create);
            try {
                if (surfConfigRef != null) {
                    if (create) {
                        List<String> folders = isFolder ? pathElements : pathElements.subList(0, pathElements.size() - 1);
                        List<FileFolderUtil.PathElementDetails> folderDetails = new ArrayList<>(pathElements.size());
                        Map<QName, Serializable> prop = new HashMap<>(2);
                        prop.put(ContentModel.PROP_IS_INDEXED, false);
                        prop.put(ContentModel.PROP_IS_CONTENT_INDEXED, false);
                        for (String element : folders) {
                            Map<QName, Map<QName, Serializable>> aspects = Collections.singletonMap(ContentModel.ASPECT_INDEX_CONTROL, prop);
                            folderDetails.add(new FileFolderUtil.PathElementDetails(element, aspects));
                        }
                        // ensure folders exist down to the specified parent
                        // ALF-17729 / ALF-17796 - disable auditable on parent folders
                        Set<NodeRef> allCreatedFolders = new LinkedHashSet<>();
                        result = FileFolderUtil.makeFolders(this.fileFolderService, nodeService, surfConfigRef, folderDetails, ContentModel.TYPE_FOLDER, behaviourFilter, new HashSet<QName>(Arrays.asList(new QName[] { ContentModel.ASPECT_AUDITABLE })), allCreatedFolders);
                        // MNT-16371: Revoke ownership privileges for surf-config folder, to tighten access for former SiteManagers.
                        for (NodeRef nodeRef : allCreatedFolders) {
                            ownableService.setOwner(nodeRef, adminUserName);
                        }
                    } else {
                        // perform the cm:name path lookup against our config root node
                        result = this.fileFolderService.resolveNamePath(surfConfigRef, pathElements);
                    }
                }
            } catch (FileNotFoundException fnfErr) {
            // this is a valid condition - we return null to indicate failed lookup
            }
        }
    }
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Serializable(java.io.Serializable) HashMap(java.util.HashMap) QName(org.alfresco.service.namespace.QName) ArrayList(java.util.ArrayList) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) FileFolderUtil(org.alfresco.service.cmr.model.FileFolderUtil) NodeRef(org.alfresco.service.cmr.repository.NodeRef) StringTokenizer(java.util.StringTokenizer) FileInfo(org.alfresco.service.cmr.model.FileInfo) Map(java.util.Map) MimetypeMap(org.alfresco.repo.content.MimetypeMap) HashMap(java.util.HashMap) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 18 with FileNotFoundException

use of org.alfresco.service.cmr.model.FileNotFoundException in project records-management by Alfresco.

the class RecordsEntityResource method fileRecord.

@Operation("file")
@WebApiDescription(title = "File record", description = "File a record into fileplan.")
public Record fileRecord(String recordId, TargetContainer target, Parameters parameters, WithResponse withResponse) {
    checkNotBlank("recordId", recordId);
    mandatory("target", target);
    mandatory("targetParentId", target.getTargetParentId());
    mandatory("parameters", parameters);
    // Get record and target folder
    NodeRef record = apiUtils.validateRecord(recordId);
    NodeRef targetRecordFolder = apiUtils.lookupAndValidateNodeType(target.getTargetParentId(), RecordsManagementModel.TYPE_RECORD_FOLDER);
    // Get the current parent type to decide if we link or move the record
    NodeRef primaryParent = nodeService.getPrimaryParent(record).getParentRef();
    if (RecordsManagementModel.TYPE_RECORD_FOLDER.equals(nodeService.getType(primaryParent))) {
        recordService.link(record, targetRecordFolder);
    } else {
        try {
            fileFolderService.moveFrom(record, primaryParent, targetRecordFolder, null);
        } catch (FileExistsException e) {
            throw new IntegrityException(e.getMessage(), null);
        } catch (FileNotFoundException e) {
            throw new ConcurrencyFailureException("The record was deleted while filing it", e);
        }
    }
    // return record state
    FileInfo info = fileFolderService.getFileInfo(record);
    return nodesModelFactory.createRecord(info, parameters, null, false);
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) FileInfo(org.alfresco.service.cmr.model.FileInfo) ConcurrencyFailureException(org.springframework.dao.ConcurrencyFailureException) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) IntegrityException(org.alfresco.repo.node.integrity.IntegrityException) FileExistsException(org.alfresco.service.cmr.model.FileExistsException) WebApiDescription(org.alfresco.rest.framework.WebApiDescription) Operation(org.alfresco.rest.framework.Operation)

Example 19 with FileNotFoundException

use of org.alfresco.service.cmr.model.FileNotFoundException in project acs-community-packaging by Alfresco.

the class BaseDownloadContentServlet method processDownloadRequest.

/**
 * Processes the download request using the current context i.e. no authentication checks are made, it is presumed
 * they have already been done.
 *
 * @param req
 *           The HTTP request
 * @param res
 *           The HTTP response
 * @param allowLogIn
 *           Indicates whether guest users without access to the content should be redirected to the log in page. If
 *           <code>false</code>, a status 403 forbidden page is displayed instead.
 */
protected void processDownloadRequest(HttpServletRequest req, HttpServletResponse res, boolean allowLogIn, boolean transmitContent) throws ServletException, IOException {
    Log logger = getLogger();
    String uri = req.getRequestURI();
    if (logger.isDebugEnabled()) {
        String queryString = req.getQueryString();
        logger.debug("Processing URL: " + uri + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
    }
    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();
    // skip servlet name
    t.nextToken();
    // attachment mode (either 'attach' or 'direct')
    String attachToken = t.nextToken();
    boolean attachment = URL_ATTACH.equals(attachToken) || URL_ATTACH_LONG.equals(attachToken);
    ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
    // get or calculate the noderef and filename to download as
    NodeRef nodeRef;
    String filename;
    // do we have a path parameter instead of a NodeRef?
    String path = req.getParameter(ARG_PATH);
    if (path != null && path.length() != 0) {
        // process the name based path to resolve the NodeRef and the Filename element
        try {
            PathRefInfo pathInfo = resolveNamePath(getServletContext(), path);
            nodeRef = pathInfo.NodeRef;
            filename = pathInfo.Filename;
        } catch (IllegalArgumentException e) {
            Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND, HttpServletResponse.SC_NOT_FOUND, logger);
            return;
        }
    } else {
        // a NodeRef must have been specified if no path has been found
        if (tokenCount < 6) {
            throw new IllegalArgumentException("Download URL did not contain all required args: " + uri);
        }
        // assume 'workspace' or other NodeRef based protocol for remaining URL elements
        StoreRef storeRef = new StoreRef(URLDecoder.decode(t.nextToken()), URLDecoder.decode(t.nextToken()));
        String id = URLDecoder.decode(t.nextToken());
        // build noderef from the appropriate URL elements
        nodeRef = new NodeRef(storeRef, id);
        if (tokenCount > 6) {
            // found additional relative path elements i.e. noderefid/images/file.txt
            // this allows a url to reference siblings nodes via a cm:name based relative path
            // solves the issue with opening HTML content containing relative URLs in HREF or IMG tags etc.
            List<String> paths = new ArrayList<String>(tokenCount - 5);
            while (t.hasMoreTokens()) {
                paths.add(URLDecoder.decode(t.nextToken()));
            }
            filename = paths.get(paths.size() - 1);
            try {
                NodeRef parentRef = serviceRegistry.getNodeService().getPrimaryParent(nodeRef).getParentRef();
                FileInfo fileInfo = serviceRegistry.getFileFolderService().resolveNamePath(parentRef, paths);
                nodeRef = fileInfo.getNodeRef();
            } catch (FileNotFoundException e) {
                Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND, HttpServletResponse.SC_NOT_FOUND, logger);
                return;
            }
        } else {
            // filename is last remaining token
            filename = t.nextToken();
        }
    }
    // get qualified of the property to get content from - default to ContentModel.PROP_CONTENT
    QName propertyQName = ContentModel.PROP_CONTENT;
    String property = req.getParameter(ARG_PROPERTY);
    if (property != null && property.length() != 0) {
        propertyQName = QName.createQName(property);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Found NodeRef: " + nodeRef);
        logger.debug("Will use filename: " + filename);
        logger.debug("For property: " + propertyQName);
        logger.debug("With attachment mode: " + attachment);
    }
    // get the services we need to retrieve the content
    NodeService nodeService = serviceRegistry.getNodeService();
    ContentService contentService = serviceRegistry.getContentService();
    // Check that the node still exists
    if (!nodeService.exists(nodeRef)) {
        Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND, HttpServletResponse.SC_NOT_FOUND, logger);
        return;
    }
    try {
        // check that the user has at least READ_CONTENT access - else redirect to an error or login page
        if (!checkAccess(req, res, nodeRef, PermissionService.READ_CONTENT, allowLogIn)) {
            return;
        }
        // check If-Modified-Since header and set Last-Modified header as appropriate
        Date modified = (Date) nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED);
        if (modified != null) {
            long modifiedSince = req.getDateHeader(HEADER_IF_MODIFIED_SINCE);
            if (modifiedSince > 0L) {
                // round the date to the ignore millisecond value which is not supplied by header
                long modDate = (modified.getTime() / 1000L) * 1000L;
                if (modDate <= modifiedSince) {
                    if (logger.isDebugEnabled())
                        logger.debug("Returning 304 Not Modified.");
                    res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                }
            }
            res.setDateHeader(HEADER_LAST_MODIFIED, modified.getTime());
            res.setHeader(HEADER_CACHE_CONTROL, "must-revalidate, max-age=0");
            res.setHeader(HEADER_ETAG, "\"" + Long.toString(modified.getTime()) + "\"");
        }
        if (attachment == true) {
            setHeaderContentDisposition(req, res, filename);
        }
        // get the content reader
        ContentReader reader = contentService.getReader(nodeRef, propertyQName);
        // ensure that it is safe to use
        reader = FileContentReader.getSafeContentReader(reader, Application.getMessage(req.getSession(), MSG_ERROR_CONTENT_MISSING), nodeRef, reader);
        String mimetype = reader.getMimetype();
        // fall back if unable to resolve mimetype property
        if (mimetype == null || mimetype.length() == 0) {
            MimetypeService mimetypeMap = serviceRegistry.getMimetypeService();
            mimetype = MIMETYPE_OCTET_STREAM;
            int extIndex = filename.lastIndexOf('.');
            if (extIndex != -1) {
                String ext = filename.substring(extIndex + 1);
                mimetype = mimetypeMap.getMimetype(ext);
            }
        }
        // explicitly set the content disposition header if the content is powerpoint
        if (!attachment && (mimetype.equals(POWER_POINT_2007_DOCUMENT_MIMETYPE) || mimetype.equals(POWER_POINT_DOCUMENT_MIMETYPE))) {
            setHeaderContentDisposition(req, res, filename);
        }
        // get the content and stream directly to the response output stream
        // assuming the repo is capable of streaming in chunks, this should allow large files
        // to be streamed directly to the browser response stream.
        res.setHeader(HEADER_ACCEPT_RANGES, "bytes");
        // for a GET request, transmit the content else just the headers are sent
        if (transmitContent) {
            try {
                boolean processedRange = false;
                String range = req.getHeader(HEADER_CONTENT_RANGE);
                if (range == null) {
                    range = req.getHeader(HEADER_RANGE);
                }
                if (range != null) {
                    if (logger.isDebugEnabled())
                        logger.debug("Found content range header: " + range);
                    // ensure the range header is starts with "bytes=" and process the range(s)
                    if (range.length() > 6) {
                        HttpRangeProcessor rangeProcessor = new HttpRangeProcessor(contentService);
                        processedRange = rangeProcessor.processRange(res, reader, range.substring(6), nodeRef, propertyQName, mimetype, req.getHeader(HEADER_USER_AGENT));
                    }
                }
                if (processedRange == false) {
                    if (logger.isDebugEnabled())
                        logger.debug("Sending complete file content...");
                    // set mimetype for the content and the character encoding for the stream
                    res.setContentType(mimetype);
                    res.setCharacterEncoding(reader.getEncoding());
                    // MNT-10642 Alfresco Explorer has javascript vulnerability opening HTML files
                    if (req.getRequestURI().contains("/d/d/") && (mimetype.equals("text/html") || mimetype.equals("application/xhtml+xml") || mimetype.equals("text/xml"))) {
                        String content = reader.getContentString();
                        if (mimetype.equals("text/html") || mimetype.equals("application/xhtml+xml")) {
                            // process with HTML stripper
                            content = StringUtils.stripUnsafeHTMLTags(content, false);
                        } else if (mimetype.equals("text/xml") && mimetype.equals("text/x-component")) {
                            // IE supports "behaviour" which means that css can load a .htc file that could
                            // contain XSS code in the form of jscript, vbscript etc, to stop it form being
                            // evaluated we set the contient type to text/plain
                            res.setContentType("text/plain");
                        }
                        String encoding = reader.getEncoding();
                        byte[] bytes = encoding != null ? content.getBytes(encoding) : content.getBytes();
                        res.setContentLength(bytes.length);
                        res.getOutputStream().write(bytes);
                        return;
                    }
                    // return the complete entity range
                    long size = reader.getSize();
                    res.setHeader(HEADER_CONTENT_RANGE, "bytes 0-" + Long.toString(size - 1L) + "/" + Long.toString(size));
                    res.setHeader(HEADER_CONTENT_LENGTH, Long.toString(size));
                    reader.getContent(res.getOutputStream());
                }
            } catch (SocketException e1) {
                // the client cut the connection - our mission was accomplished apart from a little error message
                if (logger.isDebugEnabled())
                    logger.debug("Client aborted stream read:\n\tnode: " + nodeRef + "\n\tcontent: " + reader);
            } catch (ContentIOException e2) {
                if (logger.isInfoEnabled())
                    logger.info("Failed stream read:\n\tnode: " + nodeRef + " due to: " + e2.getMessage());
            } catch (Throwable err) {
                if (err.getCause() instanceof SocketException) {
                    // the client cut the connection - our mission was accomplished apart from a little error message
                    if (logger.isDebugEnabled())
                        logger.debug("Client aborted stream read:\n\tnode: " + nodeRef + "\n\tcontent: " + reader);
                } else
                    throw err;
            }
        } else {
            if (logger.isDebugEnabled())
                logger.debug("HEAD request processed - no content sent.");
            res.getOutputStream().close();
        }
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException("Error during download content servlet processing: " + err.getMessage(), err);
    }
}
Also used : SocketException(java.net.SocketException) ArrayList(java.util.ArrayList) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) ContentIOException(org.alfresco.service.cmr.repository.ContentIOException) NodeRef(org.alfresco.service.cmr.repository.NodeRef) FileInfo(org.alfresco.service.cmr.model.FileInfo) HttpRangeProcessor(org.alfresco.repo.web.util.HttpRangeProcessor) StoreRef(org.alfresco.service.cmr.repository.StoreRef) Log(org.apache.commons.logging.Log) QName(org.alfresco.service.namespace.QName) NodeService(org.alfresco.service.cmr.repository.NodeService) FileContentReader(org.alfresco.repo.content.filestore.FileContentReader) ContentReader(org.alfresco.service.cmr.repository.ContentReader) ContentService(org.alfresco.service.cmr.repository.ContentService) Date(java.util.Date) StringTokenizer(java.util.StringTokenizer) MimetypeService(org.alfresco.service.cmr.repository.MimetypeService) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) ServiceRegistry(org.alfresco.service.ServiceRegistry)

Example 20 with FileNotFoundException

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

the class RepoStore method findNodeRef.

/**
 * Gets the node ref for the specified path within this repo store
 *
 * @param documentPath String
 * @return  node ref
 */
protected NodeRef findNodeRef(String documentPath) {
    NodeRef node = null;
    try {
        String[] pathElements = documentPath.split("/");
        List<String> pathElementsList = Arrays.asList(pathElements);
        FileInfo file = fileService.resolveNamePath(getBaseNodeRef(), pathElementsList);
        node = file.getNodeRef();
    } catch (FileNotFoundException e) {
    // NOTE: return null
    }
    return node;
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) FileInfo(org.alfresco.service.cmr.model.FileInfo) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException)

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