Java Code Examples for org.alfresco.repo.transaction.RetryingTransactionHelper#doInTransaction()

The following examples show how to use org.alfresco.repo.transaction.RetryingTransactionHelper#doInTransaction() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResourceWebScriptDelete.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Void execute(final ResourceWithMetadata resource, final Params params, final WebScriptResponse res, boolean isReadOnly)
{
    final ResourceOperation operation = resource.getMetaData().getOperation(HttpMethod.DELETE);
    final WithResponse callBack = new WithResponse(operation.getSuccessStatus(), DEFAULT_JSON_CONTENT,CACHE_NEVER);

    // MNT-20308 - allow write transactions for authentication api
    RetryingTransactionHelper transHelper = getTransactionHelper(resource.getMetaData().getApi().getName());

    transHelper.doInTransaction(
        new RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                executeAction(resource, params, callBack); //ignore return result
                return null;
            }
        }, false, true);
    setResponse(res,callBack);
    return null;

}
 
Example 2
Source File: NodeArchiveServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This is the primary purge methd that all purge methods fall back on.  It isolates the delete
 * work in a new transaction.
 */
public void purgeArchivedNode(final NodeRef archivedNodeRef)
{
    RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
    RetryingTransactionCallback<Void> deleteCallback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Exception
        {
            if (!nodeService.exists(archivedNodeRef))
            {
                // Node has disappeared
                return null;
            }
            invokeBeforePurgeNode(archivedNodeRef);
            nodeService.deleteNode(archivedNodeRef);
            return null;
        }
    };
    txnHelper.doInTransaction(deleteCallback, false, true);
}
 
Example 3
Source File: AbstractMimeMessage.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected void buildMessage(FileInfo fileInfo, ServiceRegistry serviceRegistry) throws MessagingException
{
    checkParameter(serviceRegistry, "ServiceRegistry");
    this.content = null;
    this.serviceRegistry = serviceRegistry;
    this.imapService = serviceRegistry.getImapService();
    this.messageFileInfo = fileInfo;
    this.isMessageInSitesLibrary = imapService.getNodeSiteContainer(messageFileInfo.getNodeRef()) != null ? true : false;
    RetryingTransactionHelper txHelper = serviceRegistry.getTransactionService().getRetryingTransactionHelper();
    txHelper.setMaxRetries(MAX_RETRIES);
    txHelper.setReadOnly(false);
    txHelper.doInTransaction(new RetryingTransactionCallback<Object>() {
        public Object execute() throws Throwable
        {
            buildMessageInternal();
            return null;
        }
    }, false);
    
}
 
Example 4
Source File: TemporaryNodes.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This method creates a cm:folder NodeRef and adds it to the internal list of NodeRefs to be tidied up by the rule.
 * This method will be run in its own transaction and will be run with the specified user as the fully authenticated user,
 * thus ensuring the named user is the cm:creator of the new node.
 * 
 * @param parentNode the parent node
 * @param nodeCmName the cm:name of the new node
 * @param nodeCreator the username of the person who will create the node
 * @return the newly created NodeRef.
 */
public NodeRef createFolder(final NodeRef parentNode, final String nodeCmName, final String nodeCreator)
{
    final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) appContextRule.getApplicationContext().getBean("retryingTransactionHelper");
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(nodeCreator);
    
    NodeRef newNodeRef = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            final NodeRef result = createNode(nodeCmName, parentNode, ContentModel.TYPE_FOLDER);
            
            return result;
        }
    });
    
    AuthenticationUtil.popAuthentication();
    
    this.temporaryNodeRefs.add(newNodeRef);
    return newNodeRef;
}
 
Example 5
Source File: DescriptorServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Ensures that a repository Descriptor is available.
 * This is done here to prevent flip-flopping on the license mode
 * during startup i.e. the Enterprise mode will be set once when
 * the real license is validated.
 */
