Java Code Examples for org.alfresco.service.cmr.repository.StoreRef

The following are top voted examples for showing how to use org.alfresco.service.cmr.repository.StoreRef. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alfresco-repository   File: FullTest.java   View source code 7 votes vote down vote up
@Test
public void canGuessMimeType()
{
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    
    ContentService contentService = (ContentService) ctx.getBean("ContentService");
    NodeService nodeService = (NodeService) ctx.getBean("NodeService");
    StoreRef storeRef = nodeService.createStore("workspace", getClass().getName()+UUID.randomUUID());
    NodeRef rootNodeRef = nodeService.getRootNode(storeRef);
    NodeRef nodeRef = nodeService.createNode(
                rootNodeRef,
                ContentModel.ASSOC_CHILDREN,
                QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, getClass().getSimpleName()),
                ContentModel.TYPE_CONTENT).getChildRef();

    ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    // Pre-condition of test is that we're testing with a potentially problematic BackingStoreAwareCacheWriter
    // rather than a FileContentWriter, which we would expect to work.
    assertTrue(writer instanceof BackingStoreAwareCacheWriter);
    
    String content = "This is some content";
    writer.putContent(content);
    writer.guessMimetype("myfile.txt");
    
    assertEquals("text/plain", writer.getMimetype());
}
 
Example 2
Project: alfresco-repository   File: GetNodesWithAspectCannedQueryFactory.java   View source code 6 votes vote down vote up
/**
 * Retrieve an unsorted instance of a {@link CannedQuery} based on parameters including 
 * request for a total count (up to a given max)
 *
 * @param storeRef           the store to search in, if requested
 * @param aspectQNames       qnames of aspects to search for
 * @param pagingRequest      skipCount, maxItems - optionally queryExecutionId and requestTotalCountMax
 * 
 * @return                   an implementation that will execute the query
 */
public CannedQuery<NodeRef> getCannedQuery(StoreRef storeRef, Set<QName> aspectQNames, PagingRequest pagingRequest)
{
    ParameterCheck.mandatory("aspectQNames",  aspectQNames);
    ParameterCheck.mandatory("pagingRequest", pagingRequest);
    
    int requestTotalCountMax = pagingRequest.getRequestTotalCountMax();
    
    // specific query params - context (parent) and inclusive filters (child types, property values)
    GetNodesWithAspectCannedQueryParams paramBean = new GetNodesWithAspectCannedQueryParams(storeRef, aspectQNames);

    // page details
    CannedQueryPageDetails cqpd = new CannedQueryPageDetails(pagingRequest.getSkipCount(), pagingRequest.getMaxItems(), CannedQueryPageDetails.DEFAULT_PAGE_NUMBER, CannedQueryPageDetails.DEFAULT_PAGE_COUNT);
    
    // no sort details - no sorting done
    
    // create query params holder
    CannedQueryParameters params = new CannedQueryParameters(paramBean, cqpd, null, requestTotalCountMax, pagingRequest.getQueryExecutionId());
    
    // return canned query instance
    return getCannedQuery(params);
}
 
Example 3
Project: alfresco-repository   File: ConfigurableServiceImplTest.java   View source code 6 votes vote down vote up
/**
 * onSetUpInTransaction
 */
@Override
protected void onSetUpInTransaction() throws Exception
{
	this.nodeService = (NodeService)this.applicationContext.getBean("nodeService");
	this.serviceRegistry = (ServiceRegistry)this.applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY);
	this.configurableService = (ConfigurableService)this.applicationContext.getBean("configurableService");
	
	this.testStoreRef = this.nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
       this.rootNodeRef = this.nodeService.getRootNode(this.testStoreRef);
       
       // Create the node used for tests
       this.nodeRef = this.nodeService.createNode(
               this.rootNodeRef,
			ContentModel.ASSOC_CHILDREN,
               ContentModel.ASSOC_CHILDREN,
               ContentModel.TYPE_CONTAINER).getChildRef();
}
 
Example 4
Project: alfresco-repository   File: SolrSearchService.java   View source code 6 votes vote down vote up
@Override
public ResultSet query(StoreRef store, QName queryId, QueryParameter[] queryParameters)
{
    CannedQueryDef definition = queryRegister.getQueryDefinition(queryId);

    // Do parameter replacement
    // As lucene phrases are tokensied it is correct to just do straight
    // string replacement.
    // The string will be formatted by the tokeniser.
    //
    // For non phrase queries this is incorrect but string replacement is
    // probably the best we can do.
    // As numbers and text are indexed specially, direct term queries only
    // make sense against textual data

    checkParameters(definition, queryParameters);

    String queryString = parameterise(definition.getQuery(), definition.getQueryParameterMap(), queryParameters, definition.getNamespacePrefixResolver());

    return query(store, definition.getLanguage(), queryString, null);
}
 
