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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 4 votes vote down vote up
public void setSearchService(SearchService searchService) 
{
    this.searchService = searchService;
}
 
Example 32
Project: alfresco-repository   File: ContentDiskDriver.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 4 votes vote down vote up
public void setSearchService(SearchService searchService)
{
	this.searchService = searchService;
}
 
Example 37
Project: alfresco-repository   File: PublicAPIFacet.java   Source Code and License 4 votes vote down vote up
@Override
public SearchService getSearchService()
{
    return serviceRegistry.getSearchService();
}
 
Example 38
Project: alfresco-repository   File: CustomModelServiceImpl.java   Source Code and License 4 votes vote down vote up
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 39
Project: tieto-alfresco-repository_monitor   File: NodesHierarchyJobImpl.java   Source Code and License 4 votes vote down vote up
public void setSearchService(SearchService searchService) {
	this.searchService = searchService;
}
 
Example 40
Project: alfresco-repository   File: PersonServiceImpl.java   Source Code and License 4 votes vote down vote up
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 41
Project: alfresco-repository   File: PortableHomeFolderManager.java   Source Code and License 4 votes vote down vote up
/**
 * @param searchService the searchService to set
 */
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 42
Project: alfresco-repository   File: SiteServiceImpl.java   Source Code and License 4 votes vote down vote up
@Override
public List<SiteInfo> findSites(String filter, String sitePresetFilter, int size)
{
    List<SiteInfo> result;
    
    NodeRef siteRoot = getSiteRoot();
    if (siteRoot == null)
    {
        result = Collections.emptyList();
    }
    else
    {
        // get the sites that match the specified names
        StringBuilder query = new StringBuilder(128);
        query.append("+PARENT:\"").append(siteRoot.toString()).append('"');

        final boolean filterIsPresent = filter != null && filter.length() > 0;
        // The filter string is only used in the Lucene query if it restricts results.
        // A search for name/title/description = "*" does not need to be put into the Lucene query.
        // This allows users to search for "*" in the site-finder.
        final boolean filterIsPresentAndNecessary = filterIsPresent && !filter.equals("*");
        final boolean sitePresetFilterIsPresent = sitePresetFilter != null && sitePresetFilter.length() > 0;
        
        if (filterIsPresentAndNecessary || sitePresetFilterIsPresent)
        {
            query.append(" +(");
            if (filterIsPresentAndNecessary)
            {
                String escNameFilter = SearchLanguageConversion.escapeLuceneQuery(filter.replace('"', ' '));
                
                query.append(" @cm\\:name:\"*" + escNameFilter + "*\"")
                     .append(" @cm\\:title:\"" + escNameFilter + "\"")
                     .append(" @cm\\:description:\"" + escNameFilter + "\"");
            }
            if (sitePresetFilterIsPresent)
            {
                String escPresetFilter = SearchLanguageConversion.escapeLuceneQuery(sitePresetFilter.replace('"', ' '));
                query.append(" @st\\:sitePreset:\"" + escPresetFilter + "\"");
            }
            
            query.append(")");
        }
        
        SearchParameters sp = new SearchParameters();
        sp.addStore(siteRoot.getStoreRef());
        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp.setQuery(query.toString());
        if (size > 0)
        {
            sp.setLimit(size);
            sp.setLimitBy(LimitBy.FINAL_SIZE);
        }
        ResultSet results = this.searchService.query(sp);
        try
        {
            result = new ArrayList<SiteInfo>(results.length());
            for (NodeRef site : results.getNodeRefs())
            {
                // Ignore any node type that is not a "site"
                QName siteClassName = this.nodeService.getType(site);
                if (this.dictionaryService.isSubClass(siteClassName, SiteModel.TYPE_SITE))
                {
                    result.add(createSiteInfo(site));
                }
            }
        }
        finally
        {
            results.close();
        }
    }
    
    return result;
}
 
Example 43
Project: alfresco-repository   File: AbstractPatch.java   Source Code and License 4 votes vote down vote up
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 44
Project: alfresco-repository   File: CMISConnector.java   Source Code and License 4 votes vote down vote up
public SearchService getSearchService()
{
    return searchService;
}
 