public void verifyLicense() throws LicenseException
{
    synchronized (licenseLock)
    {
        if (isCurrentRepoDescriptorIsNull())
        {
            final RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();

            RetryingTransactionCallback<Void> nopLoadLicense = new RetryingTransactionCallback<Void>()
            {
                @Override
                public Void execute()
                {
                    Descriptor newRepoDescriptor = currentRepoDescriptorDAO.updateDescriptor(serverDescriptor, LicenseMode.UNKNOWN);
                    setCurrentRepoDescriptor(newRepoDescriptor);
                    return null;
                }
            };

            txnHelper.doInTransaction(nopLoadLicense, false, false);
        }
    }
}
 
Example 6
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected MimeMessage sendMessage(String from, String subject, String template, String bodyText, final Action mailAction)
{
    if (from != null)
    {
        mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, from);
    }
    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, subject);
    if (template != null)
    {
        mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, template);
        mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, getModel());
    }
    else
    {
        mailAction.setParameterValue(MailActionExecuter.PARAM_TEXT, bodyText);
    }

    RetryingTransactionHelper txHelper = APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);

    return txHelper.doInTransaction(new RetryingTransactionCallback<MimeMessage>()
    {
        @Override
        public MimeMessage execute() throws Throwable
        {
            ACTION_SERVICE.executeAction(mailAction, null);

            return ACTION_EXECUTER.retrieveLastTestMessage();
        }
    }, true);
}
 
Example 7
Source File: PersonServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void makeHomeFolderIfRequired(NodeRef person)
{
    if ((person != null) && (homeFolderCreationDisabled == false))
    {
        NodeRef homeFolder = DefaultTypeConverter.INSTANCE.convert(NodeRef.class, nodeService.getProperty(person, ContentModel.PROP_HOMEFOLDER));
        if (homeFolder == null)
        {
            final ChildAssociationRef ref = nodeService.getPrimaryParent(person);
            RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
            txnHelper.setForceWritable(true);
            boolean requiresNew = false;
            if (AlfrescoTransactionSupport.getTransactionReadState() != TxnReadState.TXN_READ_WRITE)
            {
                // We can be in a read-only transaction, so force a new transaction
                // Note that the transaction will *always* be in read-only mode if the server read-only veto is there 
                requiresNew = true;
            }
            txnHelper.doInTransaction(new RetryingTransactionCallback<Object>()
            {
                public Object execute() throws Throwable
                {
                    makeHomeFolderAsSystem(ref);
                    return null;
                }
            }, false, requiresNew);
        }
    }
}
 
Example 8
Source File: AlfrescoPerson.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override protected void after()
{
    ApplicationContext ctxt = getApplicationContext();
    RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) ctxt.getBean("retryingTransactionHelper");
    
    transactionHelper.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override public Void execute() throws Throwable
        {
            deletePerson(userName);
            
            return null;
        }
    });
}
 
Example 9
Source File: AbstractImapFolder.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public T runFeedback(boolean readOnly) throws FolderException
{
    try
    {
        RetryingTransactionHelper txHelper = serviceRegistry.getTransactionService().getRetryingTransactionHelper();
        txHelper.setMaxRetries(MAX_RETRIES);
        txHelper.setReadOnly(readOnly);
        T result = txHelper.doInTransaction(
                new RetryingTransactionCallback<T>()
                {
                    public T execute() throws Throwable
                    {
                        return command();
                    }
                }, readOnly);
        return result;
    }
    catch (Exception e)
    {
        Throwable cause = e.getCause();
        
        if (logger.isDebugEnabled())
        {
            logger.debug("Exception is thrown : " + e + "\nCause : " + cause);
        }
        
        String message;
        if (cause != null)
        {
            message = cause.getMessage();
        }
        else
        {
            message = e.getMessage();
        }
        throw new FolderException(message);
    }
}
 
Example 10
Source File: AlfrescoPerson.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override protected void before()
{
    ApplicationContext ctxt = getApplicationContext();
    RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) ctxt.getBean("retryingTransactionHelper");
    
    transactionHelper.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override public Void execute() throws Throwable
        {
            personNodeRef = createPerson(userName);
            
            return null;
        }
    });
}
 
