Search in sources :

Example 26 with ServiceRegistry

use of org.alfresco.service.ServiceRegistry in project acs-community-packaging by Alfresco.

the class DownloadRawContentServlet method processRequest.

/**
 * Processes the 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
 */
private void processRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String uri = req.getRequestURI();
    String contentUrl = req.getParameter(ARG_CONTENT_URL);
    if (contentUrl == null || contentUrl.length() == 0) {
        throw new IllegalArgumentException("Download URL did not contain parameter '" + ARG_CONTENT_URL + "':" + uri);
    }
    String infoOnlyStr = req.getParameter(ARG_INFO_ONLY);
    boolean infoOnly = (infoOnlyStr == null) ? false : Boolean.parseBoolean(infoOnlyStr);
    ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
    ContentService contentService = serviceRegistry.getContentService();
    // Attempt to get the reader
    ContentReader reader = null;
    try {
        reader = contentService.getRawReader(contentUrl);
        // If the content doesn't exist, generate an error
        if (!reader.exists()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Returning 204 Not Found error...");
            }
            res.sendError(HttpServletResponse.SC_NO_CONTENT);
            return;
        }
    } catch (AccessDeniedException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Returning 403 Forbidden error after exception: ", e);
        }
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    long readerSize = reader.getSize();
    Date readerLastModified = new Date(reader.getLastModified());
    String readerMimetype = reader.getMimetype();
    String readerEncoding = reader.getEncoding();
    Locale readerLocale = reader.getLocale();
    // Set the content info
    res.setHeader("alfresco.dr.size", DefaultTypeConverter.INSTANCE.convert(String.class, readerSize));
    res.setHeader("alfresco.dr.lastModified", DefaultTypeConverter.INSTANCE.convert(String.class, readerLastModified));
    res.setHeader("alfresco.dr.mimetype", readerMimetype);
    res.setHeader("alfresco.dr.encoding", readerEncoding);
    res.setHeader("alfresco.dr.locale", DefaultTypeConverter.INSTANCE.convert(String.class, readerLocale));
    // Pass the stream to the response, unless only the content info was requested
    if (infoOnly) {
        // Fill response details
        res.setContentType(DEFAULT_MIMETYPE);
        res.setCharacterEncoding(DEFAULT_ENCODING);
    } else {
        // Fill response details
        res.setContentType(readerMimetype);
        res.setCharacterEncoding(readerEncoding);
        try {
            OutputStream clientOs = res.getOutputStream();
            // Streams closed for us
            reader.getContent(clientOs);
        } catch (SocketException e1) {
            // Not a problem
            if (logger.isDebugEnabled()) {
                logger.debug("Client aborted stream read:\n" + "   Content URL: " + contentUrl);
            }
        } catch (ContentIOException e2) {
            // Not a problem
            if (logger.isDebugEnabled()) {
                logger.debug("Client aborted stream read:\n" + "   Content URL: " + contentUrl);
            }
        }
    }
}
Also used : Locale(java.util.Locale) SocketException(java.net.SocketException) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) ContentReader(org.alfresco.service.cmr.repository.ContentReader) OutputStream(java.io.OutputStream) ContentService(org.alfresco.service.cmr.repository.ContentService) Date(java.util.Date) ContentIOException(org.alfresco.service.cmr.repository.ContentIOException) ServiceRegistry(org.alfresco.service.ServiceRegistry)

Example 27 with ServiceRegistry

use of org.alfresco.service.ServiceRegistry in project acs-community-packaging by Alfresco.

the class UploadContentServlet method doPut.