Example 5
Project: alfresco-repository   File: FileImporterTest.java   View source code 6 votes vote down vote up
public void setUp()
{
    ctx = ApplicationContextHelper.getApplicationContext();
    serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);

    nodeService = serviceRegistry.getNodeService();
    searchService = serviceRegistry.getSearchService();
    dictionaryService = serviceRegistry.getDictionaryService();
    contentService = serviceRegistry.getContentService();
    authenticationService = (MutableAuthenticationService) ctx.getBean("authenticationService");
    authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    permissionService = serviceRegistry.getPermissionService();
    mimetypeService = serviceRegistry.getMimetypeService();
    namespaceService = serviceRegistry.getNamespaceService();
    transactionService = serviceRegistry.getTransactionService();

    authenticationComponent.setSystemUserAsCurrentUser();
    StoreRef storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
    rootNodeRef = nodeService.getRootNode(storeRef);
}
 
Example 6
Project: alfresco-repository   File: IsSubTypeEvaluatorTest.java   View source code 6 votes vote down vote up
@Override
protected void onSetUpInTransaction() throws Exception
{
    this.nodeService = (NodeService)this.applicationContext.getBean("nodeService");
    
    // Create the store and get the root node
    this.testStoreRef = this.nodeService.createStore(
            StoreRef.PROTOCOL_WORKSPACE, "Test_"
                    + System.currentTimeMillis());
    this.rootNodeRef = this.nodeService.getRootNode(this.testStoreRef);

    // Create the node used for tests
    this.nodeRef = this.nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}testnode"),
            ContentModel.TYPE_CONTENT).getChildRef();
    
    this.evaluator = (IsSubTypeEvaluator)this.applicationContext.getBean(IsSubTypeEvaluator.NAME);
}
 
Example 7
Project: alfresco-repository   File: NodeStoreInspector.java   View source code 6 votes vote down vote up
/**
 * Dumps the contents of a store to a string.
 * 
 * @param nodeService   the node service
 * @param storeRef      the store reference
 * @return              string containing textual representation of the contents of the store
 */
public static String dumpNodeStore(NodeService nodeService, StoreRef storeRef)
{
    StringBuilder builder = new StringBuilder();
    
    if (nodeService.exists(storeRef) == true)
    {
        NodeRef rootNode = nodeService.getRootNode(storeRef);            
        builder.append(outputNode(0, nodeService, rootNode));            
    }
    else
    {
        builder.
            append("The store ").
            append(storeRef.toString()).
            append(" does not exist.");
    }
    
    return builder.toString();
}
 
Example 8
Project: alfresco-repository   File: MultiTAdminServiceImpl.java   View source code 6 votes vote down vote up
private void bootstrapSystemTenantStore(ImporterBootstrap systemImporterBootstrap, String tenantDomain)
{
    // Bootstrap Tenant-Specific System Store
    StoreRef bootstrapStoreRef = systemImporterBootstrap.getStoreRef();
    StoreRef tenantBootstrapStoreRef = new StoreRef(bootstrapStoreRef.getProtocol(), tenantService.getName(bootstrapStoreRef.getIdentifier(), tenantDomain));
    systemImporterBootstrap.setStoreUrl(tenantBootstrapStoreRef.toString());
    
    // override default property (workspace://SpacesStore)
    List<String> mustNotExistStoreUrls = new ArrayList<String>();
    mustNotExistStoreUrls.add(new StoreRef(PROTOCOL_STORE_WORKSPACE, tenantService.getName(STORE_BASE_ID_USER, tenantDomain)).toString());
    systemImporterBootstrap.setMustNotExistStoreUrls(mustNotExistStoreUrls);
    
    systemImporterBootstrap.bootstrap();
    
    // reset since systemImporter is singleton (hence reused)
    systemImporterBootstrap.setStoreUrl(bootstrapStoreRef.toString());
    
    if (logger.isDebugEnabled())
    {
        logger.debug("Bootstrapped store: "+tenantService.getBaseName(tenantBootstrapStoreRef)+" (Tenant: "+tenantDomain+")");
    }
}
 
Example 9
Project: alfresco-repository   File: StartWorkflowActionExecuterTest.java   View source code 6 votes vote down vote up
/**
 * Called at the begining of all tests
 */
@SuppressWarnings("deprecation")
@Override
protected void onSetUpInTransaction() throws Exception
{
    this.nodeService = (NodeService)this.applicationContext.getBean("nodeService");
    this.namespaceService = (NamespaceService)this.applicationContext.getBean("namespaceService");
    this.personService = (PersonService)this.applicationContext.getBean("personService");
    
    AuthenticationComponent authenticationComponent = (AuthenticationComponent)applicationContext.getBean("authenticationComponent");
    authenticationComponent.setCurrentUser(authenticationComponent.getSystemUserName());
    
    // Create the store and get the root node
    rootNodeRef = nodeService.getRootNode(new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore"));
    this.nodeRef = this.nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}testnode"),
            ContentModel.TYPE_CONTENT).getChildRef();
    
    // Get the executer instance 
    this.executer = (StartWorkflowActionExecuter)this.applicationContext.getBean(StartWorkflowActionExecuter.NAME);
}
 