Example 11
Source File: AlfrescoPeople.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override protected void after()
{
    // Set up required services
    ApplicationContext ctxt = getApplicationContext();
    final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) ctxt.getBean("retryingTransactionHelper");
    
    transactionHelper.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override public Void execute() throws Throwable
        {
            for (Map.Entry<String, NodeRef> entry : usersPersons.entrySet())
            {
                deletePerson(entry.getKey());
            }
            
            return null;
        }
    });
}
 
Example 12
Source File: PersonServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void addUserUsageContent(final String userName, final int stringDataLength)
{
    RetryingTransactionHelper.RetryingTransactionCallback<Void> usageCallback = new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            try
            {
                AuthenticationUtil.pushAuthentication();
                AuthenticationUtil.setFullyAuthenticatedUser(userName);
                String textData = "This is default text added. Add more: ";
                for (int i = 0; i < stringDataLength; i++)
                {
                    textData += "abc";
                }
                NodeRef homeFolder = getHomeSpaceFolderNode(userName);
                NodeRef folder = nodeService.createNode(
                        homeFolder,
                        ContentModel.ASSOC_CONTAINS,
                        QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "testFolder"),
                        ContentModel.TYPE_FOLDER).getChildRef();
                addTextContent(folder, "text1.txt", textData);
            }
            finally
            {
                AuthenticationUtil.popAuthentication();
            }
            return null;
        }
    };

    RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
    txnHelper.doInTransaction(usageCallback);
}
 
Example 13
Source File: DescriptorServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p/>
 * Restrictions are not changed; previous restrictions remain in place.
 */
@Override
public void onLicenseFail()
{
    synchronized (licenseLock)
    {
        // Current restrictions remain in place
        // Make sure that the repo descriptor is updated the first time
        if (isCurrentRepoDescriptorIsNull())
        {
            final RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
            RetryingTransactionCallback<Void> nopLoadLicense = new RetryingTransactionCallback<Void>()
            {
                @Override
                public Void execute()
                {
                    Descriptor newRepoDescriptor = currentRepoDescriptorDAO.updateDescriptor(serverDescriptor, LicenseMode.UNKNOWN);
                    setCurrentRepoDescriptor(newRepoDescriptor);
                    return null;
                }
            };
            txnHelper.setForceWritable(true);
            txnHelper.doInTransaction(nopLoadLicense, false, false);

        }
    }
}
 
Example 14
Source File: AbstractMailActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testPrepareEmailForDisabledUsers() throws MessagingException
{
    String groupName = null;
    final String USER1 = "test_user1";
    final String USER2 = "test_user2";
    try
    {
        createUser(USER1, null);
        NodeRef userNode = createUser(USER2, null);
        groupName = AUTHORITY_SERVICE.createAuthority(AuthorityType.GROUP, "testgroup1");
        AUTHORITY_SERVICE.addAuthority(groupName, USER1);
        AUTHORITY_SERVICE.addAuthority(groupName, USER2);
        NODE_SERVICE.addAspect(userNode, ContentModel.ASPECT_PERSON_DISABLED, null);
        final Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
        mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, "[email protected]");
        mailAction.setParameterValue(MailActionExecuter.PARAM_TO_MANY, groupName);

        mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Testing");
        mailAction.setParameterValue(MailActionExecuter.PARAM_TEXT, "Testing");

        RetryingTransactionHelper txHelper = APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);

        MimeMessage mm = txHelper.doInTransaction(new RetryingTransactionCallback<MimeMessage>()
        {
            @Override
            public MimeMessage execute() throws Throwable
            {
                return ACTION_EXECUTER.prepareEmail(mailAction, null, null, null).getMimeMessage();
            }
        }, true);

        Address[] addresses = mm.getRecipients(Message.RecipientType.TO);
        Assert.assertEquals(1, addresses.length);
        Assert.assertEquals(USER1 + "@email.com", addresses[0].toString());
    }
    finally
    {
        if (groupName != null)
        {
            AUTHORITY_SERVICE.deleteAuthority(groupName, true);
        }
        PERSON_SERVICE.deletePerson(USER1);
        PERSON_SERVICE.deletePerson(USER2);
    }
}
 