Example 45
Project: alfresco-repository   File: ConfigurationChecker.java   Source Code and License 4 votes vote down vote up
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 46
Project: alfresco-repository   File: RegistryServiceImpl.java   Source Code and License 4 votes vote down vote up
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 47
Project: alfresco-repository   File: VersionServiceImpl.java   Source Code and License 4 votes vote down vote up
/**
 * @param searcher  the searcher
 */
public void setSearcher(SearchService searcher)
{
    this.searcher = searcher;
}
 
Example 48
Project: alfresco-remote-api   File: WebDAVServlet.java   Source Code and License 4 votes vote down vote up
/**
 * @param storeValue String
 * @param rootPath String
 * @param context WebApplicationContext
 * @param nodeService NodeService
 * @param searchService SearchService
 * @param namespaceService NamespaceService
 * @param tenantService TenantService
 * @param m_transactionService TransactionService
 */
private void initializeRootNode(String storeValue, String rootPath, WebApplicationContext context, NodeService nodeService, SearchService searchService,
        NamespaceService namespaceService, TenantService tenantService, TransactionService m_transactionService)
{

    // Use the system user as the authenticated context for the filesystem initialization

    AuthenticationContext authComponent = (AuthenticationContext) context.getBean("authenticationContext");
    authComponent.setSystemUserAsCurrentUser();

    // Wrap the initialization in a transaction

    UserTransaction tx = m_transactionService.getUserTransaction(true);

    try
    {
        // Start the transaction

        if (tx != null)
            tx.begin();
        
        StoreRef storeRef = new StoreRef(storeValue);
        
        if (nodeService.exists(storeRef) == false)
        {
            throw new RuntimeException("No store for path: " + storeRef);
        }
        
        NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);
        
        List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, rootPath, null, namespaceService, false);
        
        if (nodeRefs.size() > 1)
        {
            throw new RuntimeException("Multiple possible children for : \n" + "   path: " + rootPath + "\n" + "   results: " + nodeRefs);
        }
        else if (nodeRefs.size() == 0)
        {
            throw new RuntimeException("Node is not found for : \n" + "   root path: " + rootPath);
        }
        
        defaultRootNode = nodeRefs.get(0);
        
        // Commit the transaction
        if (tx != null)
        	tx.commit();
    }
    catch (Exception ex)
    {
        logger.error(ex);
    }
    finally
    {
        // Clear the current system user

        authComponent.clearCurrentSecurityContext();
    }
}
 
Example 49
Project: alfresco-repository   File: FeedNotifierImpl.java   Source Code and License 4 votes vote down vote up
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 50
Project: alfresco-repository   File: FeedNotifierImpl.java   Source Code and License 4 votes vote down vote up
protected String getEmailTemplateRef()
{
    String locationType = feedEmailTemplateLocation.getQueryLanguage();

    if (locationType.equals(SearchService.LANGUAGE_XPATH))
    {
        StoreRef store = feedEmailTemplateLocation.getStoreRef();
        String xpath = feedEmailTemplateLocation.getPath();

        try
        {
            if (!feedEmailTemplateLocation.getQueryLanguage().equals(SearchService.LANGUAGE_XPATH))
            {
                logger.error("Cannot find the activities email template - repository location query language is not 'xpath': " + feedEmailTemplateLocation.getQueryLanguage());
                return null;
            }

            List<NodeRef> nodeRefs = searchService.selectNodes(nodeService.getRootNode(store), xpath, null, namespaceService, false);
            if (nodeRefs.size() != 1)
            {
                logger.error("Cannot find the activities email template: " + xpath);
                return null;
            }

            return fileFolderService.getLocalizedSibling(nodeRefs.get(0)).toString();
        }
        catch (SearcherException e)
        {
            logger.error("Cannot find the email template!", e);
        }

        return null;
    }
    else if (locationType.equals(RepositoryLocation.LANGUAGE_CLASSPATH))
    {
        return feedEmailTemplateLocation.getPath();
    }
    else
    {
        logger.error("Unsupported location type: " + locationType);
        return null;
    }
}
 
Example 51
Project: alfresco-repository   File: TransferServiceImpl2.java   Source Code and License 4 votes vote down vote up
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 52
Project: alfresco-repository   File: RepoTransferReceiverImpl.java   Source Code and License 4 votes vote down vote up
/**
 * @param searchService
 *            the searchService to set
 */
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 53
Project: alfresco-remote-api   File: WebDAVHelper.java   Source Code and License 4 votes vote down vote up
/**
 * @return          Return the search service
 */
