Java Code Examples for org.alfresco.service.cmr.search.SearchService

The following are top voted examples for showing how to use org.alfresco.service.cmr.search.SearchService. 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: Search.java   View source code 9 votes vote down vote up
/**
 * Execute the query
 * 
 * Removes any duplicates that may be present (ID search can cause duplicates -
 * it is better to remove them here)
 * 
 * @param store         StoreRef to search against - null for default configured store
 * @param search        Lucene search to execute
 * @param sort          Columns to sort by
 * @param language      Search language to use e.g. SearchService.LANGUAGE_LUCENE
 * @param maxResults    Maximum results to return if > 0
 * @param skipResults   Results to skip in the result set
 * 
 * @return Array of Node objects
 */
protected Object[] query(String store, String search, SortColumn[] sort, String language, int maxResults, int skipResults)
{   
    SearchParameters sp = new SearchParameters();
    sp.addStore(store != null ? new StoreRef(store) : this.storeRef);
    sp.setLanguage(language != null ? language : SearchService.LANGUAGE_LUCENE);
    sp.setQuery(search);
    if (maxResults > 0)
    {
        sp.setLimit(maxResults);
        sp.setLimitBy(LimitBy.FINAL_SIZE);
    }
    if (skipResults > 0)
    {
        sp.setSkipCount(skipResults);
    }
    if (sort != null)
    {
        for (SortColumn sd : sort)
        {
            sp.addSort(sd.column, sd.asc);
        }
    }
    
    return query(sp, true);
}
 
Example 2
Project: alfresco-repository   File: EmailServiceImplTest.java   View source code 7 votes vote down vote up
@Override
public void setUp() throws Exception
{  
    AuthenticationUtil.setRunAsUserSystem();
    nodeService = (NodeService)ctx.getBean("NodeService");
    assertNotNull("nodeService", nodeService);
    authorityService = (AuthorityService)ctx.getBean("AuthorityService");
    assertNotNull("authorityService", authorityService);
    ChildApplicationContextFactory emailSubsystem = (ChildApplicationContextFactory) ctx.getBean("InboundSMTP");
    assertNotNull("emailSubsystem", emailSubsystem);
    ApplicationContext emailCtx = emailSubsystem.getApplicationContext();
    emailService = (EmailService)emailCtx.getBean("emailService");       
    assertNotNull("emailService", emailService);
    personService = (PersonService)emailCtx.getBean("PersonService");       
    assertNotNull("personService", personService);     
    namespaceService = (NamespaceService)emailCtx.getBean("NamespaceService");       
    assertNotNull("namespaceService", namespaceService);
    searchService = (SearchService)emailCtx.getBean("SearchService");  
    assertNotNull("searchService", searchService);
    folderEmailMessageHandler = (FolderEmailMessageHandler) emailCtx.getBean("folderEmailMessageHandler");  
    assertNotNull("folderEmailMessageHandler", folderEmailMessageHandler);
    transactionHelper = (RetryingTransactionHelper) emailCtx.getBean("retryingTransactionHelper");
    assertNotNull("transactionHelper", transactionHelper);
}
 
Example 3
Project: alfresco-repository   File: PatchTest.java   View source code 6 votes vote down vote up
public void setUp() throws Exception
{
    transactionService = (TransactionService) ctx.getBean("transactionComponent");
    namespaceService = (NamespaceService) ctx.getBean("namespaceService");
    nodeService = (NodeService) ctx.getBean("nodeService");
    searchService = (SearchService) ctx.getBean("searchService");
    authenticationContext = (AuthenticationContext) ctx.getBean("authenticationContext");
    tenantAdminService = (TenantAdminService) ctx.getBean("tenantAdminService");
    
    patchService = (PatchService) ctx.getBean("PatchService");
    
    // get the patches to play with
    patchService.registerPatch((Patch)ctx.getBean("patch.sample.02"));
    patchService.registerPatch((Patch)ctx.getBean("patch.sample.01"));
    patchService.registerPatch((Patch)ctx.getBean("patch.sample.03"));
}
 