Example 15
Source File: AlfrescoCmisServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
    public void deleteContentStream(
            String repositoryId, Holder<String> objectId, Holder<String> changeToken,
            ExtensionsData extension)
    {
        checkRepositoryId(repositoryId);

        CMISNodeInfo info = getOrCreateNodeInfo(objectId.getValue(), "Object");

        if (!info.isVariant(CMISObjectVariant.CURRENT_VERSION) && !info.isVariant(CMISObjectVariant.PWC))
        {
            throw new CmisStreamNotSupportedException("Content can only be deleted from ondocuments!");
        }

        final NodeRef nodeRef = info.getNodeRef();

        if (((DocumentTypeDefinition) info.getType().getTypeDefinition(false)).getContentStreamAllowed() == ContentStreamAllowed.REQUIRED)
        {
            throw new CmisInvalidArgumentException("Document type requires content!");
        }

        //ALF-21852 - Separated deleteContent and objectId.setValue in two different transactions because
        //after executing deleteContent, the new objectId is not visible.
        RetryingTransactionHelper helper = connector.getRetryingTransactionHelper();
        helper.doInTransaction(new RetryingTransactionCallback<Void>()
        {
            public Void execute() throws Throwable
            {

                connector.getNodeService().setProperty(nodeRef, ContentModel.PROP_CONTENT, null);

//              connector.createVersion(nodeRef, VersionType.MINOR, "Delete content");

                connector.getActivityPoster().postFileFolderUpdated(info.isFolder(), nodeRef);
                return null;
            }
        }, false, true);

        String objId = helper.doInTransaction(new RetryingTransactionCallback<String>()
        {
            public String execute() throws Throwable
            {
                return connector.createObjectId(nodeRef);
            }
        }, true, true);

        objectId.setValue(objId);
    }
 
Example 16
Source File: DescriptorServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void onLicenseChange(final LicenseDescriptor licenseDescriptor)
{
    synchronized (licenseLock)
    {
        logger.debug("Received changed license descriptor: " + licenseDescriptor);
                
        RetryingTransactionCallback<RepoUsage> updateLicenseCallback = new RetryingTransactionCallback<RepoUsage>()
        {
            public RepoUsage execute()
            {
                // Configure the license restrictions
                RepoUsage.LicenseMode newMode = licenseDescriptor.getLicenseMode();
                Long expiryTime = licenseDescriptor.getValidUntil() == null ? null : licenseDescriptor.getValidUntil().getTime();
                RepoUsage restrictions = new RepoUsage(
                        System.currentTimeMillis(), 
                        licenseDescriptor.getMaxUsers(), 
                        licenseDescriptor.getMaxDocs(), 
                        newMode,
                        expiryTime,
                        false);
                repoUsageComponent.setRestrictions(restrictions);
                
                // Reset usage upon loading the unlimited license
                if (restrictions.getUsers() == null)
                {
                    repoUsageComponent.resetUsage(UsageType.USAGE_USERS);
                }
                if (restrictions.getDocuments() == null)
                {
                    repoUsageComponent.resetUsage(UsageType.USAGE_DOCUMENTS);
                }

                // persist the server descriptor values in the current repository descriptor
                if (currentRepoDescriptorNullOrModeHasChanged(newMode))
                {
                    if (logger.isDebugEnabled())
                    {
                        logger.debug("Changing license mode in current repo descriptor to: " + newMode);
                    }
                    Descriptor newRepoDescriptor = currentRepoDescriptorDAO.updateDescriptor(
                            serverDescriptor,
                            newMode);
                    setCurrentRepoDescriptor(newRepoDescriptor);
                }
                if (logger.isDebugEnabled())
                {
                    logger.debug("License restrictions updated: " + restrictions);
                }
                return null;
            }
        };
        RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
        txnHelper.setForceWritable(true);
        txnHelper.doInTransaction(updateLicenseCallback);
    }
}
 
Example 17
Source File: ImporterActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * MNT-16292: Unzipped files which have folders do not get the cm:titled
 * aspect applied
 * 
 * @throws IOException
 */
