Search in sources :

Example 16 with QueryManager

use of org.xwiki.query.QueryManager in project xwiki-platform by xwiki.

the class WikiTemplateMigrationTest method setUp.

@Before
public void setUp() throws Exception {
    wikiDescriptorManager = mocker.getInstance(WikiDescriptorManager.class);
    queryManager = mocker.getInstance(QueryManager.class);
    // documentReferenceResolver = mocker.getInstance(DocumentReferenceResolver.TYPE_STRING, "current");
    documentReferenceResolver = mocker.getInstance(new DefaultParameterizedType(null, DocumentReferenceResolver.class, String.class));
    execution = mock(Execution.class);
    mocker.registerComponent(Execution.class, execution);
    xcontext = mock(XWikiContext.class);
    xwiki = mock(XWiki.class);
    ExecutionContext executionContext = mock(ExecutionContext.class);
    when(execution.getContext()).thenReturn(executionContext);
    when(executionContext.getProperty("xwikicontext")).thenReturn(xcontext);
    when(xcontext.getWiki()).thenReturn(xwiki);
    when(wikiDescriptorManager.getMainWikiId()).thenReturn("mainWiki");
    query = mock(Query.class);
    when(queryManager.createQuery(any(), eq(Query.XWQL))).thenReturn(query);
}
Also used : Execution(org.xwiki.context.Execution) ExecutionContext(org.xwiki.context.ExecutionContext) Query(org.xwiki.query.Query) WikiDescriptorManager(org.xwiki.wiki.descriptor.WikiDescriptorManager) QueryManager(org.xwiki.query.QueryManager) XWikiContext(com.xpn.xwiki.XWikiContext) XWiki(com.xpn.xwiki.XWiki) DefaultParameterizedType(org.xwiki.component.util.DefaultParameterizedType) Before(org.junit.Before)

Example 17 with QueryManager

use of org.xwiki.query.QueryManager in project xwiki-platform by xwiki.

the class X509CertificateWikiStoreTest method setUp.

@Before
public void setUp() throws Exception {
    EntityReferenceProvider valueProvider = mock(EntityReferenceProvider.class);
    when(valueProvider.getDefaultReference(EntityType.WIKI)).thenReturn(WIKI_REFERENCE);
    when(valueProvider.getDefaultReference(EntityType.SPACE)).thenReturn(SPACE_REFERENCE);
    when(valueProvider.getDefaultReference(EntityType.DOCUMENT)).thenReturn(DOCUMENT_REFERENCE);
    mocker.registerComponent(EntityReferenceProvider.class, "current", valueProvider);
    Provider<XWikiContext> xcontextProvider = mocker.registerMockComponent(XWikiContext.TYPE_PROVIDER);
    xcontext = mock(XWikiContext.class);
    when(xcontextProvider.get()).thenReturn(xcontext);
    xwiki = mock(com.xpn.xwiki.XWiki.class);
    when(xcontext.getWiki()).thenReturn(xwiki);
    BinaryStringEncoder encoder = mocker.getInstance(BinaryStringEncoder.class, "Base64");
    when(encoder.encode(CERTIFICATE, 64)).thenReturn(ENCODED_CERTIFICATE);
    when(encoder.decode(ENCODED_CERTIFICATE)).thenReturn(CERTIFICATE);
    when(encoder.encode(SUBJECT_KEYID)).thenReturn(ENCODED_SUBJECTKEYID);
    when(encoder.decode(ENCODED_SUBJECTKEYID)).thenReturn(SUBJECT_KEYID);
    QueryManager queryManager = mocker.getInstance(QueryManager.class);
    query = mock(Query.class);
    when(query.bindValue(any(String.class), any())).thenReturn(query);
    when(query.setWiki(WIKI)).thenReturn(query);
    when(queryManager.createQuery(any(String.class), any(String.class))).thenReturn(query);
    store = mocker.getComponentUnderTest();
}
Also used : BinaryStringEncoder(org.xwiki.crypto.BinaryStringEncoder) EntityReferenceProvider(org.xwiki.model.reference.EntityReferenceProvider) AbstractX509StoreQuery(org.xwiki.crypto.store.wiki.internal.query.AbstractX509StoreQuery) Query(org.xwiki.query.Query) AbstractX509IssuerAndSerialQuery(org.xwiki.crypto.store.wiki.internal.query.AbstractX509IssuerAndSerialQuery) AbstractX509SubjectQuery(org.xwiki.crypto.store.wiki.internal.query.AbstractX509SubjectQuery) AbstractX509KeyIdentifierQuery(org.xwiki.crypto.store.wiki.internal.query.AbstractX509KeyIdentifierQuery) QueryManager(org.xwiki.query.QueryManager) XWikiContext(com.xpn.xwiki.XWikiContext) XWiki(com.xpn.xwiki.XWiki) Before(org.junit.Before)