Example 10
Project: alfresco-repository   File: ACLEntryAfterInvocationTest.java   View source code 6 votes vote down vote up
public void testBasicAllowStore() throws Exception
{
    runAs("andy");

    Object o = new ClassWithMethods();
    Method method = o.getClass().getMethod("echoStoreRef", new Class[] { StoreRef.class });

    AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.addAdvisor(advisorAdapterRegistry.wrap(new Interceptor("AFTER_ACL_NODE.sys:base.Read")));
    proxyFactory.setTargetSource(new SingletonTargetSource(o));
    Object proxy = proxyFactory.getProxy();

    permissionService.setPermission(new SimplePermissionEntry(rootNodeRef, getPermission(PermissionService.READ), "andy", AccessStatus.ALLOWED));

    Object answer = method.invoke(proxy, new Object[] { rootNodeRef.getStoreRef() });
    assertEquals(answer, rootNodeRef.getStoreRef());

}
 
Example 11
Project: alfresco-repository   File: NodeServiceImpl.java   View source code 6 votes vote down vote up
/**
 * The node will apprear to be attached to the root of the version store
 *
 * @see NodeService#getParentAssocs(NodeRef, QNamePattern, QNamePattern)
 */
public List<ChildAssociationRef> getParentAssocs(NodeRef nodeRef, QNamePattern typeQNamePattern, QNamePattern qnamePattern)
{
    List<ChildAssociationRef> result = new ArrayList<ChildAssociationRef>();
    if (qnamePattern.isMatch(rootAssocName) == true)
    {
        result.add(new ChildAssociationRef(
                ContentModel.ASSOC_CHILDREN,
                dbNodeService.getRootNode(new StoreRef(StoreRef.PROTOCOL_WORKSPACE, STORE_ID)),
                rootAssocName,
                nodeRef));
    }
    return result;
}
 
Example 12
Project: alfresco-repository   File: ContentStoreCleanerScalabilityRunner.java   View source code 6 votes vote down vote up
/**
 * Creates a node with two properties
 */
public void makeNode(ContentData contentData)
{
    StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
    Long rootNodeId = nodeDAO.newStore(storeRef).getFirst();
    ChildAssocEntity assoc = nodeDAO.newNode(
            rootNodeId,
            ContentModel.ASSOC_CHILDREN,
            ContentModel.ASSOC_CHILDREN,
            storeRef,
            null,
            ContentModel.TYPE_CONTENT,
            I18NUtil.getLocale(),
            null,
            null);
    Long nodeId = assoc.getChildNode().getId();
    nodeDAO.addNodeProperty(nodeId, contentQName, contentData);
}
 
Example 13
Project: alfresco-repository   File: AbstractReindexComponent.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
/**
 * Helper method that caches ADM store references to prevent repeated and unnecessary calls to the
 * NodeService for this list.
 */
private Set<StoreRef> getAdmStoreRefs()
{
    Set<StoreRef> storeRefs = (Set<StoreRef>) AlfrescoTransactionSupport.getResource(KEY_STORE_REFS);
    if (storeRefs != null)
    {
        return storeRefs;
    }
    else
    {
        storeRefs = new HashSet<StoreRef>(nodeService.getStores());
        Iterator<StoreRef> storeRefsIterator = storeRefs.iterator();
        while (storeRefsIterator.hasNext())
        {
            // Remove stores to ignore
            StoreRef storeRef = storeRefsIterator.next();
            if (isIgnorableStore(storeRef))
            {
                storeRefsIterator.remove();
            }
        }
        
        // Bind it in
        AlfrescoTransactionSupport.bindResource(KEY_STORE_REFS, storeRefs);
    }
    return storeRefs;
}
 
Example 14
Project: alfresco-repository   File: StoreRedirectorProxyFactoryTest.java   View source code 6 votes vote down vote up
public void testException()
{
    StoreRef storeRef1 = new StoreRef("Type1", "id");
    NodeRef nodeRef1 = new NodeRef(storeRef1, "id");
    TestServiceInterface service = (TestServiceInterface) factory.getBean("redirector_service1");
    
    try
    {
        service.throwException(nodeRef1);
        fail("Service method did not throw exception");
    }
    catch(Exception e)
    {
        assertTrue(e instanceof IllegalArgumentException);
        assertEquals(nodeRef1.toString(), e.getMessage());
    }
}
 
Example 15
Project: alfresco-repository   File: RepositoryLocation.java   View source code 5 votes vote down vote up
/**
 * Constructor
 * 
 * @param storeRef       the store reference (e.g. 'workspace://SpacesStore' )
 * @param path           the path (e.g. '/app:company_home/app:dictionary/app:models' )
 * @param queryLanguage  the query language (e.g. 'xpath' or 'lucence')
 */
public RepositoryLocation(StoreRef storeRef, String path, String queryLanguage)
{
    this.storeProtocol = storeRef.getProtocol();
    this.storeId = storeRef.getIdentifier();
    this.path = path;
    
    setQueryLanguage(queryLanguage);
}
 