@Test
public void testImportHasTitledAspectForFolders() throws IOException
{
    final RetryingTransactionHelper retryingTransactionHelper = serviceRegistry.getRetryingTransactionHelper();

    retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        public Void execute()
        {
            NodeRef rootNodeRef = nodeService.getRootNode(storeRef);

            // create test data
            NodeRef zipFileNodeRef = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_CONTENT).getChildRef();
            NodeRef targetFolderNodeRef = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_FOLDER).getChildRef();

            putContent(zipFileNodeRef, "import-archive-test/folderCmTitledAspectArchive.zip");

            Action action = createAction(zipFileNodeRef, "ImporterActionExecuterTestActionDefinition", targetFolderNodeRef);

            try
            {
                importerActionExecuter.execute(action, zipFileNodeRef);

                // check if import succeeded 
                NodeRef importedFolder = nodeService.getChildByName(targetFolderNodeRef, ContentModel.ASSOC_CONTAINS, "folderCmTitledAspectArchive");
                assertNotNull("import action failed", importedFolder);

                // check if aspect is set
                boolean hasAspectTitled = nodeService.hasAspect(importedFolder, ContentModel.ASPECT_TITLED);
                assertTrue("folder didn't get the cm:titled aspect applied", hasAspectTitled);

                // MNT-17017 check ContentModel.PROP_TITLE is not set on the top level folder, just like Share
                String title = (String)nodeService.getProperty(importedFolder, ContentModel.PROP_TITLE);
                assertNull("The title should not have cm:title set", title);
            }
            finally
            {
                // clean test data
                nodeService.deleteNode(targetFolderNodeRef);
                nodeService.deleteNode(zipFileNodeRef);
            }

            return null;
        }
    });
}
 
Example 18
Source File: ThumbnailServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.thumbnail.ThumbnailService#createThumbnail(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.namespace.QName, java.lang.String, org.alfresco.service.cmr.repository.TransformationOptions, java.lang.String, org.alfresco.service.cmr.thumbnail.ThumbnailParentAssociationDetails)
 */
public NodeRef createThumbnail(final NodeRef node, final QName contentProperty, final String mimetype,
        final TransformationOptions transformationOptions, final String thumbnailName, final ThumbnailParentAssociationDetails assocDetails)
{
    // Parameter check
    ParameterCheck.mandatory("node", node);
    ParameterCheck.mandatory("contentProperty", contentProperty);
    ParameterCheck.mandatoryString("mimetype", mimetype);
    ParameterCheck.mandatory("transformationOptions", transformationOptions);

    if (logger.isDebugEnabled() == true)
    {
        logger.debug("Creating thumbnail (node=" + node.toString() + "; contentProperty="
                    + contentProperty.toString() + "; mimetype=" + mimetype);
    }
    
    if (thumbnailName != null)
    {
        NodeRef existingThumbnail = getThumbnailByName(node, contentProperty, thumbnailName);
        if (existingThumbnail != null)
        {
            if (logger.isDebugEnabled() == true)
            {
                logger.debug("Creating thumbnail: There is already a thumbnail with the name '" + thumbnailName + "' (node=" + node.toString() + "; contentProperty=" + contentProperty.toString() + "; mimetype=" + mimetype);
            }
            
            // Return the thumbnail that has already been created
            return existingThumbnail;
        }
    }
    
    RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
    txnHelper.setForceWritable(true);
    boolean requiresNew = false;
    if (AlfrescoTransactionSupport.getTransactionReadState() != TxnReadState.TXN_READ_WRITE)
    {
        //We can be in a read-only transaction, so force a new transaction 
        requiresNew = true;
    }
    return txnHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {

        @Override
        public NodeRef execute() throws Throwable
        {
            return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<NodeRef>()
            {
                public NodeRef doWork() throws Exception
                {
                   return createThumbnailNode( node, 
                                               contentProperty,
                                                mimetype, 
                                                transformationOptions, 
                                                thumbnailName, 
                                                assocDetails);
                }
            }, AuthenticationUtil.getSystemUserName());
        }

    }, false, requiresNew);
    
}
 