Example 18 with QueryManager

use of org.xwiki.query.QueryManager in project xwiki-platform by xwiki.

the class XWikiGroupServiceImpl method getAllMatchedMembersNamesForGroup.

@Override
public Collection<String> getAllMatchedMembersNamesForGroup(String group, String matchField, int nb, int start, Boolean orderAsc, XWikiContext context) throws XWikiException {
    // TODO: add cache mechanism.
    XWikiDocument groupDocument = new XWikiDocument(this.currentMixedDocumentReferenceResolver.resolve(group));
    Map<String, Object> parameterValues = new HashMap<String, Object>();
    // //////////////////////////////////////
    // Create the query string
    StringBuilder queryString = new StringBuilder("SELECT field.value");
    queryString.append(' ').append(createMatchGroupMembersWhereClause(groupDocument.getFullName(), matchField, orderAsc, parameterValues));
    try {
        // //////////////////////////////////////
        // Create the query
        QueryManager qm = context.getWiki().getStore().getQueryManager();
        Query query = qm.createQuery(queryString.toString(), Query.HQL);
        for (Map.Entry<String, Object> entry : parameterValues.entrySet()) {
            query.bindValue(entry.getKey(), entry.getValue());
        }
        query.setOffset(start);
        query.setLimit(nb);
        query.setWiki(groupDocument.getDocumentReference().getWikiReference().getName());
        return query.execute();
    } catch (QueryException ex) {
        throw new XWikiException(0, 0, ex.getMessage(), ex);
    }
}
Also used : XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) QueryException(org.xwiki.query.QueryException) Query(org.xwiki.query.Query) HashMap(java.util.HashMap) QueryManager(org.xwiki.query.QueryManager) BaseObject(com.xpn.xwiki.objects.BaseObject) HashMap(java.util.HashMap) Map(java.util.Map) XWikiException(com.xpn.xwiki.XWikiException)

Example 19 with QueryManager

use of org.xwiki.query.QueryManager in project xwiki-platform by xwiki.

the class CreateActionRequestHandler method loadAvailableTemplateProviders.

/**
 * @param spaceReference the space to check if there are available templates for
 * @param context the context of the current request
 * @param templateClassReference the reference to the template provider class
 * @return the available template providers for the passed space, as {@link Document}s
 */