Example 16
Project: alfresco-repository   File: ImapServiceImplTest.java   View source code 5 votes vote down vote up
public void testContentRecovery() throws Exception
{
    reauthenticate(USER_NAME, USER_PASSWORD);
    
    // create content
    NodeRef nodeRef = nodeService.createNode(testImapFolderNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "content_recover"), ContentModel.TYPE_CONTENT).getChildRef();
    FileInfo fileInfo = fileFolderService.getFileInfo(nodeRef);
    
    // Outlook sets flags that indicates that a content was seen and deleted
    imapService.setFlag(fileInfo, Flags.Flag.DELETED, true);
    imapService.setFlag(fileInfo, Flags.Flag.SEEN, true);
    
    // delete a content
    fileFolderService.delete(nodeRef);
    
    // get archive node reference
    String storePath = "archive://SpacesStore";
    StoreRef storeRef = new StoreRef(storePath);
    NodeRef archivedNodeRef = new NodeRef(storeRef, nodeRef.getId());
   
    // restore a node and check flags
    Boolean value = false;
    if (nodeService.exists(archivedNodeRef))
    {
        NodeRef restoredNode = nodeService.restoreNode(archivedNodeRef, testImapFolderNodeRef, null, null);

        Map<QName, Serializable> props = nodeService.getProperties(restoredNode);

        if (props.containsKey(ImapModel.PROP_FLAG_DELETED) && props.containsKey(ImapModel.PROP_FLAG_SEEN))
        {
            value = !(Boolean) props.get(ImapModel.PROP_FLAG_DELETED) && !(Boolean) props.get(ImapModel.PROP_FLAG_SEEN);
        }
    }
    
    assertTrue("Can't set DELETED flag to false", value);
}
 
Example 17
Project: alfresco-remote-api   File: TagsImpl.java   View source code 5 votes vote down vote up
public CollectionWithPagingInfo<Tag> getTags(StoreRef storeRef, Paging paging)
{
	PagingResults<Pair<NodeRef, String>> results = taggingService.getTags(storeRef, Util.getPagingRequest(paging));
	Integer totalItems = results.getTotalResultCount().getFirst();
	List<Pair<NodeRef, String>> page = results.getPage();
	List<Tag> tags = new ArrayList<Tag>(page.size());
	for(Pair<NodeRef, String> pair : page)
	{
		tags.add(new Tag(pair.getFirst(), pair.getSecond()));
	}

	return CollectionWithPagingInfo.asPaged(paging, tags, results.hasMoreItems(), (totalItems == null ? null : totalItems.intValue()));
}
 
Example 18
Project: alfresco-repository   File: AbstractReindexComponent.java   View source code 5 votes vote down vote up
/**
 * @return                  Returns true if the given transaction is present in the index
 */
private boolean isTxnIdPresentInIndex(StoreRef storeRef, Transaction txn)
{
    long txnId = txn.getId();
    String changeTxnId = txn.getChangeTxnId();
    // do the most update check, which is most common
    ResultSet results = null;
    try
    {
        SearchParameters sp = new SearchParameters();
        sp.addStore(storeRef);
        // search for it in the index, sorting with youngest first, fetching only 1
        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp.setQuery("TX:" + SearchLanguageConversion.escapeLuceneQuery(changeTxnId));
        sp.setLimit(1);
        
        results = searcher.query(sp);
        
        if (results.length() > 0)
        {
            if (logger.isTraceEnabled())
            {
                logger.trace("Index has results for txn " + txnId + " for store " + storeRef);
            }
            return true;        // there were updates/creates and results for the txn were found
        }
        else
        {
            if (logger.isTraceEnabled())
            {
                logger.trace("Transaction " + txnId + " not in index for store " + storeRef + ".  Possibly out of date.");
            }
            return false;
        }
    }
    finally
    {
        if (results != null) { results.close(); }
    }
}
 
Example 19
Project: alfresco-repository   File: PermissionServiceImpl.java   View source code 5 votes vote down vote up
@Override
@Extend(traitAPI = PermissionServiceTrait.class, extensionAPI = PermissionServiceExtension.class)
public void deletePermissions(StoreRef storeRef)
{
    permissionsDaoComponent.deletePermissions(storeRef);
    accessCache.clear();
}
 
Example 20
Project: alfresco-repository   File: AuditMethodInterceptorTest.java   View source code 5 votes vote down vote up
/**
 * Test for <a href="https://issues.alfresco.com/jira/browse/MNT-16748">MNT-16748</a> <br>
 * Use {@link SearchService#query(SearchParameters)} to perform a query.
 */
public void testAuditSearchServiceSearchParametersQuery() throws Exception
{
    // Run as admin
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    // Create SearchParameters to be used in query
    SearchParameters sp = new SearchParameters();
    sp.setLanguage(SearchService.LANGUAGE_XPATH);
    sp.setQuery("/app:company_home/app:dictionary");
    sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);

    // Perform a search
    @SuppressWarnings("unused")
    ResultSet rs = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<ResultSet>()
    {
        @Override
        public ResultSet execute() throws Throwable
        {
            return searchService.query(sp);
        }

    }, true, false);

    // Check the audit entries
    checkAuditEntries(APPLICATION_NAME_MNT_16748, SearchService.LANGUAGE_XPATH, "/app:company_home/app:dictionary", 1);
}
 
