Search in sources :

Example 41 with AlfrescoRuntimeException

use of org.alfresco.error.AlfrescoRuntimeException in project acs-community-packaging by Alfresco.

the class CommandServlet method createCommandProcessor.

/**
 * Created the specified CommandProcessor instance. The name of the processor is looked up
 * in the client config, it should find a valid class impl and then create it.
 *
 * @param procName      Name of the CommandProcessor to lookup in the client config.
 *
 * @return CommandProcessor
 *
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
private CommandProcessor createCommandProcessor(String procName) throws InstantiationException, IllegalAccessException {
    Config config = Application.getConfigService(getServletContext()).getConfig("Command Servlet");
    if (config == null) {
        throw new AlfrescoRuntimeException("No command processors configured - unable to process any commands.");
    }
    CommandServletConfigElement configElement = (CommandServletConfigElement) config.getConfigElement(CommandServletConfigElement.CONFIG_ELEMENT_ID);
    if (configElement == null) {
        throw new AlfrescoRuntimeException("No command processors configured - unable to process any commands.");
    }
    Class clazz = configElement.getCommandProcessor(procName);
    Object obj = clazz.newInstance();
    if (obj instanceof CommandProcessor == false) {
        throw new AlfrescoRuntimeException("Configured command processor '" + procName + "' is does not implement interface CommandProcessor!");
    }
    return (CommandProcessor) obj;
}
Also used : Config(org.springframework.extensions.config.Config) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) ExtCommandProcessor(org.alfresco.web.app.servlet.command.ExtCommandProcessor) CommandProcessor(org.alfresco.web.app.servlet.command.CommandProcessor) CommandServletConfigElement(org.alfresco.web.config.CommandServletConfigElement)

Example 42 with AlfrescoRuntimeException

use of org.alfresco.error.AlfrescoRuntimeException in project acs-community-packaging by Alfresco.

the class CommandServlet method service.

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String uri = req.getRequestURI();
    if (logger.isDebugEnabled())
        logger.debug("Processing URL: " + uri + (req.getQueryString() != null ? ("?" + req.getQueryString()) : ""));
    AuthenticationStatus status = servletAuthenticate(req, res);
    if (status == AuthenticationStatus.Failure) {
        return;
    }
    setNoCacheHeaders(res);
    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();
    if (tokenCount < 3) {
        throw new IllegalArgumentException("Command Servlet URL did not contain all required args: " + uri);
    }
    // skip servlet name
    t.nextToken();
    // get the command processor to execute the command e.g. "workflow"
    String procName = t.nextToken();
    // get the command to perform
    String command = t.nextToken();
    // get any remaining uri elements to pass to the processor
    String[] urlElements = new String[tokenCount - 3];
    for (int i = 0; i < tokenCount - 3; i++) {
        urlElements[i] = t.nextToken();
    }
    // retrieve the URL arguments to pass to the processor
    Map<String, String> args = new HashMap<String, String>(8, 1.0f);
    Enumeration names = req.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        args.put(name, req.getParameter(name));
    }
    try {
        // get configured command processor by name from Config Service
        CommandProcessor processor = createCommandProcessor(procName);
        // validate that the processor has everything it needs to run the command
        if (processor.validateArguments(getServletContext(), command, args, urlElements) == false) {
            redirectToLoginPage(req, res, getServletContext());
            return;
        }
        ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
        UserTransaction txn = null;
        try {
            txn = serviceRegistry.getTransactionService().getUserTransaction();
            txn.begin();
            // inform the processor to execute the specified command
            if (processor instanceof ExtCommandProcessor) {
                ((ExtCommandProcessor) processor).process(serviceRegistry, req, res, command);
            } else {
                processor.process(serviceRegistry, req, command);
            }
            // commit the transaction
            txn.commit();
        } catch (Throwable txnErr) {
            try {
                if (txn != null) {
                    txn.rollback();
                }
            } catch (Exception tex) {
            }
            throw txnErr;
        }
        String returnPage = req.getParameter(ARG_RETURNPAGE);
        if (returnPage != null && returnPage.length() != 0) {
            validateReturnPage(returnPage, req);
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to specified return page: " + returnPage);
            res.sendRedirect(returnPage);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("No return page specified, displaying status output.");
            if (res.getContentType() == null && !res.isCommitted()) {
                res.setContentType("text/html");
                // request that the processor output a useful status message
                PrintWriter out = res.getWriter();
                processor.outputStatus(out);
                out.close();
            }
        }
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException("Error during command servlet processing: " + err.getMessage(), err);
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Enumeration(java.util.Enumeration) HashMap(java.util.HashMap) ExtCommandProcessor(org.alfresco.web.app.servlet.command.ExtCommandProcessor) MalformedURLException(java.net.MalformedURLException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) StringTokenizer(java.util.StringTokenizer) ExtCommandProcessor(org.alfresco.web.app.servlet.command.ExtCommandProcessor) CommandProcessor(org.alfresco.web.app.servlet.command.CommandProcessor) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) ServiceRegistry(org.alfresco.service.ServiceRegistry) PrintWriter(java.io.PrintWriter)

Example 43 with AlfrescoRuntimeException

use of org.alfresco.error.AlfrescoRuntimeException in project acs-community-packaging by Alfresco.

the class FacesHelper method getComponentGenerator.

/**
 * Retrieves the named component generator implementation.
 * If the named generator is not found the TextFieldGenerator is looked up
 * as a default, if this is also not found an AlfrescoRuntimeException is thrown.
 *
 * @param context FacesContext
 * @param generatorName The name of the component generator to retrieve
 * @return The component generator instance
 */