public final SearchService getSearchService()
{
    return m_searchService;
}
 
Example 54
Project: alfresco-repository   File: BaseSearchResultsMap.java   Source Code and License 4 votes vote down vote up
/**
 * Perform a SearchService query with the given Lucene search string
 */
protected List<TemplateNode> query(String search)
{
    List<TemplateNode> nodes = null;
    HashSet<NodeRef> nodeRefs = new HashSet<NodeRef>();

    // check if a full Lucene search string has been supplied or extracted from XML
    if (search != null && search.length() != 0)
    {
        // perform the search against the repo
        ResultSet results = null;
        try
        {
            results = this.services.getSearchService().query(this.parent.getNodeRef().getStoreRef(),
                    SearchService.LANGUAGE_LUCENE, search);

            if (results.length() != 0)
            {
                NodeService nodeService = this.services.getNodeService();
                
                nodes = new ArrayList<TemplateNode>(results.length());
                for (ResultSetRow row : results)
                {
                    NodeRef nodeRef = row.getNodeRef();
                    if (!nodeRefs.contains(nodeRef) && (nodeService.exists(nodeRef)))
                    {
                        nodes.add(new TemplateNode(nodeRef, services, this.parent.getImageResolver()));
                        nodeRefs.add(nodeRef);
                    }
                }
            }
        }
        catch (Throwable err)
        {
            throw new AlfrescoRuntimeException("Failed to execute search: " + search, err);
        }
        finally
        {
            if (results != null)
            {
                results.close();
            }
        }
    }

    return nodes != null ? nodes : (List) Collections.emptyList();
}
 
Example 55
Project: alfresco-remote-api   File: WebDAVHelper.java   Source Code and License 4 votes vote down vote up
/**
 * @param searchService the search service
 */
public void setSearchService(SearchService searchService)
{
    this.m_searchService = searchService;
}
 
Example 56
Project: alfresco-repository   File: XPathNodeLocator.java   Source Code and License 4 votes vote down vote up
/**
 * @param searchService the searchService to set
 */
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 57
Project: alfresco-repository   File: MissingContentReindexComponent.java   Source Code and License 4 votes vote down vote up
/**
 * @param storeRef the store to check for missing content
 * @return Returns the number of documents reindexed
 */
private int reindexMissingContent(StoreRef storeRef)
{
    SearchParameters sp = new SearchParameters();
    sp.addStore(storeRef);

    // search for it in the index, sorting with youngest first
    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.setQuery(
            "TEXT:" + AbstractLuceneIndexerImpl.NOT_INDEXED_CONTENT_MISSING +
            " TEXT: " + AbstractLuceneIndexerImpl.NOT_INDEXED_TRANSFORMATION_FAILED +
            " TEXT: " + AbstractLuceneIndexerImpl.NOT_INDEXED_NO_TRANSFORMATION);
    sp.addSort(SearchParameters.SORT_IN_DOCUMENT_ORDER_DESCENDING);
    ResultSet results = null;
    try
    {
        results = searcher.query(sp);
        
        int count = 0;
        // iterate over the nodes and prompt for reindexing
        for (ResultSetRow row : results)
        {
            final NodeRef childNodeRef = row.getNodeRef();
            // prompt for a reindex - it might fail again, but we just keep plugging away
            RetryingTransactionCallback<Object> reindexWork = new RetryingTransactionCallback<Object>()
            {
                public Object execute()
                {
                    indexer.updateNode(childNodeRef);
                    return null;
                }
            };
            transactionService.getRetryingTransactionHelper().doInTransaction(reindexWork, true);
            count++;
            // check if we have to break out
            if (isShuttingDown())
            {
                break;
            }
        }
        // done
        if (logger.isDebugEnabled())
        {
            logger.debug(
                    "Reindexed missing content: \n" +
                    "   store: " + storeRef + "\n" +
                    "   node count: " + count);
        }
        return count;
    }
    finally
    {
        if (results != null)
        {
            results.close();
        }
    }
}
 