Example 21
Project: alfresco-repository   File: MessageServiceImplTest.java   View source code 5 votes vote down vote up
private void setupRepo() throws Exception
{       
    AuthenticationUtil.clearCurrentSecurityContext();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
    
    // Create a test workspace
    this.testStoreRef = this.nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
         
    // Get a reference to the root node
    NodeRef rootNodeRef = this.nodeService.getRootNode(this.testStoreRef);
    
    // Create and authenticate the user        
    if(!authenticationService.authenticationExists(AuthenticationUtil.getAdminUserName()))
    {
        authenticationService.createAuthentication(AuthenticationUtil.getAdminUserName(), PWD.toCharArray());
    }
         
    // Authenticate - as admin
    authenticationService.authenticate(AuthenticationUtil.getAdminUserName(), PWD.toCharArray());
    
    // Store test messages in repo
    String pattern = "classpath*:" + BASE_RESOURCE_CLASSPATH + BASE_BUNDLE_NAME + "*";
    
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
   
    Resource[] resources = resolver.getResources(pattern);

    if (resources != null)
    {
        for (int i = 0; i < resources.length; i++)
        {
            String filename = resources[i].getFilename();
            addMessageResource(rootNodeRef, filename, resources[i].getInputStream());                
        }
    }
}
 
Example 22
Project: alfresco-repository   File: RuleTypeImplTest.java   View source code 5 votes vote down vote up
@Override
protected void onSetUpInTransaction() throws Exception
{
	this.nodeService = (NodeService)this.applicationContext.getBean("nodeService");
	this.contentService = (ContentService)this.applicationContext.getBean("contentService");
	
	this.testStoreRef = this.nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
       this.rootNodeRef = this.nodeService.getRootNode(this.testStoreRef);
}
 
Example 23
Project: alfresco-remote-api   File: AbstractWorkflowRestApiTest.java   View source code 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    ApplicationContext appContext = getServer().getApplicationContext();

    namespaceService = (NamespaceService) appContext.getBean("NamespaceService");
    workflowService = (WorkflowService) appContext.getBean("WorkflowService");
    MutableAuthenticationService authenticationService = (MutableAuthenticationService) appContext.getBean("AuthenticationService");
    PersonService personService = (PersonService) appContext.getBean("PersonService");
    SearchService searchService = (SearchService) appContext.getBean("SearchService");
    FileFolderService fileFolderService = (FileFolderService) appContext.getBean("FileFolderService");
    nodeService = (NodeService) appContext.getBean("NodeService");
    
    // for the purposes of the tests make sure workflow engine is enabled/visible.
    WorkflowAdminServiceImpl workflowAdminService = (WorkflowAdminServiceImpl) appContext.getBean("workflowAdminService");
    this.wfTestHelper = new WorkflowTestHelper(workflowAdminService, getEngine(), true);
    
    AuthorityService authorityService = (AuthorityService) appContext.getBean("AuthorityService");
    personManager = new TestPersonManager(authenticationService, personService, nodeService);
    groupManager = new TestGroupManager(authorityService);

    authenticationComponent = (AuthenticationComponent) appContext.getBean("authenticationComponent");
    dictionaryService = (DictionaryService) appContext.getBean("dictionaryService");

    personManager.createPerson(USER1);
    personManager.createPerson(USER2);
    personManager.createPerson(USER3);

    authenticationComponent.setSystemUserAsCurrentUser();

    groupManager.addUserToGroup(GROUP, USER2);

    packageRef = workflowService.createPackage(null);

    NodeRef companyHome = searchService.selectNodes(nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE), COMPANY_HOME, null, namespaceService, false).get(0);

    contentNodeRef = fileFolderService.create(companyHome, TEST_CONTENT + System.currentTimeMillis(), ContentModel.TYPE_CONTENT).getNodeRef();

    authenticationComponent.clearCurrentSecurityContext();
}
 
Example 24
Project: alfresco-repository   File: RoutingContentServiceTest.java   View source code 5 votes vote down vote up
@Override
public void setUp() throws Exception
{
    ctx = ApplicationContextHelper.getApplicationContext();
    transactionService = (TransactionService) ctx.getBean("TransactionService");
    nodeService = (NodeService) ctx.getBean("NodeService");
    contentService = (ContentService) ctx.getBean(ServiceRegistry.CONTENT_SERVICE.getLocalName());
    this.policyComponent = (PolicyComponent) ctx.getBean("policyComponent");
    this.authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    
    // authenticate
    this.authenticationComponent.setSystemUserAsCurrentUser();
    
    // start the transaction
    txn = getUserTransaction();
    txn.begin();
    
    // create a store and get the root node
    StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, getName());
    if (!nodeService.exists(storeRef))
    {
        storeRef = nodeService.createStore(storeRef.getProtocol(), storeRef.getIdentifier());
    }
    rootNodeRef = nodeService.getRootNode(storeRef);
    // create a content node
    ContentData contentData = new ContentData(null, "text/plain", 0L, "UTF-16", Locale.CHINESE);
    
    PropertyMap properties = new PropertyMap();
    properties.put(ContentModel.PROP_CONTENT, contentData);
    
    ChildAssociationRef assocRef = nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName(TEST_NAMESPACE, GUID.generate()),
            ContentModel.TYPE_CONTENT,
            properties);
    contentNodeRef = assocRef.getChildRef();
}
 