Example 4
Project: alfresco-repository   File: RepoAdminServiceImplTest.java   View source code 6 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    
    repoAdminService = (RepoAdminService) ctx.getBean("RepoAdminService");
    dictionaryService = (DictionaryService) ctx.getBean("DictionaryService");
    transactionService = (TransactionService) ctx.getBean("TransactionService");
    nodeService = (NodeService) ctx.getBean("NodeService");
    contentService = (ContentService) ctx.getBean("ContentService");
    searchService = (SearchService) ctx.getBean("SearchService");
    namespaceService = (NamespaceService) ctx.getBean("NamespaceService");
    behaviourFilter = (BehaviourFilter)ctx.getBean("policyBehaviourFilter");
    dictionaryDAO = (DictionaryDAO) ctx.getBean("dictionaryDAO");
    
    DbNodeServiceImpl dbNodeService = (DbNodeServiceImpl)ctx.getBean("dbNodeService");
    dbNodeService.setEnableTimestampPropagation(false);
    
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
}
 
Example 5
Project: tieto-alfresco-repository_monitor   File: MonitorSitesCountAction.java   View source code 6 votes vote down vote up
@Override
protected void executeImpl(NodeRef actionedUponNodeRef) {
	
	final SearchParameters sp = new SearchParameters();
	sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
	sp.setLanguage(SearchService.LANGUAGE_CMIS_ALFRESCO);
	sp.setQuery(QUERY);
	try {
		final ResultSet rs = searchService.query(sp);
		LOGGER.info("Actual number of sites: {}", rs.length());
		final String message = rs.length() < 5000?"Count of sites is OK":"Count of sites exceed recomended limit";
		setOutput(actionedUponNodeRef, new JSONSitesBuilder().setSitesCount(rs.length()).generateOutput());
		updateStatus(actionedUponNodeRef, JobStatus.Status.FINISHED, message);
	} catch (RuntimeException e) {
		updateStatus(actionedUponNodeRef, JobStatus.Status.ERROR, "Error to get number of sites.");
	}
}
 
Example 6
Project: alfresco-repository   File: AuditMethodInterceptorTest.java   View source code 6 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(StoreRef, String, String)} to perform a query.
 */
public void testAuditSearchServiceQuery() throws Exception
{
    // Run as admin
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    // Perform a search
    @SuppressWarnings("unused")
    ResultSet rs = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<ResultSet>()
    {
        @Override
        public ResultSet execute() throws Throwable
        {
            return searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_XPATH, "/app:company_home");
        }

    }, true, false);

    // Check the audit entries
    checkAuditEntries(APPLICATION_NAME_MNT_16748, SearchService.LANGUAGE_XPATH, "/app:company_home", 1);
}
 
Example 7
Project: alfresco-repository   File: TaggingServiceImpl.java   View source code 6 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.tagging.TaggingService#findTaggedNodes(StoreRef, java.lang.String)
 */
public List<NodeRef> findTaggedNodes(StoreRef storeRef, String tag)
{
    // Lower the case of the tag
    tag = tag.toLowerCase();
    ResultSet resultSet= null;
    
    try
    {
        // Do the search for nodes
        resultSet = this.searchService.query(
            storeRef, 
            SearchService.LANGUAGE_LUCENE, 
            "+PATH:\"/cm:taggable/cm:" + ISO9075.encode(tag) + "/member\"");
        List<NodeRef> nodeRefs = resultSet.getNodeRefs();
        return nodeRefs;
    }
    finally
    {
        if(resultSet != null) {resultSet.close();}
    }
}
 
Example 8
Project: alfresco-repository   File: RepositoryPathConfigBean.java   View source code 5 votes vote down vote up
/**
 * Helper method to resolve the path represented by this configuration bean.
 * <p>
 * Authentication and transactions are the client's responsibility.
 * 
 * @return                      Returns the node reference (first one found) or <tt>null</tt>
 */
public NodeRef resolveNodePath(NamespaceService namespaceService, NodeService nodeService, SearchService searchService)
{
    NodeRef rootNodeRef = nodeService.getRootNode(store);
    List<NodeRef> nodeRefs = searchService.selectNodes(rootNodeRef, rootPath, null, namespaceService, true);
    if (nodeRefs.size() == 0)
    {
        return null;
    }
    else
    {
        return nodeRefs.get(0);
    }
}
 