public static IComponentGenerator getComponentGenerator(FacesContext context, String generatorName) {
    IComponentGenerator generator = lookupComponentGenerator(context, generatorName);
    if (generator == null) {
        // create a text field if we can't find a component generator (a warning should have already been
        // displayed on the appserver console)
        logger.warn("Attempting to find default component generator '" + RepoConstants.GENERATOR_TEXT_FIELD + "'");
        generator = lookupComponentGenerator(context, RepoConstants.GENERATOR_TEXT_FIELD);
    }
    // if we still don't have a component generator we should abort as vital configuration is missing
    if (generator == null) {
        throw new AlfrescoRuntimeException("Failed to find a component generator, please ensure the '" + RepoConstants.GENERATOR_TEXT_FIELD + "' bean is present in your configuration");
    }
    return generator;
}
Also used : IComponentGenerator(org.alfresco.web.bean.generator.IComponentGenerator) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException)

Example 44 with AlfrescoRuntimeException

use of org.alfresco.error.AlfrescoRuntimeException in project records-management by Alfresco.

the class RecordServiceImpl method rejectRecord.

/**
 * @see org.alfresco.module.org_alfresco_module_rm.record.RecordService#rejectRecord(org.alfresco.service.cmr.repository.NodeRef, java.lang.String)
 */