Example 25
Project: alfresco-repository   File: AbstractNodeServiceImpl.java   View source code 5 votes vote down vote up
/**
 * @see NodeServicePolicies.BeforeCreateStorePolicy#beforeCreateStore(QName,
 *      StoreRef)
 */
protected void invokeBeforeCreateStore(QName nodeTypeQName, StoreRef storeRef)
{
    if (ignorePolicy(storeRef))
    {
        return;
    }
    
    NodeServicePolicies.BeforeCreateStorePolicy policy = this.beforeCreateStoreDelegate.get(nodeTypeQName);
    policy.beforeCreateStore(nodeTypeQName, storeRef);
}
 
Example 26
Project: alfresco-repository   File: CheckOutActionExecuterTest.java   View source code 5 votes vote down vote up
@Override
protected void onSetUpInTransaction() throws Exception
{
    this.nodeService = (NodeService) this.applicationContext.getBean("nodeService");

    this.checkOutCheckInService = (CheckOutCheckInService) this.applicationContext.getBean("checkOutCheckInService");

    AuthenticationComponent authenticationComponent = (AuthenticationComponent) applicationContext.getBean("authenticationComponent");
    authenticationComponent.setCurrentUser(authenticationComponent.getSystemUserName());

    // Create the store and get the root node
    this.testStoreRef = this.nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
    this.rootNodeRef = this.nodeService.getRootNode(this.testStoreRef);

    // Create 'content' the node used for tests
    this.nodeRefContent = this.nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}contenttestnode"),
            ContentModel.TYPE_CONTENT).getChildRef();

    // Create 'folder' the node used for tests
    this.nodeRefFolder = this.nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}foldertestnode"),
            ContentModel.TYPE_FOLDER).getChildRef();

    // Get the executer instance
    this.executer = (CheckOutActionExecuter) this.applicationContext.getBean(CheckOutActionExecuter.NAME);
}
 
Example 27
Project: alfresco-remote-api   File: NodesImpl.java   View source code 5 votes vote down vote up
@Override
public NodeRef validateNode(String nodeId)
{
    //belts-and-braces
    if (nodeId == null)
    {
        throw new InvalidArgumentException("Missing nodeId");
    }

    return validateNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, nodeId);
}
 
Example 28
Project: alfresco-repository   File: MissingContentReindexComponent.java   View source code 5 votes vote down vote up
/**
 * If this object is currently busy, then it just nothing
 */
@Override
public void reindexImpl()
{
    List<StoreRef> storeRefs = nodeService.getStores();
    int count = 0;
    for (StoreRef storeRef : storeRefs)
    {
        // prompt the FTS reindexing
        if (!ftsIndexerCalled)
        {
            ftsIndexer.requiresIndex(storeRef);
        }
        // reindex missing content
        count += reindexMissingContent(storeRef);
        // check if we have to break out
        if (isShuttingDown())
        {
            break;
        }
    }
    
    // The FTS indexer only needs to be prompted once
    ftsIndexerCalled = true;

    // done
    if (logger.isDebugEnabled())
    {
        logger.debug("Missing content indexing touched " + count + " content nodes");
    }
}
 
Example 29
Project: alfresco-remote-api   File: NodeArchiveServiceRestApiTest.java   View source code 5 votes vote down vote up
/**
 * This test method restores some deleted nodes from the archive store.
 */
public void testRestoreDeletedItems() throws Exception
{
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    
    JSONObject archivedNodesJson = getArchivedNodes();
    JSONObject dataJsonObj = archivedNodesJson.getJSONObject("data");
    JSONArray archivedNodesArray = dataJsonObj.getJSONArray(AbstractArchivedNodeWebScript.DELETED_NODES);
    
    int archivedNodesLength = archivedNodesArray.length();
    assertTrue("Insufficient archived nodes for test to run.", archivedNodesLength > 1);
    
    // Take a specific archived node and restore it.
    JSONObject firstArchivedNode = archivedNodesArray.getJSONObject(0);
    
    // So we have identified a specific Node in the archive that we want to restore.
    String nodeRefString = firstArchivedNode.getString(AbstractArchivedNodeWebScript.NODEREF);
    assertTrue("nodeRef string is invalid", NodeRef.isNodeRef(nodeRefString));
    NodeRef nodeRef = new NodeRef(nodeRefString);
    
    // This is not the StoreRef where the node originally lived e.g. workspace://SpacesStore
    // This is its current StoreRef i.e. archive://SpacesStore
    final StoreRef currentStoreRef = nodeRef.getStoreRef();
    
    String restoreUrl = getArchiveUrl(currentStoreRef) + "/" + nodeRef.getId();
    
    
    int archivedNodesCountBeforeRestore = getArchivedNodesCount();

    // Send the PUT REST call.
    String jsonString = new JSONStringer().object()
        .key("restoreLocation").value("")
        .endObject()
    .toString();
    Response rsp = sendRequest(new PutRequest(restoreUrl, jsonString, "application/json"), 200);
    
    assertEquals("Expected archive to shrink by one", archivedNodesCountBeforeRestore - 1, getArchivedNodesCount());
}
 