Example 9
Project: alfresco-repository   File: CustomModelServiceImpl.java   View source code 5 votes vote down vote up
private List<CompiledModel> getAllCustomM2Models(boolean onlyInactiveModels)
{
    List<CompiledModel> result = new ArrayList<>();

    StringBuilder builder = new StringBuilder(160);
    builder.append(repoModelsLocation.getPath()).append(RepoAdminServiceImpl.CRITERIA_ALL).append("[(")
                .append(RepoAdminServiceImpl.defaultSubtypeOfDictionaryModel).append(" and ").append(DEFAULT_CUSTOM_MODEL_ASPECT);
    if (onlyInactiveModels)
    {
        builder.append(" and @cm:modelActive='false'");
    }
    builder.append(")]");

    List<NodeRef> nodeRefs = searchService.selectNodes(getRootNode(), builder.toString(), null, namespaceDAO, false,
                SearchService.LANGUAGE_XPATH);

    if (nodeRefs.size() > 0)
    {
        for (NodeRef nodeRef : nodeRefs)
        {
            try
            {
                M2Model m2Model = getM2Model(nodeRef);
                if (m2Model == null)
                {
                    logger.warn("Couldn't construct M2Model from nodeRef:" + nodeRef);
                    continue;
                }
                result.add(compileModel(m2Model));
            }
            catch (Throwable t)
            {
                logger.warn("Skip model (" + t.getMessage() + ")");
            }
        }
    }

    return result;
}
 
Example 10
Project: alfresco-remote-api   File: WebDAVonContentUpdateTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception
{
    searchService = ctx.getBean("SearchService", SearchService.class);
    fileFolderService = ctx.getBean("FileFolderService", FileFolderService.class);
    nodeService = ctx.getBean("NodeService", NodeService.class);
    transactionService = ctx.getBean("transactionService", TransactionService.class);
    webDAVHelper = ctx.getBean("webDAVHelper", WebDAVHelper.class);
    lockService = ctx.getBean("LockService", LockService.class);
    policyComponent = ctx.getBean("policyComponent", PolicyComponent.class);
    namespaceService = ctx.getBean("namespaceService", NamespaceService.class);

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    repositoryHelper = (Repository)ctx.getBean("repositoryHelper");
    companyHomeNodeRef = repositoryHelper.getCompanyHome();

    InputStream testDataIS = getClass().getClassLoader().getResourceAsStream(TEST_DATA_FILE_NAME);
    InputStream davLockInfoIS = getClass().getClassLoader().getResourceAsStream(DAV_LOCK_INFO_XML);
    testDataFile = IOUtils.toByteArray(testDataIS);
    davLockInfoFile = IOUtils.toByteArray(davLockInfoIS);
    testDataIS.close();
    davLockInfoIS.close();

    txn = transactionService.getUserTransaction();
    txn.begin();
}
 
Example 11
Project: alfresco-repository   File: EmailHelperTest.java   View source code 5 votes vote down vote up
@Before
public void setup() throws Exception
{
    this.dummyTemplateNodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, GUID.generate());
    // Mock the required services
    this.serviceRegistryMock = mock(ServiceRegistry.class);
    this.nodeServiceMock = mock(NodeService.class);
    this.searchServiceMock = mock(SearchService.class);
    this.namespaceServiceMock = mock(NamespaceService.class);
    this.fileFolderServiceMock = mock(FileFolderService.class);
    this.personServiceMock = mock(PersonService.class);
    this.preferenceServiceMock = mock(PreferenceService.class);
    this.repositoryHelperMock = mock(Repository.class);
    this.templateLoaderMock = mock(TemplateLoader.class);

    when(serviceRegistryMock.getNodeService()).thenReturn(nodeServiceMock);
    when(serviceRegistryMock.getSearchService()).thenReturn(searchServiceMock);
    when(serviceRegistryMock.getNamespaceService()).thenReturn(namespaceServiceMock);
    when(serviceRegistryMock.getFileFolderService()).thenReturn(fileFolderServiceMock);
    when(serviceRegistryMock.getPersonService()).thenReturn(personServiceMock);
    when(serviceRegistryMock.getContentService()).thenReturn(mock(ContentService.class));
    when(repositoryHelperMock.getRootHome()).thenReturn(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, GUID.generate()));
    when(fileFolderServiceMock.getLocalizedSibling(dummyTemplateNodeRef)).thenReturn(dummyTemplateNodeRef);

    this.emailHelper = new EmailHelper();
    emailHelper.setServiceRegistry(serviceRegistryMock);
    emailHelper.setPreferenceService(preferenceServiceMock);
    emailHelper.setRepositoryHelper(repositoryHelperMock);
    emailHelper.setCompanyHomeChildName("app:company_home");
    //test init
    emailHelper.init();
    // Note: set the template loader after the init method
    emailHelper.setTemplateLoader(templateLoaderMock);
}
 