Example 58
Project: alfresco-remote-api   File: QueriesImpl.java   Source Code and License 4 votes vote down vote up
@Override
public CollectionWithPagingInfo<Site> findSites(Parameters parameters)
{
    SearchService searchService = sr.getSearchService();
    return new AbstractQuery<Site>(nodeService, searchService)
    {
        @Override
        protected void buildQuery(StringBuilder query, String term, SearchParameters sp, String queryTemplateName)
        {
            sp.addQueryTemplate(queryTemplateName, "%(cm:name cm:title cm:description)");
            sp.setExcludeTenantFilter(false);
            sp.setPermissionEvaluation(PermissionEvaluationMode.EAGER);

            query.append("TYPE:\"").append(SiteModel.TYPE_SITE).append("\" AND (\"*");
            query.append(term);
            query.append("*\")");
        }
        
        @Override
        protected List<Site> newList(int capacity)
        {
            return new ArrayList<>(capacity);
        }

        @Override
        protected Site convert(NodeRef nodeRef, List<String> includeParam)
        {
            return getSite(siteService.getSite(nodeRef), true);
        }

        // note: see also Sites.getSite
        private Site getSite(SiteInfo siteInfo, boolean includeRole)
        {
            // set the site id to the short name (to deal with case sensitivity issues with using the siteId from the url)
            String siteId = siteInfo.getShortName();
            String role = null;
            if(includeRole)
            {
                role = sites.getSiteRole(siteId);
            }
            return new Site(siteInfo, role);
        }
    }.find(parameters, PARAM_TERM, MIN_TERM_LENGTH_SITES, "_SITE", POST_QUERY_SORT, SITE_SORT_PARAMS_TO_QNAMES, new SortColumn(PARAM_SITE_TITLE, true));
}
 
Example 59
Project: alfresco-repository   File: CMISConnector.java   Source Code and License 4 votes vote down vote up
/**
 * Sets the search service.
 */
public void setSearchService(SearchService searchService)
{
    this.searchService = searchService;
}
 
Example 60
Project: alfresco-remote-api   File: PutMethodTest.java   Source Code and License 4 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);
    authenticationService = ctx.getBean("authenticationService", MutableAuthenticationService.class);
    personService = ctx.getBean("PersonService", PersonService.class);
    lockService = ctx.getBean("LockService", LockService.class);
    contentService = ctx.getBean("contentService", ContentService.class);
    checkOutCheckInService = ctx.getBean("CheckOutCheckInService", CheckOutCheckInService.class);
    permissionService = ctx.getBean("PermissionService", PermissionService.class);
    namespaceService = ctx.getBean("namespaceService", NamespaceService.class);

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    repositoryHelper = (Repository)ctx.getBean("repositoryHelper");
    companyHomeNodeRef = repositoryHelper.getCompanyHome();
    txn = transactionService.getUserTransaction();
    txn.begin();
    createUser(USER1_NAME);
    createUser(USER2_NAME);

    InputStream testDataIS = getClass().getClassLoader().getResourceAsStream(TEST_DATA_FILE_NAME);
    InputStream davLockInfoAdminIS = getClass().getClassLoader().getResourceAsStream(DAV_LOCK_INFO_ADMIN);
    InputStream davLockInfoUser2IS = getClass().getClassLoader().getResourceAsStream(DAV_LOCK_INFO_USER2);
    
    testDataFile = IOUtils.toByteArray(testDataIS);
    davLockInfoAdminFile = IOUtils.toByteArray(davLockInfoAdminIS);
    davLockInfoUser2File = IOUtils.toByteArray(davLockInfoUser2IS);

    testDataIS.close();
    davLockInfoAdminIS.close();
    davLockInfoUser2IS.close();

    // Create a test file with versionable aspect and content
    Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
    versionableDocName = "doc-" + GUID.generate();
    properties.put(ContentModel.PROP_NAME, versionableDocName);

    versionableDoc = nodeService.createNode(companyHomeNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName(ContentModel.USER_MODEL_URI, versionableDocName),
            ContentModel.TYPE_CONTENT, properties).getChildRef();
    contentService.getWriter(versionableDoc, ContentModel.PROP_CONTENT, true).putContent("WebDAVTestContent");
    nodeService.addAspect(versionableDoc, ContentModel.ASPECT_VERSIONABLE, null);

    txn.commit();

    txn = transactionService.getUserTransaction();
    txn.begin();
}