Example 19
Source File: DictionaryModelTypeTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test(expected=AlfrescoRuntimeException.class)
public void testImportingSameNamespaceFailsWithinSingleModel() throws Exception
{
    // Create model
    PropertyMap properties = new PropertyMap(1);
    properties.put(ContentModel.PROP_MODEL_ACTIVE, true);
    final NodeRef modelNode = this.nodeService.createNode(
             this.rootNodeRef,
             ContentModel.ASSOC_CHILDREN,
             QName.createQName(NamespaceService.ALFRESCO_URI, "dictionaryModels"),
             ContentModel.TYPE_DICTIONARY_MODEL,
             properties).getChildRef(); 
    assertNotNull(modelNode);
    TestTransaction.flagForCommit();
    TestTransaction.end();

    // update model to introduce self referencing dependency
    try
    {
        RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
        txnHelper.setMaxRetries(1);
        txnHelper.doInTransaction(new RetryingTransactionCallback<Void>() {
                public Void execute() throws Exception {

                    ContentWriter contentWriter = contentService.getWriter(modelNode, ContentModel.PROP_CONTENT, true);
                    contentWriter.setEncoding("UTF-8");
                    contentWriter.setMimetype(MimetypeMap.MIMETYPE_XML);
                    contentWriter.putContent(Thread.currentThread().getContextClassLoader().getResourceAsStream("dictionary/modelWithCurrentNamespaceImported.xml"));
                    return null;
                }
        }, false, true);
        fail("Validation should fail as a circular dependency was introduced");
    } catch(AlfrescoRuntimeException e)
    {
        assertTrue(e.getCause().getMessage().contains("URI http://www.alfresco.org/model/dictionary/1.0 cannot be imported as it is already contained in the model's namespaces"));
        throw e;
    }

    //delete model
    finally
    {
        transactionService.getRetryingTransactionHelper().doInTransaction(
                new RetryingTransactionCallback<Object>() {
                    public Object execute() throws Exception {
                        // Delete the model
                        DictionaryModelTypeTest.this.nodeService.deleteNode(modelNode);
                        return null;
                    }
                }, false, true);
    }
}
 
Example 20
Source File: TemporarySites.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * This method creates a test site (of Alfresco type <code>st:site</code>) and one user for each of the Share Site Roles.
 * This method will be run in its own transaction and will be run with the specified user as the fully authenticated user,
 * thus ensuring the named user is the creator of the new site.
 * The site and its users will be deleted automatically by the rule.
 * 
 * @param sitePreset the site preset.
 * @param visibility the Site visibility.
 * @param siteCreator the username of a user who will be used to create the site (user must exist of course).
 * @return the {@link SiteInfo} object for the newly created site.
 */
public TestSiteAndMemberInfo createTestSiteWithUserPerRole(final String siteShortName, String sitePreset, SiteVisibility visibility, String siteCreator)
{
    // create the site
    SiteInfo result = this.createSite(sitePreset, siteShortName, null, null, visibility, siteCreator);
    
    // create the users
    final RetryingTransactionHelper transactionHelper = appContextRule.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    final SiteService siteService = appContextRule.getApplicationContext().getBean("siteService", SiteService.class);
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(siteCreator);
    
    // Create users for this test site that cover the various roles.
    List<String> userNames = transactionHelper.doInTransaction(new RetryingTransactionCallback<List<String>>()
    {
        public List<String> execute() throws Throwable
        {
            List<String> users = new ArrayList<String>(4);
            
            for (String shareRole : SiteModel.STANDARD_PERMISSIONS)
            {
                final String userName = siteShortName + "_" + shareRole + "_" + GUID.generate();
                
                log.debug("Creating temporary site user " + userName);
                
                createPerson(userName);
                siteService.setMembership(siteShortName, userName, shareRole);
                users.add(userName);
                
                temporarySiteUsers.add(userName);
            }
            
            return users;
        }
    });
    
    NodeRef doclibFolder = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            return siteService.getContainer(siteShortName, SiteService.DOCUMENT_LIBRARY);
        }
    });
    
    AuthenticationUtil.popAuthentication();
     
    
    return new TestSiteAndMemberInfo(result, doclibFolder, userNames.get(0),
                                                           userNames.get(1),
                                                           userNames.get(2),
                                                           userNames.get(3));
}