Example 12
Project: alfresco-remote-api   File: TestEnterpriseAtomPubTCK.java   View source code 5 votes vote down vote up
@Before
public void setup() throws Exception
{
	JettyComponent jetty = getTestFixture().getJettyComponent();
	
	final SearchService searchService = (SearchService)jetty.getApplicationContext().getBean("searchService");;
	final NodeService nodeService = (NodeService)jetty.getApplicationContext().getBean("nodeService");
	final FileFolderService fileFolderService = (FileFolderService)jetty.getApplicationContext().getBean("fileFolderService");
	final NamespaceService namespaceService = (NamespaceService)jetty.getApplicationContext().getBean("namespaceService");
	final TransactionService transactionService = (TransactionService)jetty.getApplicationContext().getBean("transactionService");
	final String name = "abc" + System.currentTimeMillis();

	transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
	{
		@Override
		public Void execute() throws Throwable
		{
			AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

               Repository repositoryHelper = (Repository)jetty.getApplicationContext().getBean("repositoryHelper");
			NodeRef companyHome = repositoryHelper.getCompanyHome();
			fileFolderService.create(companyHome, name, ContentModel.TYPE_FOLDER).getNodeRef();

			return null;
		}
	}, false, true);

   	int port = jetty.getPort();
   	Map<String, String> cmisParameters = new HashMap<String, String>();
   	cmisParameters.put(TestParameters.DEFAULT_RELATIONSHIP_TYPE, "R:cm:replaces");
   	cmisParameters.put(TestParameters.DEFAULT_TEST_FOLDER_PARENT, "/" + name);
   	clientContext = new OpenCMISClientContext(BindingType.ATOMPUB,
   			MessageFormat.format(CMIS_URL, "localhost", String.valueOf(port), "alfresco"), "admin", "admin", cmisParameters, jetty.getApplicationContext());

       overrideVersionableAspectProperties(jetty.getApplicationContext());
}
 
Example 13
Project: alfresco-repository   File: ViewXMLExporter.java   View source code 5 votes vote down vote up
/**
 * Construct
 * 
 * @param namespaceService  namespace service
 * @param nodeService  node service
 * @param contentHandler  content handler
 */
ViewXMLExporter(NamespaceService namespaceService, NodeService nodeService, SearchService searchService,
        DictionaryService dictionaryService, PermissionService permissionService, ContentHandler contentHandler)
{
    this.namespaceService = namespaceService;
    this.nodeService = nodeService;
    this.searchService = searchService;
    this.dictionaryService = dictionaryService;
    this.permissionService = permissionService;
    this.contentHandler = contentHandler;
    
    VIEW_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, VIEW_LOCALNAME, namespaceService);
    VALUE_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, VALUE_LOCALNAME, namespaceService);
    VALUES_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, VALUES_LOCALNAME, namespaceService);
    CHILDNAME_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, CHILDNAME_LOCALNAME, namespaceService);
    ASPECTS_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, ASPECTS_LOCALNAME, namespaceService);
    PROPERTIES_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, PROPERTIES_LOCALNAME, namespaceService);
    ASSOCIATIONS_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, ASSOCIATIONS_LOCALNAME, namespaceService);
    DATATYPE_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, DATATYPE_LOCALNAME, namespaceService);
    ISNULL_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, ISNULL_LOCALNAME, namespaceService);
    METADATA_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, METADATA_LOCALNAME, namespaceService);
    EXPORTEDBY_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, EXPORTEDBY_LOCALNAME, namespaceService);
    EXPORTEDDATE_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, EXPORTEDDATE_LOCALNAME, namespaceService);
    EXPORTERVERSION_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, EXPORTERVERSION_LOCALNAME, namespaceService);
    EXPORTOF_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, EXPORTOF_LOCALNAME, namespaceService);
    ACL_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, ACL_LOCALNAME, namespaceService);
    ACE_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, ACE_LOCALNAME, namespaceService);
    ACCESS_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, ACCESS_LOCALNAME, namespaceService);
    AUTHORITY_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, AUTHORITY_LOCALNAME, namespaceService);
    PERMISSION_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, PERMISSION_LOCALNAME, namespaceService);
    INHERITPERMISSIONS_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, INHERITPERMISSIONS_LOCALNAME, namespaceService);
    REFERENCE_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, REFERENCE_LOCALNAME, namespaceService);
    PATHREF_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, PATHREF_LOCALNAME, namespaceService);
    NODEREF_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, NODEREF_LOCALNAME, namespaceService);
    LOCALE_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, LOCALE_LOCALNAME, namespaceService);
    MLVALUE_QNAME = QName.createQName(NamespaceService.REPOSITORY_VIEW_PREFIX, MLVALUE_LOCALNAME, namespaceService);

}
 