/**
 * @see javax.servlet.http.HttpServlet#doPut(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (logger.isDebugEnabled() == true) {
        String queryString = req.getQueryString();
        logger.debug("Authenticating request to URL: " + req.getRequestURI() + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
    }
    AuthenticationStatus status = servletAuthenticate(req, res, false);
    if (status == AuthenticationStatus.Failure || status == AuthenticationStatus.Guest) {
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }
    // Tokenise the URI
    String uri = req.getRequestURI();
    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();
    // skip servlet name
    t.nextToken();
    // get or calculate the noderef and filename to download as
    NodeRef nodeRef = null;
    String filename = null;
    QName propertyQName = null;
    if (tokenCount == 2) {
        // filename is the only token
        filename = t.nextToken();
    } else if (tokenCount == 4 || tokenCount == 5) {
        // assume 'workspace' or other NodeRef based protocol for remaining URL
        // elements
        StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
        String id = t.nextToken();
        // build noderef from the appropriate URL elements
        nodeRef = new NodeRef(storeRef, id);
        if (tokenCount == 5) {
            // filename is last remaining token
            filename = t.nextToken();
        }
        // get qualified of the property to get content from - default to
        // ContentModel.PROP_CONTENT
        propertyQName = ContentModel.PROP_CONTENT;
        String property = req.getParameter(ARG_PROPERTY);
        if (property != null && property.length() != 0) {
            propertyQName = QName.createQName(property);
        }
    } else {
        logger.debug("Upload URL did not contain all required args: " + uri);
        res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
        return;
    }
    // get the services we need to retrieve the content
    ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
    ContentService contentService = serviceRegistry.getContentService();
    PermissionService permissionService = serviceRegistry.getPermissionService();
    MimetypeService mimetypeService = serviceRegistry.getMimetypeService();
    NodeService nodeService = serviceRegistry.getNodeService();
    InputStream is = req.getInputStream();
    BufferedInputStream inputStream = new BufferedInputStream(is);
    // Sort out the mimetype
    String mimetype = req.getParameter(ARG_MIMETYPE);
    if (mimetype == null || mimetype.length() == 0) {
        mimetype = MIMETYPE_OCTET_STREAM;
        if (filename != null) {
            MimetypeService mimetypeMap = serviceRegistry.getMimetypeService();
            int extIndex = filename.lastIndexOf('.');
            if (extIndex != -1) {
                String ext = filename.substring(extIndex + 1);
                mimetype = mimetypeService.getMimetype(ext);
            }
        }
    }
    // Get the encoding
    String encoding = req.getParameter(ARG_ENCODING);
    if (encoding == null || encoding.length() == 0) {
        // Get the encoding
        ContentCharsetFinder charsetFinder = mimetypeService.getContentCharsetFinder();
        Charset charset = charsetFinder.getCharset(inputStream, mimetype);
        encoding = charset.name();
    }
    // Get the locale
    Locale locale = I18NUtil.parseLocale(req.getParameter(ARG_LOCALE));
    if (locale == null) {
        locale = I18NUtil.getContentLocale();
        if (nodeRef != null) {
            ContentData contentData = (ContentData) nodeService.getProperty(nodeRef, propertyQName);
            if (contentData != null) {
                locale = contentData.getLocale();
            }
        }
    }
    if (logger.isDebugEnabled()) {
        if (nodeRef != null) {
            logger.debug("Found NodeRef: " + nodeRef.toString());
        }
        logger.debug("For property: " + propertyQName);
        logger.debug("File name: " + filename);
        logger.debug("Mimetype: " + mimetype);
        logger.debug("Encoding: " + encoding);
        logger.debug("Locale: " + locale);
    }
    // Check that the user has the permissions to write the content
    if (permissionService.hasPermission(nodeRef, PermissionService.WRITE_CONTENT) == AccessStatus.DENIED) {
        if (logger.isDebugEnabled() == true) {
            logger.debug("User does not have permissions to wrtie content for NodeRef: " + nodeRef.toString());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Returning 403 Forbidden error...");
        }
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    // Try and get the content writer
    ContentWriter writer = contentService.getWriter(nodeRef, propertyQName, true);
    if (writer == null) {
        if (logger.isDebugEnabled() == true) {
            logger.debug("Content writer cannot be obtained for NodeRef: " + nodeRef.toString());
        }
        res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
        return;
    }
    // Set the mimetype, encoding and locale
    writer.setMimetype(mimetype);
    writer.setEncoding(encoding);
    if (locale != null) {
        writer.setLocale(locale);
    }
    // Stream the content into the repository
    writer.putContent(inputStream);
    if (logger.isDebugEnabled() == true) {
        logger.debug("Content details: " + writer.getContentData().toString());
    }
    // Set return status
    res.getWriter().write(writer.getContentData().toString());
    res.flushBuffer();
    if (logger.isDebugEnabled() == true) {
        logger.debug("UploadContentServlet done");
    }
}
Also used : Locale(java.util.Locale) StoreRef(org.alfresco.service.cmr.repository.StoreRef) QName(org.alfresco.service.namespace.QName) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) NodeService(org.alfresco.service.cmr.repository.NodeService) ContentCharsetFinder(org.alfresco.repo.content.encoding.ContentCharsetFinder) Charset(java.nio.charset.Charset) ContentService(org.alfresco.service.cmr.repository.ContentService) PermissionService(org.alfresco.service.cmr.security.PermissionService) NodeRef(org.alfresco.service.cmr.repository.NodeRef) StringTokenizer(java.util.StringTokenizer) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) ContentData(org.alfresco.service.cmr.repository.ContentData) BufferedInputStream(java.io.BufferedInputStream) MimetypeService(org.alfresco.service.cmr.repository.MimetypeService) ServiceRegistry(org.alfresco.service.ServiceRegistry)

Example 28 with ServiceRegistry

use of org.alfresco.service.ServiceRegistry in project acs-community-packaging by Alfresco.

the class AdvancedSearchDialog method selectSearch.

/**
 * Action handler called when a saved search is selected by the user
 */
