Search in sources :

Example 6 with RunAsWork

use of org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork in project records-management by Alfresco.

the class RMCaveatConfigComponentImpl method validateAndReset.

/**
 * Validate the caveat config and optionally update the cache.
 *
 * @param nodeRef The nodeRef of the config
 * @param updateCache Set to <code>true</code> to update the cache
 */
@SuppressWarnings("unchecked")
protected void validateAndReset(NodeRef nodeRef) {
    ContentReader cr = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
    if (cr != null) {
        // TODO - check who can change caveat config !
        // TODO - locking (or checkout/checkin)
        String caveatConfigData = cr.getContentString();
        if (caveatConfigData != null) {
            NodeRef existing = getCaveatConfigNode();
            if ((existing != null && (!existing.equals(nodeRef)))) {
                throw new AlfrescoRuntimeException("Cannot create more than one caveat config (existing=" + existing + ", new=" + nodeRef + ")");
            }
            try {
                if (logger.isTraceEnabled()) {
                    logger.trace(caveatConfigData);
                }
                Set<QName> models = new HashSet<QName>(1);
                Set<QName> props = new HashSet<QName>(10);
                Set<String> expectedPrefixes = new HashSet<String>(10);
                if (caveatModelQNames.size() > 0) {
                    models.addAll(caveatModelQNames);
                } else {
                    models.addAll(dictionaryService.getAllModels());
                }
                if (logger.isTraceEnabled()) {
                    logger.trace("validateAndReset: models to check " + models);
                }
                for (QName model : models) {
                    props.addAll(dictionaryService.getProperties(model, DATATYPE_TEXT));
                    expectedPrefixes.addAll(namespaceService.getPrefixes(model.getNamespaceURI()));
                }
                if (props.size() == 0) {
                    logger.warn("validateAndReset: no caveat properties found");
                } else {
                    if (logger.isTraceEnabled()) {
                        logger.trace("validateAndReset: properties to check " + props);
                    }
                }
                Map<String, Object> caveatConfigMap = JSONtoFmModel.convertJSONObjectToMap(caveatConfigData);
                for (Map.Entry<String, Object> conEntry : caveatConfigMap.entrySet()) {
                    String conStr = conEntry.getKey();
                    QName conQName = QName.resolveToQName(namespaceService, conStr);
                    // check prefix
                    String conPrefix = QName.splitPrefixedQName(conStr)[0];
                    boolean prefixFound = false;
                    for (String expectedPrefix : expectedPrefixes) {
                        if (conPrefix.equals(expectedPrefix)) {
                            prefixFound = true;
                        }
                    }
                    if (!prefixFound) {
                        throw new AlfrescoRuntimeException("Unexpected prefix: " + conPrefix + " (" + conStr + ") expected one of " + expectedPrefixes + ")");
                    }
                    Map<String, List<String>> caveatMap = (Map<String, List<String>>) conEntry.getValue();
                    List<String> allowedValues = null;
                    @SuppressWarnings("unused") boolean found = false;
                    for (QName propertyName : props) {
                        PropertyDefinition propDef = dictionaryService.getProperty(propertyName);
                        List<ConstraintDefinition> conDefs = propDef.getConstraints();
                        for (ConstraintDefinition conDef : conDefs) {
                            final Constraint con = conDef.getConstraint();
                            if (con instanceof RMListOfValuesConstraint) {
                                String conName = ((RMListOfValuesConstraint) con).getShortName();
                                if (conName.equals(conStr)) {
                                    // note: assumes only one caveat/LOV against a given property
                                    allowedValues = AuthenticationUtil.runAs(new RunAsWork<List<String>>() {

                                        public List<String> doWork() {
                                            return ((RMListOfValuesConstraint) con).getAllowedValues();
                                        }
                                    }, AuthenticationUtil.getSystemUserName());
                                    found = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (allowedValues != null) {
                        if (logger.isInfoEnabled()) {
                            logger.info("Processing constraint: " + conQName);
                        }
                        for (Map.Entry<String, List<String>> caveatEntry : caveatMap.entrySet()) {
                            String authorityName = caveatEntry.getKey();
                            List<String> caveatList = caveatEntry.getValue();
                            // validate authority (user or group) - note: groups are configured with fullname (ie. GROUP_xxx)
                            if ((!authorityService.authorityExists(authorityName) && !personService.personExists(authorityName))) {
                                // TODO - review warnings (& I18N)
                                String msg = "User/group does not exist: " + authorityName + " (constraint=" + conStr + ")";
                                logger.warn(msg);
                            }
                            // validate caveat list
                            for (String value : caveatList) {
                                if (!allowedValues.contains(value)) {
                                    // TODO - review warnings (& add I18N)
                                    String msg = "Invalid value in list: " + value + " (authority=" + authorityName + ", constraint=" + conStr + ")";
                                    logger.warn(msg);
                                }
                            }
                        }
                    }
                }
                try {
                    writeLock.lock();
                    // we can't just clear the cache, as all puts to the cache afterwards in this transaction will be ignored
                    // first delete all keys that are now not in the config
                    caveatConfig.getKeys().retainAll(caveatConfigMap.keySet());
                    for (Map.Entry<String, Object> conEntry : caveatConfigMap.entrySet()) {
                        String conStr = conEntry.getKey();
                        Map<String, List<String>> caveatMap = (Map<String, List<String>>) conEntry.getValue();
                        Map<String, List<String>> cacheValue = caveatConfig.get(conStr);
                        if (cacheValue == null || !cacheValue.equals(caveatMap)) {
                            // update the cache
                            caveatConfig.put(conStr, caveatMap);
                        }
                    }
                } finally {
                    writeLock.unlock();
                }
            } catch (JSONException e) {
                throw new AlfrescoRuntimeException("Invalid caveat config syntax: " + e);
            }
        }
    }
}
Also used : Constraint(org.alfresco.service.cmr.dictionary.Constraint) RunAsWork(org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork) NodeRef(org.alfresco.service.cmr.repository.NodeRef) List(java.util.List) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) QName(org.alfresco.service.namespace.QName) ContentReader(org.alfresco.service.cmr.repository.ContentReader) JSONException(org.json.JSONException) PropertyDefinition(org.alfresco.service.cmr.dictionary.PropertyDefinition) ConstraintDefinition(org.alfresco.service.cmr.dictionary.ConstraintDefinition) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) JSONObject(org.json.JSONObject) Map(java.util.Map) MimetypeMap(org.alfresco.repo.content.MimetypeMap) HashMap(java.util.HashMap)

Example 7 with RunAsWork

use of org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork in project records-management by Alfresco.

the class FreezeServiceImpl method hasFrozenChildren.

/**
 * @see org.alfresco.module.org_alfresco_module_rm.freeze.FreezeService#hasFrozenChildren(org.alfresco.service.cmr.repository.NodeRef)
 */
@Override
public boolean hasFrozenChildren(final NodeRef nodeRef) {
    ParameterCheck.mandatory("nodeRef", nodeRef);
    boolean result = false;
    // check that we are dealing with a record folder
    if (isRecordFolder(nodeRef)) {
        int heldCount = 0;
        if (nodeService.hasAspect(nodeRef, ASPECT_HELD_CHILDREN)) {
            heldCount = (Integer) getInternalNodeService().getProperty(nodeRef, PROP_HELD_CHILDREN_COUNT);
        } else {
            final TransactionService transactionService = (TransactionService) applicationContext.getBean("transactionService");
            heldCount = AuthenticationUtil.runAsSystem(new RunAsWork<Integer>() {

                @Override
                public Integer doWork() {
                    return transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Integer>() {

                        public Integer execute() throws Throwable {
                            int heldCount = 0;
                            // NOTE: this process remains to 'patch' older systems to improve performance next time around
                            List<ChildAssociationRef> childAssocs = getInternalNodeService().getChildAssocs(nodeRef, ContentModel.ASSOC_CONTAINS, null);
                            if (childAssocs != null && !childAssocs.isEmpty()) {
                                for (ChildAssociationRef childAssociationRef : childAssocs) {
                                    NodeRef record = childAssociationRef.getChildRef();
                                    if (childAssociationRef.isPrimary() && isRecord(record) && isFrozen(record)) {
                                        heldCount++;
                                    }
                                }
                            }
                            // add aspect and set count
                            Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
                            props.put(PROP_HELD_CHILDREN_COUNT, heldCount);
                            getInternalNodeService().addAspect(nodeRef, ASPECT_HELD_CHILDREN, props);
                            return heldCount;
                        }
                    }, false, true);
                }
            });
        }
        // true if more than one child held
        result = (heldCount > 0);
    }
    return result;
}
Also used : Serializable(java.io.Serializable) TransactionService(org.alfresco.service.transaction.TransactionService) RunAsWork(org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork) QName(org.alfresco.service.namespace.QName) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with RunAsWork

use of org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork in project records-management by Alfresco.

the class FilingPermissionsOnTransferFolderTest method testFilingPermissionsOnTransferFolder.

public void testFilingPermissionsOnTransferFolder() {
    doBehaviourDrivenTest(new BehaviourDrivenTest(testUser1) {

        // Records folder
        private NodeRef recordsFolder = null;

        // Transfer folder
        private NodeRef transferFolder = null;

        /**
         * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#given()
         */
        @Override
        public void given() {
            runAs(new RunAsWork<Void>() {

                public Void doWork() {
                    // Create category
                    NodeRef category = filePlanService.createRecordCategory(filePlan, generate());
                    // Give filing permissions for the test users on the category
                    filePlanPermissionService.setPermission(category, testUser1, FILING);
                    filePlanPermissionService.setPermission(category, testUser2, FILING);
                    // Create disposition schedule
                    utils.createDispositionSchedule(category, DEFAULT_DISPOSITION_INSTRUCTIONS, DEFAULT_DISPOSITION_AUTHORITY, false, true, true);
                    // Create folder
                    recordsFolder = recordFolderService.createRecordFolder(category, generate());
                    // Make eligible for cut off
                    Map<String, Serializable> params = new HashMap<String, Serializable>(1);
                    params.put(PARAM_EVENT_NAME, DEFAULT_EVENT_NAME);
                    rmActionService.executeRecordsManagementAction(recordsFolder, CompleteEventAction.NAME, params);
                    // Cut off folder
                    rmActionService.executeRecordsManagementAction(recordsFolder, CutOffAction.NAME);
                    return null;
                }
            }, getAdminUserName());
            // FIXME: This step should be executed in "when()".
            // See RM-3931
            transferFolder = (NodeRef) rmActionService.executeRecordsManagementAction(recordsFolder, TransferAction.NAME).getValue();
        }

        /**
         * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#when()
         */
        @Override
        public void when() {
            // FIXME: If the transfer step is executed here the test fails. See RM-3931
            // transferFolder = (NodeRef) rmActionService.executeRecordsManagementAction(recordsFolder, TransferAction.NAME).getValue();
            // Give testUser2 filing permissions on transfer folder
            filePlanPermissionService.setPermission(transferFolder, testUser2, FILING);
        }

        /**
         * @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseRMTestCase.BehaviourDrivenTest#then()
         */
        @Override
        public void then() {
            // Check transfer folder
            assertNotNull(transferFolder);
            // testUser1 should have read permissions on the transfers container
            assertEquals(ALLOWED, permissionService.hasPermission(transfersContainer, READ_RECORDS));
            // Check if testUser1 has filing permissions on the transfer folder
            assertEquals(ALLOWED, permissionService.hasPermission(transferFolder, FILING));
            runAs(new RunAsWork<Void>() {

                public Void doWork() {
                    // Check transfer folder
                    assertNotNull(transferFolder);
                    // testUser2 should have read permissions on the transfers container
                    assertEquals(ALLOWED, permissionService.hasPermission(transfersContainer, READ_RECORDS));
                    // Check if testUser2 has read permissions on the transfer folder
                    assertEquals(ALLOWED, permissionService.hasPermission(transferFolder, READ_RECORDS));
                    // Check if testUser2 has filing permissions on the transfer folder
                    assertEquals(ALLOWED, permissionService.hasPermission(transferFolder, FILING));
                    return null;
                }
            }, testUser2);
        }
    });
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) Serializable(java.io.Serializable) RunAsWork(org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork) HashMap(java.util.HashMap)

Example 9 with RunAsWork

use of org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork in project records-management by Alfresco.

the class RecordsManagementSearchServiceImpl method saveSearch.

/**
 * @see org.alfresco.module.org_alfresco_module_rm.search.RecordsManagementSearchService#saveSearch(org.alfresco.module.org_alfresco_module_rm.search.SavedSearchDetails)
 */
@Override
public SavedSearchDetails saveSearch(final SavedSearchDetails savedSearchDetails) {
    // Check for mandatory parameters
    ParameterCheck.mandatory("savedSearchDetails", savedSearchDetails);
    // Get the root saved search container
    final String siteId = savedSearchDetails.getSiteId();
    NodeRef container = siteService.getContainer(siteId, SEARCH_CONTAINER);
    if (container == null) {
        container = AuthenticationUtil.runAs(new RunAsWork<NodeRef>() {

            @Override
            public NodeRef doWork() {
                return siteService.createContainer(siteId, SEARCH_CONTAINER, null, null);
            }
        }, AuthenticationUtil.getSystemUserName());
    }
    // Get the private container for the current user
    if (!savedSearchDetails.isPublic()) {
        final String userName = AuthenticationUtil.getFullyAuthenticatedUser();
        NodeRef userContainer = fileFolderService.searchSimple(container, userName);
        if (userContainer == null) {
            final NodeRef parentContainer = container;
            userContainer = AuthenticationUtil.runAs(new RunAsWork<NodeRef>() {

                @Override
                public NodeRef doWork() {
                    return fileFolderService.create(parentContainer, userName, ContentModel.TYPE_FOLDER).getNodeRef();
                }
            }, AuthenticationUtil.getSystemUserName());
        }
        container = userContainer;
    }
    // Get the saved search node
    NodeRef searchNode = fileFolderService.searchSimple(container, savedSearchDetails.getName());
    if (searchNode == null) {
        final NodeRef searchContainer = container;
        searchNode = AuthenticationUtil.runAs(new RunAsWork<NodeRef>() {

            @Override
            public NodeRef doWork() {
                return fileFolderService.create(searchContainer, savedSearchDetails.getName(), ContentModel.TYPE_CONTENT).getNodeRef();
            }
        }, AuthenticationUtil.getSystemUserName());
    }
    nodeService.addAspect(searchNode, ASPECT_SAVED_SEARCH, null);
    // Write the JSON content to search node
    final NodeRef writableSearchNode = searchNode;
    AuthenticationUtil.runAs(new RunAsWork<Void>() {

        @Override
        public Void doWork() {
            ContentWriter writer = fileFolderService.getWriter(writableSearchNode);
            writer.setEncoding("UTF-8");
            writer.setMimetype(MimetypeMap.MIMETYPE_JSON);
            writer.putContent(savedSearchDetails.toJSONString());
            return null;
        }
    }, AuthenticationUtil.getSystemUserName());
    return savedSearchDetails;
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) RunAsWork(org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork)

Example 10 with RunAsWork

use of org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork in project records-management by Alfresco.

the class AdHocRecordableVersionsTest method testRecordedVersionWithRecordMetadataAspect.

/**
 * Test recorded version with record metadata aspect (want to ensure additional non-rm URI properties and aspects
 * don't find their way into the frozen state)
 */
public void testRecordedVersionWithRecordMetadataAspect() {
    doBehaviourDrivenTest(new BehaviourDrivenTest(dmCollaborator) {

        private Map<String, Serializable> versionProperties;

        public void given() throws Exception {
            // setup version properties
            versionProperties = new HashMap<String, Serializable>(4);
            versionProperties.put(Version.PROP_DESCRIPTION, DESCRIPTION);
            versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
            versionProperties.put(RecordableVersionServiceImpl.KEY_RECORDABLE_VERSION, true);
            versionProperties.put(RecordableVersionServiceImpl.KEY_FILE_PLAN, filePlan);
        }

        public void when() {
            // create version
            final Version version = versionService.createVersion(dmDocument, versionProperties);
            AuthenticationUtil.runAs(new RunAsWork<Void>() {

                public Void doWork() throws Exception {
                    // add custom meta-data to record
                    NodeRef record = recordableVersionService.getVersionRecord(version);
                    assertNotNull(record);
                    recordService.addRecordType(record, TestModel.ASPECT_RECORD_METADATA);
                    nodeService.setProperty(record, TestModel.PROPERTY_RECORD_METADATA, "Peter Wetherall");
                    return null;
                }
            }, AuthenticationUtil.getAdminUserName());
        }

        public void then() {
            // check that the record has been recorded
            checkRecordedVersion(dmDocument, DESCRIPTION, "0.1");
        }
    });
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) Serializable(java.io.Serializable) HashMap(java.util.HashMap) Version(org.alfresco.service.cmr.version.Version) RunAsWork(org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException)

Aggregations

RunAsWork (org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork)34 NodeRef (org.alfresco.service.cmr.repository.NodeRef)26 HashMap (java.util.HashMap)11 Serializable (java.io.Serializable)8 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)7 FileNotFoundException (org.alfresco.service.cmr.model.FileNotFoundException)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 FileExistsException (org.alfresco.service.cmr.model.FileExistsException)4 ContentWriter (org.alfresco.service.cmr.repository.ContentWriter)4 QName (org.alfresco.service.namespace.QName)4 HashSet (java.util.HashSet)3 Map (java.util.Map)3 Set (java.util.Set)3 AccessDeniedException (org.alfresco.repo.security.permissions.AccessDeniedException)3 ChildAssociationRef (org.alfresco.service.cmr.repository.ChildAssociationRef)3 SiteInfo (org.alfresco.service.cmr.site.SiteInfo)3 Version (org.alfresco.service.cmr.version.Version)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2