Example 14
Project: alfresco-repository   File: SearcherComponent.java   View source code 5 votes vote down vote up
public ResultSet query(SearchParameters searchParameters)
{
    if(searchParameters.getStores().size() == 0)
    {
        throw new IllegalStateException("At least one store must be defined to search");
    }
    StoreRef storeRef = searchParameters.getStores().get(0);
    SearchService searcher = indexerAndSearcherFactory.getSearcher(storeRef, !searchParameters.excludeDataInTheCurrentTransaction());
    return searcher.query(searchParameters);
}
 
Example 15
Project: alfresco-repository   File: AbstractSearcherComponent.java   View source code 5 votes vote down vote up
public List<Serializable> selectProperties(NodeRef contextNodeRef, String xpath,
        QueryParameterDefinition[] parameters, NamespacePrefixResolver namespacePrefixResolver,
        boolean followAllParentLinks) throws InvalidNodeRefException, XPathException
{
    return selectProperties(contextNodeRef, xpath, parameters, namespacePrefixResolver, followAllParentLinks,
            SearchService.LANGUAGE_XPATH);
}
 
Example 16
Project: alfresco-repository   File: RepositoryFolderConfigBean.java   View source code 5 votes vote down vote up
/**
 * Helper method to find or create the folder path referenced by this bean.
 * The {@link #getFolderPath() path} to the start of the folder path
 * must exist.  The folder path will be created, if required.
 * <p>
 * Authentication and transactions are the client's responsibility.
 * 
 * @return                      Returns an existing or new folder reference
 */
public NodeRef getOrCreateFolderPath(
        NamespaceService namespaceService,
        NodeService nodeService,
        SearchService searchService,
        FileFolderService fileFolderService)
{
    NodeRef pathStartNodeRef = super.resolveNodePath(namespaceService, nodeService, searchService);
    if (pathStartNodeRef == null)
    {
        throw new AlfrescoRuntimeException(
                "Folder path resolution requires an existing base path. \n" +
                "   Base path: " + getRootPath());
    }
    // Just choose the root path if the folder path is empty
    if (folderPath.length() == 0)
    {
        return pathStartNodeRef;
    }
    else
    {
        StringTokenizer folders = new StringTokenizer(folderPath, "/");
        NodeRef nodeRef = pathStartNodeRef;
        while (folders.hasMoreTokens())
        {
            QName folderQName = QName.createQName(folders.nextToken(), namespaceService);
            List<ChildAssociationRef> children = nodeService.getChildAssocs(nodeRef, RegexQNamePattern.MATCH_ALL, folderQName); 
            if (children.isEmpty())
            {
                nodeRef = fileFolderService.create(nodeRef, folderQName.getLocalName(), ContentModel.TYPE_FOLDER, folderQName).getNodeRef();
            }
            else
            {
                nodeRef = children.get(0).getChildRef();
            }
        }
        return nodeRef;
    }
    // Done
}
 
Example 17
Project: alfresco-repository   File: InviteSenderTest.java   View source code 5 votes vote down vote up
/**
 * Mocks up a SearchService that will return the template NodeRef when
 * queried.
 * 
 * @return SearchService
 */
private SearchService mockSearchService()
{
    SearchService searchService = mock(SearchService.class);
    ResultSet results = mock(ResultSet.class);
    List<NodeRef> nodeRefs = Arrays.asList(template);
    when(results.getNodeRefs()).thenReturn(nodeRefs);
    when(searchService.query((SearchParameters) any())).thenReturn(results);
    when(searchService.selectNodes(any(NodeRef.class), any(String.class),
                any(QueryParameterDefinition[].class), any(NamespacePrefixResolver.class), eq(false)))
                .thenReturn(nodeRefs);
    return searchService;
}
 