@Override
public void rejectRecord(final NodeRef nodeRef, final String reason) {
    ParameterCheck.mandatory("NodeRef", nodeRef);
    ParameterCheck.mandatoryString("Reason", reason);
    // Save the id of the currently logged in user
    final String userId = AuthenticationUtil.getFullyAuthenticatedUser();
    // invoke policy
    invokeBeforeRecordRejection(nodeRef);
    // do the work of rejecting the record as the system user
    AuthenticationUtil.runAsSystem(new RunAsWork<Void>() {

        @Override
        public Void doWork() throws Exception {
            ruleService.disableRules();
            try {
                // get the latest version record, if there is one
                NodeRef latestVersionRecord = getLatestVersionRecord(nodeRef);
                if (latestVersionRecord != null) {
                    relationshipService.removeRelationship(CUSTOM_REF_VERSIONS.getLocalName(), nodeRef, latestVersionRecord);
                }
                // get record property values
                final Map<QName, Serializable> properties = nodeService.getProperties(nodeRef);
                final String recordId = (String) properties.get(PROP_IDENTIFIER);
                final String documentOwner = (String) properties.get(PROP_RECORD_ORIGINATING_USER_ID);
                final String originalName = (String) properties.get(PROP_ORIGIONAL_NAME);
                final NodeRef originatingLocation = (NodeRef) properties.get(PROP_RECORD_ORIGINATING_LOCATION);
                // we can only reject if the originating location is present
                if (originatingLocation != null) {
                    // first remove the secondary link association
                    final List<ChildAssociationRef> parentAssocs = nodeService.getParentAssocs(nodeRef);
                    for (ChildAssociationRef childAssociationRef : parentAssocs) {
                        if (!childAssociationRef.isPrimary() && childAssociationRef.getParentRef().equals(originatingLocation)) {
                            nodeService.removeChildAssociation(childAssociationRef);
                            break;
                        }
                    }
                    removeRmAspectsFrom(nodeRef);
                    // get the records primary parent association
                    final ChildAssociationRef parentAssoc = nodeService.getPrimaryParent(nodeRef);
                    // move the record into the collaboration site
                    nodeService.moveNode(nodeRef, originatingLocation, ContentModel.ASSOC_CONTAINS, parentAssoc.getQName());
                    // rename to the original name
                    if (originalName != null) {
                        fileFolderService.rename(nodeRef, originalName);
                        String name = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
                        LOGGER.debug("Rename {} to {}", name, originalName);
                    }
                    // save the information about the rejection details
                    final Map<QName, Serializable> aspectProperties = new HashMap<>(3);
                    aspectProperties.put(PROP_RECORD_REJECTION_USER_ID, userId);
                    aspectProperties.put(PROP_RECORD_REJECTION_DATE, new Date());
                    aspectProperties.put(PROP_RECORD_REJECTION_REASON, reason);
                    nodeService.addAspect(nodeRef, ASPECT_RECORD_REJECTION_DETAILS, aspectProperties);
                    // Restore the owner of the document
                    if (StringUtils.isBlank(documentOwner)) {
                        throw new AlfrescoRuntimeException("Unable to find the creator of document.");
                    }
                    ownableService.setOwner(nodeRef, documentOwner);
                    // clear the existing permissions
                    permissionService.clearPermission(nodeRef, null);
                    // restore permission inheritance
                    permissionService.setInheritParentPermissions(nodeRef, true);
                    // send an email to the record creator
                    notificationHelper.recordRejectedEmailNotification(nodeRef, recordId, documentOwner);
                }
            } finally {
                ruleService.enableRules();
            }
            return null;
        }

        /**
         * Removes all RM related aspects from the specified node and any rendition children.
         */
        private void removeRmAspectsFrom(NodeRef nodeRef) {
            // Note that when folder records are supported, we will need to recursively
            // remove aspects from their descendants.
            final Set<QName> aspects = nodeService.getAspects(nodeRef);
            for (QName aspect : aspects) {
                if (RM_URI.equals(aspect.getNamespaceURI()) || RecordableVersionModel.RMV_URI.equals(aspect.getNamespaceURI())) {
                    nodeService.removeAspect(nodeRef, aspect);
                }
            }
            for (ChildAssociationRef renditionAssoc : renditionService.getRenditions(nodeRef)) {
                final NodeRef renditionNode = renditionAssoc.getChildRef();
                // Do not attempt to clean up rendition nodes which are not children of their source node.
                final boolean renditionRequiresCleaning = nodeService.exists(renditionNode) && renditionAssoc.isPrimary();
                if (renditionRequiresCleaning) {
                    removeRmAspectsFrom(renditionNode);
                }
            }
        }
    });
    // invoke policy
    invokeOnRecordRejection(nodeRef);
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) QName(org.alfresco.service.namespace.QName) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) IntegrityException(org.alfresco.repo.node.integrity.IntegrityException) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) ModelAccessDeniedException(org.alfresco.module.org_alfresco_module_rm.model.security.ModelAccessDeniedException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) Date(java.util.Date) NodeRef(org.alfresco.service.cmr.repository.NodeRef) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) PropertyMap(org.alfresco.util.PropertyMap) HashMap(java.util.HashMap)

Example 45 with AlfrescoRuntimeException

use of org.alfresco.error.AlfrescoRuntimeException in project records-management by Alfresco.

the class RecordServiceImpl method createRecord.

/**
 * @see org.alfresco.module.org_alfresco_module_rm.record.RecordService#createRecord(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.cmr.repository.NodeRef, boolean)
 */