public void selectSearch(ActionEvent event) {
    if (NO_SELECTION.equals(properties.getSavedSearch()) == false) {
        // read an XML serialized version of the SearchContext object
        NodeRef searchSearchRef = new NodeRef(Repository.getStoreRef(), properties.getSavedSearch());
        ServiceRegistry services = Repository.getServiceRegistry(FacesContext.getCurrentInstance());
        ContentService cs = services.getContentService();
        try {
            if (services.getNodeService().exists(searchSearchRef)) {
                ContentReader reader = cs.getReader(searchSearchRef, ContentModel.PROP_CONTENT);
                SearchContext search = new SearchContext().fromXML(reader.getContentString());
                // if we get here we read the serialized object successfully
                // now setup the UI to match the new SearchContext object
                initialiseFromContext(search);
            }
        } catch (Throwable err) {
            Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_RESTORE_SEARCH), err.getMessage()), err);
        }
    }
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentReader(org.alfresco.service.cmr.repository.ContentReader) ServiceRegistry(org.alfresco.service.ServiceRegistry) ContentService(org.alfresco.service.cmr.repository.ContentService)

Example 29 with ServiceRegistry

use of org.alfresco.service.ServiceRegistry in project acs-community-packaging by Alfresco.

the class User method getUserPreferencesRef.

/**
 * Get or create the node used to store user preferences.
 * Utilises the 'configurable' aspect on the Person linked to this user.
 */
synchronized NodeRef getUserPreferencesRef(WebApplicationContext context) {
    final ServiceRegistry registry = (ServiceRegistry) context.getBean("ServiceRegistry");
    final NodeService nodeService = registry.getNodeService();
    final SearchService searchService = registry.getSearchService();
    final NamespaceService namespaceService = registry.getNamespaceService();
    final TransactionService txService = registry.getTransactionService();
    final ConfigurableService configurableService = (ConfigurableService) context.getBean("ConfigurableService");
    RetryingTransactionHelper txnHelper = registry.getTransactionService().getRetryingTransactionHelper();
    return txnHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>() {

        public NodeRef execute() throws Throwable {
            NodeRef prefRef = null;
            NodeRef person = getPerson();
            if (nodeService.hasAspect(person, ApplicationModel.ASPECT_CONFIGURABLE) == false) {
                // if the repository is in read-only mode just return null
                if (txService.isReadOnly()) {
                    return null;
                } else {
                    // create the configuration folder for this Person node
                    configurableService.makeConfigurable(person);
                }
            }
            // target of the assoc is the configurations folder ref
            NodeRef configRef = configurableService.getConfigurationFolder(person);
            if (configRef == null) {
                throw new IllegalStateException("Unable to find associated 'configurations' folder for node: " + person);
            }
            String xpath = NamespaceService.APP_MODEL_PREFIX + ":" + "preferences";
            List<NodeRef> nodes = searchService.selectNodes(configRef, xpath, null, namespaceService, false);
            if (nodes.size() == 1) {
                prefRef = nodes.get(0);
            } else {
                // create the preferences Node for this user (if repo is not read-only)
                if (txService.isReadOnly() == false) {
                    ChildAssociationRef childRef = nodeService.createNode(configRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.APP_MODEL_1_0_URI, "preferences"), ContentModel.TYPE_CMOBJECT);
                    prefRef = childRef.getChildRef();
                }
            }
            return prefRef;
        }
    }, txService.isReadOnly());
}
Also used : TransactionService(org.alfresco.service.transaction.TransactionService) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) NodeService(org.alfresco.service.cmr.repository.NodeService) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) NodeRef(org.alfresco.service.cmr.repository.NodeRef) NamespaceService(org.alfresco.service.namespace.NamespaceService) SearchService(org.alfresco.service.cmr.search.SearchService) List(java.util.List) ServiceRegistry(org.alfresco.service.ServiceRegistry) ConfigurableService(org.alfresco.repo.configuration.ConfigurableService)