Example 18
Project: alfresco-repository   File: ConcurrentNodeServiceSearchTest.java   View source code 5 votes vote down vote up
public void testConcurrent() throws Exception
{
    int count = 10;
    int repeats = 10;

    SearchService searcher = (SearchService) ctx.getBean(ServiceRegistry.SEARCH_SERVICE.getLocalName());

    Map<QName, ChildAssociationRef> assocRefs = commitNodeGraph();
    Thread runner = null;

    for (int i = 0; i < count; i++)
    {
        runner = new Nester("Concurrent-" + i, runner, repeats, searcher);
    }
    if (runner != null)
    {
        runner.start();

        try
        {
            runner.join();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    assertEquals(2, searcher.selectNodes(rootNodeRef, "/*", null,
            getNamespacePrefixReolsver(""), false).size());
    ResultSet results = searcher.query(rootNodeRef.getStoreRef(), "lucene", "PATH:\"/*\"");
    // n6 has root aspect - there are three things at the root level in the
    // index
    assertEquals(3, results.length());
    results.close();
}
 
Example 19
Project: alfresco-repository   File: RuleServiceImplTest.java   View source code 5 votes vote down vote up
@Override
  protected void onSetUpInTransaction() throws Exception 
  {
      super.onSetUpInTransaction();        
      this.permissionService = (PermissionService)this.applicationContext.getBean("permissionService");
this.authenticationService = (MutableAuthenticationService)this.applicationContext.getBean("authenticationService");
      this.searchService = (SearchService) applicationContext.getBean("SearchService");
      this.namespaceService = (NamespaceService) applicationContext.getBean("NamespaceService");
      this.fileFolderService = (FileFolderService) applicationContext.getBean("FileFolderService");
  }
 
Example 20
Project: alfresco-acl-templates   File: AclTemplateServiceImpl.java   View source code 5 votes vote down vote up
public Set<String> getAclTemplates() {
    String query = "+PATH:\"" + aclTemplateFolderPath + "/*\"";
    ResultSet results = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_LUCENE, query);
    Set<String> aclTemplates = new HashSet<>();
    for (int i = 0; i < results.length(); i++) {
        NodeRef nodeRef = results.getNodeRef(i);
        aclTemplates.add((String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME));
    }
    return aclTemplates;
}
 
Example 21
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 22
Project: alfresco-repository   File: SolrIndexerAndSearcherFactory.java   View source code 5 votes vote down vote up
@Override
public SearchService getSearcher(StoreRef storeRef, boolean searchDelta) throws SearcherException
{
     SolrSearchService searchService = new SolrSearchService();
     searchService.setDictionaryService(dictionaryService);
     searchService.setNamespacePrefixResolver(namespacePrefixResolver);
     searchService.setNodeService(nodeService);
     searchService.setQueryLanguages(getQueryLanguages());
     searchService.setQueryRegister(queryRegister);
     return searchService;
}
 
Example 23
Project: alfresco-repository   File: SolrFacetServiceImpl.java   View source code 5 votes vote down vote up
/**
 * Gets the {@link NodeRef} of the {@code srft:facets} folder, if it exists.
 * @return the {@link NodeRef} if it exists, else {@code null}.
 */
public NodeRef getFacetsRoot()
{
    NodeRef facetHomeRef = (NodeRef) singletonCache.get(KEY_FACETS_HOME_NODEREF);
    if (facetHomeRef == null)
    {
        facetHomeRef = AuthenticationUtil.runAs(new RunAsWork<NodeRef>()
        {
            public NodeRef doWork() throws Exception
            {
                return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
                {
                    public NodeRef execute() throws Exception
                    {
                        NodeRef result = null;

                        // Get the root 'facets' folder
                        NodeRef rootNodeRef = nodeService.getRootNode(FACET_STORE);
                        List<NodeRef> results = searchService.selectNodes(rootNodeRef, facetsRootXPath, null,
                                    namespaceService, false, SearchService.LANGUAGE_XPATH);
                        if (results.size() != 0)
                        {
                            result = results.get(0);
                        }

                        return result;
                    }
                }, true);
            }
        }, AuthenticationUtil.getSystemUserName());

        if (facetHomeRef != null) { singletonCache.put(KEY_FACETS_HOME_NODEREF, facetHomeRef); }
    }
    return facetHomeRef;
}
 