Example 30
Project: alfresco-repository   File: SolrSuggesterServiceImpl.java   View source code 5 votes vote down vote up
@Override
public SuggesterResult getSuggestions(SuggesterParameters suggesterParameters)
{
    // if it is not enabled, return an empty result set
    if (!enabled)
    {
        return new SolrSuggesterResult();
    }
    try
    {
        HashMap<String, String> params = new HashMap<>(3);
        String term = suggesterParameters.isTermIsCaseSensitive() ? suggesterParameters.getTerm() : suggesterParameters.getTerm().toLowerCase();
        int limit = suggesterParameters.getLimit();

        params.put("q", term);
        params.put("shards.qt", SUGGEST_HANDLER);
        if (limit > 0)
        {
            params.put("suggest.count", Integer.toString(limit));
        }
        params.put("wt", "json");

        JSONObject response = solrQueryHTTPClient.execute(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SUGGEST_HANDLER, params);
        return new SolrSuggesterResult(response);
    }
    catch (Exception e)
    {
        throw new AlfrescoRuntimeException("SolrSuggester failed.", e);
    }
}
 
Example 31
Project: alfresco-repository   File: MultiTServiceImpl.java   View source code 5 votes vote down vote up
@Override
public StoreRef getName(StoreRef storeRef)
{
    if (storeRef == null)
    {
        return null;
    }

    return new StoreRef(storeRef.getProtocol(), getName(storeRef.getIdentifier()));
}
 
Example 32
Project: alfresco-repository   File: AbstractNodeDAOImpl.java   View source code 5 votes vote down vote up
/**
 * Set the cache that maintains the Store root node data
 * 
 * @param cache                 the cache
 */
public void setRootNodesCache(SimpleCache<Serializable, Serializable> cache)
{
    this.rootNodesCache = new EntityLookupCache<StoreRef, Node, Serializable>(
            cache,
            CACHE_REGION_ROOT_NODES,
            new RootNodesCacheCallbackDAO());
}
 
Example 33
Project: alfresco-repository   File: MetadataEncryptorTests.java   View source code 5 votes vote down vote up
@Override
    public void setUp() throws Exception
    {
        ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
        transactionService = serviceRegistry.getTransactionService();
//        txnHelper = transactionService.getRetryingTransactionHelper();
        metadataEncryptor = (MetadataEncryptor)ctx.getBean("metadataEncryptor");
        nodeService = serviceRegistry.getNodeService();
        tenantService = (TenantService)ctx.getBean("tenantService");
        dictionaryDAO = (DictionaryDAO)ctx.getBean("dictionaryDAO");

        AuthenticationUtil.setRunAsUserSystem();
        
        DictionaryBootstrap bootstrap = new DictionaryBootstrap();
        List<String> bootstrapModels = new ArrayList<String>();
        bootstrapModels.add("alfresco/model/dictionaryModel.xml");
        bootstrapModels.add(TEST_MODEL);
//        List<String> labels = new ArrayList<String>();
//        labels.add(TEST_BUNDLE);
        bootstrap.setModels(bootstrapModels);
//        bootstrap.setLabels(labels);
        bootstrap.setDictionaryDAO(dictionaryDAO);
        bootstrap.setTenantService(tenantService);
        bootstrap.bootstrap();
        
        // create a first store directly
        RetryingTransactionCallback<NodeRef> createStoreWork = new RetryingTransactionCallback<NodeRef>()
        {
            public NodeRef execute()
            {
                StoreRef storeRef = nodeService.createStore(
                        StoreRef.PROTOCOL_WORKSPACE,
                        "Test_" + System.nanoTime());
                return nodeService.getRootNode(storeRef);
            }
        };
        rootNodeRef = transactionService.getRetryingTransactionHelper().doInTransaction(createStoreWork);
    }
 
Example 34
Project: alfresco-remote-api   File: NodeBrowserPost.java   View source code 5 votes vote down vote up
/**
 * Gets the list of repository stores
 * 
 * @return stores
 */
public List<StoreRef> getStores()
{
    if (stores == null)
    {
        stores = getNodeService().getStores();
    }
    return stores;
}
 
Example 35
Project: alfresco-repository   File: SolrQueryHTTPClient.java   View source code 5 votes vote down vote up
private StoreRef extractStoreRef(BasicSearchParameters searchParameters)
{
    if (searchParameters.getStores().size() == 0)
    {
        throw new AlfrescoRuntimeException("No store for query");
    }
    
    StoreRef store = searchParameters.getStores().get(0);
    return store;
}
 