private List<Document> loadAvailableTemplateProviders(SpaceReference spaceReference, DocumentReference templateClassReference, XWikiContext context) {
    List<Document> templates = new ArrayList<>();
    try {
        QueryManager queryManager = Utils.getComponent((Type) QueryManager.class, "secure");
        Query query = queryManager.createQuery("from doc.object(XWiki.TemplateProviderClass) as template " + "where doc.fullName not like 'XWiki.TemplateProviderTemplate' " + "order by template.name", Query.XWQL);
        // TODO: Extend the above query to include a filter on the type and allowed spaces properties so we can
        // remove the java code below, thus improving performance by not loading all the documents, but only the
        // documents we need.
        List<XWikiDocument> recommendedTemplates = new ArrayList<>();
        List<String> templateProviderDocNames = query.execute();
        for (String templateProviderName : templateProviderDocNames) {
            // get the document and template provider object
            DocumentReference reference = getCurrentMixedResolver().resolve(templateProviderName);
            // Verify that the current user has the view right on the Template document
            if (!getAuthManager().hasAccess(Right.VIEW, reference)) {
                continue;
            }
            XWikiDocument templateDoc = context.getWiki().getDocument(reference, context);
            BaseObject templateObject = templateDoc.getXObject(templateClassReference);
            // Check the template provider's visibility restrictions.
            if (isTemplateProviderAllowedInSpace(templateObject, spaceReference, TP_VISIBILITY_RESTRICTIONS_PROPERTY)) {
                List<String> creationRestrictions = getTemplateProviderRestrictions(templateObject, TP_CREATION_RESTRICTIONS_PROPERTY);
                if (creationRestrictions.size() > 0 && isTemplateProviderAllowedInSpace(templateObject, spaceReference, TP_CREATION_RESTRICTIONS_PROPERTY)) {
                    // Consider providers that have creations restrictions matching the current space as
                    // "recommended" and handle them separately.
                    recommendedTemplates.add(templateDoc);
                } else {
                    // Other visible providers.
                    templates.add(new Document(templateDoc, context));
                }
            }
        }
        EntityReferenceSerializer<String> localSerializer = Utils.getComponent(EntityReferenceSerializer.TYPE_STRING, LOCAL_SERIALIZER_HINT);
        String spaceStringReference = localSerializer.serialize(spaceReference);
        // Sort the recommended providers and promote the most specific ones.
        recommendedTemplates.sort(Comparator.comparing((XWikiDocument templateProviderDocument) -> {
            BaseObject templateProviderObject = templateProviderDocument.getXObject(templateClassReference);
            // Look at any set creation restrictions.
            List<String> restrictions = getTemplateProviderRestrictions(templateProviderObject, TP_CREATION_RESTRICTIONS_PROPERTY);
            // Return the longest (max) matching restriction reference size as being the most specific.
            return restrictions.stream().filter(restriction -> matchesRestriction(spaceStringReference, restriction)).mapToInt(restriction -> {
                SpaceReferenceResolver<String> spaceResolver = Utils.getComponent(SpaceReferenceResolver.TYPE_STRING);
                SpaceReference restrictionSpaceReference = spaceResolver.resolve(restriction);
                // The specificity score.
                int specificity = restrictionSpaceReference.getReversedReferenceChain().size();
                return specificity;
            }).max().orElse(0);
        }).reversed());
        this.recommendedTemplateProviders = recommendedTemplates.stream().map(recommendedTemplate -> new Document(recommendedTemplate, context)).collect(Collectors.toList());
        // Give priority to the providers that that specify creation restrictions
        templates.addAll(0, recommendedTemplateProviders);
    } catch (Exception e) {
        LOGGER.warn("There was an error getting the available templates for space {0}", spaceReference, e);
    }
    return templates;
}
Also used : XWiki(com.xpn.xwiki.XWiki) XWikiException(com.xpn.xwiki.XWikiException) Right(org.xwiki.security.authorization.Right) Query(org.xwiki.query.Query) EntityReference(org.xwiki.model.reference.EntityReference) LoggerFactory(org.slf4j.LoggerFactory) SpaceReference(org.xwiki.model.reference.SpaceReference) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) ContextualAuthorizationManager(org.xwiki.security.authorization.ContextualAuthorizationManager) DocumentReferenceResolver(org.xwiki.model.reference.DocumentReferenceResolver) Map(java.util.Map) VelocityManager(org.xwiki.velocity.VelocityManager) ScriptContextManager(org.xwiki.script.ScriptContextManager) EntityType(org.xwiki.model.EntityType) EntityReferenceSerializer(org.xwiki.model.reference.EntityReferenceSerializer) Logger(org.slf4j.Logger) BaseObject(com.xpn.xwiki.objects.BaseObject) SpaceReferenceResolver(org.xwiki.model.reference.SpaceReferenceResolver) QueryManager(org.xwiki.query.QueryManager) Collectors(java.util.stream.Collectors) VelocityContext(org.apache.velocity.VelocityContext) Document(com.xpn.xwiki.api.Document) ScriptContext(javax.script.ScriptContext) EntityReferenceResolver(org.xwiki.model.reference.EntityReferenceResolver) List(java.util.List) Type(java.lang.reflect.Type) DocumentReference(org.xwiki.model.reference.DocumentReference) XWikiContext(com.xpn.xwiki.XWikiContext) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) Comparator(java.util.Comparator) Query(org.xwiki.query.Query) SpaceReference(org.xwiki.model.reference.SpaceReference) ArrayList(java.util.ArrayList) Document(com.xpn.xwiki.api.Document) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) XWikiException(com.xpn.xwiki.XWikiException) BaseObject(com.xpn.xwiki.objects.BaseObject) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) QueryManager(org.xwiki.query.QueryManager) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 20 with QueryManager