Example 24
Project: alfresco-remote-api   File: DeleteMethodTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception
{
    transactionService = ctx.getBean("transactionService", TransactionService.class);
    searchService = ctx.getBean("SearchService", SearchService.class);
    nodeService = ctx.getBean("NodeService", NodeService.class);
    contentService = ctx.getBean("contentService", ContentService.class);
    webDAVHelper = ctx.getBean("webDAVHelper", WebDAVHelper.class);         
    repositoryHelper = (Repository)ctx.getBean("repositoryHelper");
    companyHomeNodeRef = repositoryHelper.getCompanyHome();
}
 
Example 25
Project: alfresco-repository   File: Search.java   View source code 5 votes vote down vote up
/**
 * Execute a Lucene search
 * 
 * @param store         Store reference to search against i.e. workspace://SpacesStore
 * @param search        Lucene search string to execute
 * 
 * @return JavaScript array of Node results from the search - can be empty but not null
 */
public Scriptable luceneSearch(String store, String search)
{
    if (search != null && search.length() != 0)
    {
        Object[] results = query(store, search, null, SearchService.LANGUAGE_LUCENE);
        return Context.getCurrentContext().newArray(getScope(), results);
    }
    else
    {
        return Context.getCurrentContext().newArray(getScope(), 0);
    }
}
 
Example 26
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 27
Project: alfresco-expirable-content   File: ExpiredContentReportWriter.java   View source code 5 votes vote down vote up
private NodeRef getReportFolderNode(String folderPath) {
    String query = "PATH:\"" + folderPath + "\"";
    ResultSet results = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_FTS_ALFRESCO, query);
    if (results.length() <= 0) {
        return null;
    }
    return results.getNodeRef(0);
}
 
Example 28
Project: alfresco-repository   File: RepoTransferReceiverImplTest.java   View source code 5 votes vote down vote up
/**
 * Called during the transaction setup
 */