Example 36
Project: alfresco-repository   File: MultiTServiceImpl.java   View source code 5 votes vote down vote up
@Override
public StoreRef getBaseName(StoreRef storeRef)
{
    if (storeRef == null)
    {
        return null;
    }

    return new StoreRef(storeRef.getProtocol(), getBaseName(storeRef.getIdentifier()));
}
 
Example 37
Project: alfresco-repository   File: DbNodeServiceImpl.java   View source code 5 votes vote down vote up
/**
 * Archives the node without the <b>cm:auditable</b> aspect behaviour
 */
private void archiveHierarchy(NodeHierarchyWalker walker, StoreRef archiveStoreRef)
{
    policyBehaviourFilter.disableBehaviour(ContentModel.ASPECT_AUDITABLE);
    try
    {
        archiveHierarchyImpl(walker, archiveStoreRef);
    }
    finally
    {
        policyBehaviourFilter.enableBehaviour(ContentModel.ASPECT_AUDITABLE);
    }
}
 
Example 38
Project: alfresco-repository   File: LuceneCategoryServiceImpl.java   View source code 5 votes vote down vote up
public Collection<ChildAssociationRef> getCategories(StoreRef storeRef, QName aspectQName, Depth depth)
{
    Collection<ChildAssociationRef> assocs = new LinkedList<ChildAssociationRef>();
    Set<NodeRef> nodeRefs = getClassificationNodes(storeRef, aspectQName);
    for (NodeRef nodeRef : nodeRefs)
    {
        assocs.addAll(getChildren(nodeRef, Mode.SUB_CATEGORIES, depth));
    }
    return assocs;
}
 
Example 39
Project: alfresco-repository   File: MultiTenantShareMapper.java   View source code 4 votes vote down vote up
/**
 * Create a tenant domain specific share
 */
private final DiskSharedDevice createTenantShare(String tenantDomain)
{
    logger.debug("create tenant share for domain " + tenantDomain);
       StoreRef storeRef = new StoreRef(getStoreName());
       NodeRef rootNodeRef = new NodeRef(storeRef.getProtocol(), storeRef.getIdentifier(), "dummy"); 
       
       // Root nodeRef is required for storeRef part
       
       rootNodeRef = m_alfrescoConfig.getTenantService().getRootNode(
               m_alfrescoConfig.getNodeService(), 
               m_alfrescoConfig.getSearchService(),
       		m_alfrescoConfig.getNamespaceService(), 
       		getRootPath(), 
       		rootNodeRef);

       //  Create the disk driver and context

       DiskInterface diskDrv = getRepoDiskInterface();
       ContentContext diskCtx = new ContentContext(m_tenantShareName, getStoreName(), getRootPath(), rootNodeRef);
       
       // Set a quota manager for the share, if enabled
       
       if ( m_quotaManager != null)
       {
       	diskCtx.setQuotaManager( m_quotaManager);
       }
       
       if(m_config instanceof ServerConfigurationBean)
       {
           ServerConfigurationBean config = (ServerConfigurationBean)m_config;
           
           config.initialiseRuntimeContext("cifs.tenant." + tenantDomain, diskCtx);
       }
       else
       {
           throw new AlfrescoRuntimeException("configuration error, unknown configuration bean");
       }
       
       //  Default the filesystem to look like an 80Gb sized disk with 90% free space

       diskCtx.setDiskInformation(new SrvDiskInfo(2560, 64, 512, 2304));

       //  Create a temporary shared device for the user to access the tenant company home directory

       return new DiskSharedDevice(m_tenantShareName, diskDrv, diskCtx);
}
 
Example 40
Project: alfresco-repository   File: EmailServiceImpl.java   View source code 4 votes vote down vote up
/**
 * Authenticate in Alfresco repository by sender's e-mail address.
 * 
 * @param from Sender's email address
 * @return User name or null if the user does not exist.
 * @throws EmailMessageException Exception will be thrown if authentication is failed.
 */
private String getUsername(String from)
{
    String userName = null;
    
    if(from == null || from.length()==0)
    {
        return null;
    }
    
    if(logger.isDebugEnabled())
    {
        logger.debug("getUsername from: " + from);
    }
    
    
    StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
    String query = "TYPE:cm\\:person AND [email protected]\\:email:\"" + from + "\"";

    ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_FTS_ALFRESCO, query);
    try
    {
        if (resultSet == null || resultSet.length() == 0)
        {
            return null;
        }
        if (resultSet.length() > 1)
        {
            if(logger.isWarnEnabled())
            {
                logger.warn("found more as one result for email '" + from + "'. The first will be used");
            }
        }
        NodeRef userNode = resultSet.getNodeRef(0);
        if (nodeService.exists(userNode))
        {
            userName = DefaultTypeConverter.INSTANCE.convert(
                    String.class,
                    nodeService.getProperty(userNode, ContentModel.PROP_USERNAME));

            if(logger.isDebugEnabled())
            {
                logger.debug("found username: " + userName);
            }
        }
        else
        {
            // The Lucene index returned a dead result
            throw new EmailMessageException(ERR_UNKNOWN_SOURCE_ADDRESS, from);
        }
    }
    finally
    {
        if(resultSet != null)
        {
            resultSet.close();
        }
    }

    return userName;
}