@Override
public void createRecord(final NodeRef filePlan, final NodeRef nodeRef, final boolean isLinked) {
    // filePlan can be null. In this case the default RM site will be used.
    ParameterCheck.mandatory("nodeRef", nodeRef);
    ParameterCheck.mandatory("isLinked", isLinked);
    recordCreationSanityCheckOnNode(nodeRef);
    final NodeRef checkedFilePlan = recordCreationSanityCheckOnFilePlan(filePlan);
    invokeBeforeRecordDeclaration(nodeRef);
    // do the work of creating the record as the system user
    AuthenticationUtil.runAsSystem(new RunAsWork<Void>() {

        @Override
        public Void doWork() {
            if (!nodeService.hasAspect(nodeRef, ASPECT_RECORD)) {
                // disable delete rules
                ruleService.disableRuleType("outbound");
                try {
                    // get the new record container for the file plan
                    NodeRef newRecordContainer = filePlanService.getUnfiledContainer(checkedFilePlan);
                    if (newRecordContainer == null) {
                        throw new AlfrescoRuntimeException("Unable to create record, because new record container could not be found.");
                    }
                    // get the documents readers and writers
                    Pair<Set<String>, Set<String>> readersAndWriters = extendedPermissionService.getReadersAndWriters(nodeRef);
                    // get the current owner
                    String owner = ownableService.getOwner(nodeRef);
                    // get the documents primary parent assoc
                    ChildAssociationRef parentAssoc = nodeService.getPrimaryParent(nodeRef);
                    // get the latest version record, if there is one
                    NodeRef latestVersionRecord = getLatestVersionRecord(nodeRef);
                    behaviourFilter.disableBehaviour();
                    try {
                        // move the document into the file plan
                        nodeService.moveNode(nodeRef, newRecordContainer, ContentModel.ASSOC_CONTAINS, parentAssoc.getQName());
                    } finally {
                        behaviourFilter.enableBehaviour();
                    }
                    // save the information about the originating details
                    Map<QName, Serializable> aspectProperties = new HashMap<QName, Serializable>(3);
                    aspectProperties.put(PROP_RECORD_ORIGINATING_LOCATION, parentAssoc.getParentRef());
                    aspectProperties.put(PROP_RECORD_ORIGINATING_USER_ID, owner);
                    aspectProperties.put(PROP_RECORD_ORIGINATING_CREATION_DATE, new Date());
                    nodeService.addAspect(nodeRef, ASPECT_RECORD_ORIGINATING_DETAILS, aspectProperties);
                    // make the document a record
                    makeRecord(nodeRef);
                    generateRecordIdentifier(nodeService, identifierService, nodeRef);
                    if (latestVersionRecord != null) {
                        // indicate that this is the 'final' record version
                        PropertyMap versionRecordProps = new PropertyMap(2);
                        versionRecordProps.put(RecordableVersionModel.PROP_VERSION_LABEL, I18NUtil.getMessage(FINAL_VERSION));
                        versionRecordProps.put(RecordableVersionModel.PROP_VERSION_DESCRIPTION, I18NUtil.getMessage(FINAL_DESCRIPTION));
                        nodeService.addAspect(nodeRef, RecordableVersionModel.ASPECT_VERSION_RECORD, versionRecordProps);
                        // link to previous version
                        relationshipService.addRelationship(CUSTOM_REF_VERSIONS.getLocalName(), nodeRef, latestVersionRecord);
                    }
                    if (isLinked) {
                        // turn off rules
                        ruleService.disableRules();
                        try {
                            // maintain the original primary location
                            nodeService.addChild(parentAssoc.getParentRef(), nodeRef, parentAssoc.getTypeQName(), parentAssoc.getQName());
                            // set the extended security
                            extendedSecurityService.set(nodeRef, readersAndWriters);
                        } finally {
                            ruleService.enableRules();
                        }
                    }
                } finally {
                    ruleService.enableRuleType("outbound");
                }
            }
            return null;
        }
    });
    invokeOnRecordDeclaration(nodeRef);
}
Also used : Serializable(java.io.Serializable) QName(org.alfresco.service.namespace.QName) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) Date(java.util.Date) NodeRef(org.alfresco.service.cmr.repository.NodeRef) PropertyMap(org.alfresco.util.PropertyMap) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) Map(java.util.Map) PropertyMap(org.alfresco.util.PropertyMap) HashMap(java.util.HashMap) Pair(org.alfresco.util.Pair)

Aggregations

AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)197 NodeRef (org.alfresco.service.cmr.repository.NodeRef)79 QName (org.alfresco.service.namespace.QName)39 HashMap (java.util.HashMap)38 IOException (java.io.IOException)32 ArrayList (java.util.ArrayList)31 JSONException (org.json.JSONException)23 ChildAssociationRef (org.alfresco.service.cmr.repository.ChildAssociationRef)22 Serializable (java.io.Serializable)20 M2Model (org.alfresco.repo.dictionary.M2Model)18 JSONObject (org.json.JSONObject)15 Date (java.util.Date)14 Map (java.util.Map)12 FacesContext (javax.faces.context.FacesContext)12 InputStream (java.io.InputStream)10 RetryingTransactionCallback (org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback)10 SiteInfo (org.alfresco.service.cmr.site.SiteInfo)10 JSONArray (org.json.JSONArray)10 List (java.util.List)8 FileNotFoundException (org.alfresco.service.cmr.model.FileNotFoundException)8