protected void onSetUp() throws Exception
{
    super.onSetUp();
    System.out.println("java.io.tmpdir == " + System.getProperty("java.io.tmpdir"));

    // Get the required services
    this.nodeService = (NodeService) this.applicationContext.getBean("nodeService");
    this.contentService = (ContentService) this.applicationContext.getBean("contentService");
    this.authenticationService = (MutableAuthenticationService) this.applicationContext
            .getBean("authenticationService");
    this.actionService = (ActionService) this.applicationContext.getBean("actionService");
    this.transactionService = (TransactionService) this.applicationContext.getBean("transactionComponent");
    this.authenticationComponent = (AuthenticationComponent) this.applicationContext
            .getBean("authenticationComponent");
    this.receiver = (RepoTransferReceiverImpl) this.getApplicationContext().getBean("transferReceiver");
    this.policyComponent = (PolicyComponent) this.getApplicationContext().getBean("policyComponent");
    this.searchService = (SearchService) this.getApplicationContext().getBean("searchService");
    this.repositoryHelper = (Repository) this.getApplicationContext().getBean("repositoryHelper");
    this.namespaceService = (NamespaceService) this.getApplicationContext().getBean("namespaceService");
    this.dummyContent = "This is some dummy content.";        
    this.dummyContentBytes = dummyContent.getBytes("UTF-8");
    setTransactionDefinition(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
    authenticationComponent.setSystemUserAsCurrentUser();

    startNewTransaction();
    guestHome = repositoryHelper.getGuestHome();
    endTransaction();
}
 
Example 29
Project: tieto-alfresco-repository_monitor   File: NodesHierarchyJobImpl.java   View source code 5 votes vote down vote up
public NodeRef getNodeFromPathName(String pathName) {
	StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
	ResultSet rs = searchService.query(storeRef, SearchService.LANGUAGE_XPATH, String.format("/app:%s", pathName));

	NodeRef sourceNameNodeRef = null;
	try {
		if (rs.length() == 0) {
			throw new AlfrescoRuntimeException(String.format("Didn't find %s", pathName));
		}
		sourceNameNodeRef = rs.getNodeRef(0);
	} finally {
		rs.close();
	}
	return sourceNameNodeRef;
}
 
Example 30
Project: alfresco-repository   File: VirtualQueryImpl.java   View source code 5 votes vote down vote up
/**
 * @deprecated will be replaced by {@link VirtualQueryConstraint}s once
 *             complex constrains are implemented
 */
private String filter(String language, String query, boolean files, boolean folders) throws VirtualizationException
{
    String filteredQuery = query;

    if (files ^ folders)
    {
        if (SearchService.LANGUAGE_FTS_ALFRESCO.equals(language))
        {
            if (!files)
            {
                filteredQuery = "(" + filteredQuery + ") and TYPE:\"cm:folder\"";
            }
            else
            {
                filteredQuery = "(" + filteredQuery + ") and TYPE:\"cm:content\"";
            }
        }
        else
        {
            throw new VirtualizationException("Disjunctive file-folder filters are only supported on "
                        + SearchService.LANGUAGE_FTS_ALFRESCO + " virtual query language.");
        }

    }

    return filteredQuery;
}
 
Example 31
Project: alfresco-repository   File: RepoUrlConfigSource.java   View source code 4 votes vote down vote up
public void setSearchService(SearchService searchService) 
{
    this.searchService = searchService;
}
 
Example 32
Project: alfresco-repository   File: ContentDiskDriver.java   View source code 4 votes vote down vote up
/**
 * @param searchService the search service
 */
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 33
Project: alfresco-remote-api   File: StatsGet.java   View source code 4 votes vote down vote up
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) 
{
   Map<String, Object> model = new HashMap<String, Object>(2, 1.0f);
   Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
   SiteInfo siteInfo = null;
   
   String listFacets = req.getParameter("listFacets");
   if (listFacets != null)
   {
       model.put("facets", facets.keySet());
       model.put("resultSize", 0);
       return model;
   }
   
   if (templateVars != null && templateVars.containsKey("siteId") )
   {
     siteInfo = siteService.getSite(templateVars.get("siteId"));
     if (siteInfo == null)
     {
         throw new AccessDeniedException("No such site: " + templateVars.get("siteId"));
     }
   }

   String facetKey = req.getParameter("facet");
   if (facetKey == null) facetKey = facets.entrySet().iterator().next().getKey();  //default
   String query;
   
   QName propFacet = findFacet(facetKey);
   Pair<LocalDate, LocalDate> startAndEnd = getStartAndEndDates(req.getParameter("startDate"),req.getParameter("endDate"));
   query = buildQuery(siteInfo, facetKey, startAndEnd);

   StatsParameters params = new StatsParameters(SearchService.LANGUAGE_SOLR_FTS_ALFRESCO, query, false);
   //params.addSort(new SortDefinition(SortDefinition.SortType.FIELD, this.statsField, false));
   params.addStatsParameter(StatsParameters.PARAM_FIELD, this.statsField);
   params.addStatsParameter(StatsParameters.PARAM_FACET, StatsParameters.FACET_PREFIX+propFacet.toString());
  
   StatsResultSet result = stats.query(params);
   
   if (postProcessors.containsKey(facetKey))
   {
       StatsProcessor processor = postProcessors.get(facetKey);
       result = processor.process(result);
   }
   model.put("result", result);
   model.put("resultSize", result.getStats().size());
   return model;
}
 
Example 34
Project: alfresco-repository   File: EmailServiceImpl.java   View source code 4 votes vote down vote up
/**
 * @param searchService Alfresco Search Service
 */
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 35
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;
}
 
Example 36
Project: alfresco-repository   File: DynamicCreateRepositoryLocation.java   View source code 4 votes vote down vote up
public void setSearchService(SearchService searchService)
{
	this.searchService = searchService;
}
 
Example 37
Project: alfresco-repository   File: PublicAPIFacet.java   View source code 4 votes vote down vote up
@Override
public SearchService getSearchService()
{
    return serviceRegistry.getSearchService();
}
 
Example 38
Project: alfresco-repository   File: CustomModelServiceImpl.java   View source code 4 votes vote down vote up
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 39
Project: tieto-alfresco-repository_monitor   File: NodesHierarchyJobImpl.java   View source code 4 votes vote down vote up
public void setSearchService(SearchService searchService) {
	this.searchService = searchService;
}
 
Example 40
Project: alfresco-repository   File: PersonServiceImpl.java   View source code 4 votes vote down vote up
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}