use of org.xwiki.query.QueryManager in project xwiki-platform by xwiki.

the class ExportAction method resolvePagesToExport.

private Collection<DocumentReference> resolvePagesToExport(String[] pages, XWikiContext context) throws XWikiException {
    List<DocumentReference> pageList = new ArrayList<>();
    if (pages == null || pages.length == 0) {
        pageList.add(context.getDoc().getDocumentReference());
    } else {
        Map<String, Object[]> wikiQueries = new HashMap<>();
        for (int i = 0; i < pages.length; ++i) {
            String pattern = pages[i];
            String wikiName;
            if (pattern.contains(":")) {
                int index = pattern.indexOf(':');
                wikiName = pattern.substring(0, index);
                pattern = pattern.substring(index + 1);
            } else {
                wikiName = context.getWikiId();
            }
            StringBuffer where;
            List<QueryParameter> params;
            if (!wikiQueries.containsKey(wikiName)) {
                Object[] query = new Object[2];
                query[0] = where = new StringBuffer("where ");
                query[1] = params = new ArrayList<>();
                wikiQueries.put(wikiName, query);
            } else {
                Object[] query = wikiQueries.get(wikiName);
                where = (StringBuffer) query[0];
                params = (List<QueryParameter>) query[1];
            }
            if (i > 0) {
                where.append(" or ");
            }
            where.append("doc.fullName like ?");
            params.add(new DefaultQueryParameter(null).like(pattern));
        }
        DocumentReferenceResolver<String> resolver = Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, "current");
        QueryManager queryManager = Utils.getComponent(QueryManager.class);
        String database = context.getWikiId();
        try {
            for (Map.Entry<String, Object[]> entry : wikiQueries.entrySet()) {
                String wikiName = entry.getKey();
                Object[] query = entry.getValue();
                String where = query[0].toString();
                List<Object> params = (List<Object>) query[1];
                Query dbQuery = queryManager.createQuery(where, Query.HQL);
                List<String> docsNames = dbQuery.setWiki(wikiName).bindValues(params).execute();
                for (String docName : docsNames) {
                    String pageReference = wikiName + XWikiDocument.DB_SPACE_SEP + docName;
                    if (context.getWiki().getRightService().hasAccessLevel("view", context.getUser(), pageReference, context)) {
                        pageList.add(resolver.resolve(pageReference));
                    }
                }
            }
        } catch (QueryException e) {
            throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_EXPORT, "Failed to resolve pages to export", e);
        } finally {
            context.setWikiId(database);
        }
    }
    return pageList;
}
Also used : DefaultQueryParameter(org.xwiki.query.internal.DefaultQueryParameter) QueryParameter(org.xwiki.query.QueryParameter) DefaultQueryParameter(org.xwiki.query.internal.DefaultQueryParameter) Query(org.xwiki.query.Query) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) QueryException(org.xwiki.query.QueryException) QueryManager(org.xwiki.query.QueryManager) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) DocumentReference(org.xwiki.model.reference.DocumentReference) XWikiException(com.xpn.xwiki.XWikiException)

Aggregations

QueryManager (org.xwiki.query.QueryManager)22 Query (org.xwiki.query.Query)18 DocumentReference (org.xwiki.model.reference.DocumentReference)11 Before (org.junit.Before)7 Test (org.junit.Test)7 XWikiContext (com.xpn.xwiki.XWikiContext)6 XWiki (com.xpn.xwiki.XWiki)5 ArrayList (java.util.ArrayList)5 List (java.util.List)5 XWikiException (com.xpn.xwiki.XWikiException)4 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)4 Map (java.util.Map)4 BaseObject (com.xpn.xwiki.objects.BaseObject)3 Date (java.util.Date)3 HashMap (java.util.HashMap)3 QueryException (org.xwiki.query.QueryException)3 ImmutablePair (org.apache.commons.lang3.tuple.ImmutablePair)2 Pair (org.apache.commons.lang3.tuple.Pair)2 Expectations (org.jmock.Expectations)2 ConfigurationSource (org.xwiki.configuration.ConfigurationSource)2