Example 30 with ServiceRegistry

use of org.alfresco.service.ServiceRegistry in project acs-community-packaging by Alfresco.

the class UIRepositoryProperties method getDebugData.

/**
 * @see org.alfresco.web.ui.common.component.debug.BaseDebugComponent#getDebugData()
 */
@SuppressWarnings("unchecked")
public Map getDebugData() {
    // note: sort properties
    Map properties = new TreeMap();
    FacesContext fc = FacesContext.getCurrentInstance();
    ServiceRegistry services = Repository.getServiceRegistry(fc);
    DescriptorService descriptorService = services.getDescriptorService();
    Descriptor installedRepoDescriptor = descriptorService.getInstalledRepositoryDescriptor();
    properties.put("Installed Version", installedRepoDescriptor.getVersion());
    properties.put("Installed Schema", installedRepoDescriptor.getSchema());
    Descriptor systemDescriptor = descriptorService.getServerDescriptor();
    properties.put("Server Version", systemDescriptor.getVersion());
    properties.put("Server Schema", systemDescriptor.getSchema());
    WebApplicationContext cx = FacesContextUtils.getRequiredWebApplicationContext(fc);
    PatchService patchService = (PatchService) cx.getBean("PatchService");
    List<AppliedPatch> patches = patchService.getPatches(null, null);
    for (AppliedPatch patch : patches) {
        StringBuilder data = new StringBuilder(256);
        data.append(patch.getAppliedOnDate()).append(" - ").append(patch.getDescription()).append(" - ").append(patch.getSucceeded() == true ? Application.getMessage(fc, "repository_patch_succeeded") : Application.getMessage(fc, "repository_patch_failed"));
        properties.put(patch.getId(), data);
    }
    return properties;
}
Also used : FacesContext(javax.faces.context.FacesContext) Descriptor(org.alfresco.service.descriptor.Descriptor) ServiceRegistry(org.alfresco.service.ServiceRegistry) TreeMap(java.util.TreeMap) DescriptorService(org.alfresco.service.descriptor.DescriptorService) TreeMap(java.util.TreeMap) Map(java.util.Map) PatchService(org.alfresco.repo.admin.patch.PatchService) WebApplicationContext(org.springframework.web.context.WebApplicationContext) AppliedPatch(org.alfresco.repo.admin.patch.AppliedPatch)

Aggregations

ServiceRegistry (org.alfresco.service.ServiceRegistry)32 NodeRef (org.alfresco.service.cmr.repository.NodeRef)17 NodeService (org.alfresco.service.cmr.repository.NodeService)8 FacesContext (javax.faces.context.FacesContext)7 MimetypeService (org.alfresco.service.cmr.repository.MimetypeService)6 QName (org.alfresco.service.namespace.QName)6 StringTokenizer (java.util.StringTokenizer)5 Serializable (java.io.Serializable)4 HashMap (java.util.HashMap)4 SelectItem (javax.faces.model.SelectItem)4 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)4 ContentService (org.alfresco.service.cmr.repository.ContentService)4 ContentWriter (org.alfresco.service.cmr.repository.ContentWriter)4 StoreRef (org.alfresco.service.cmr.repository.StoreRef)4 PermissionService (org.alfresco.service.cmr.security.PermissionService)4 TransactionService (org.alfresco.service.transaction.TransactionService)4 QuickSort (org.alfresco.web.data.QuickSort)4 SocketException (java.net.SocketException)3 Map (java.util.Map)3 UserTransaction (javax.transaction.UserTransaction)3