Search in sources :

Example 36 with Query

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

the class AbstractDatabaseSearchSource method search.

@Override
public List<SearchResult> search(String partialQueryString, String wikiName, String wikis, boolean hasProgrammingRights, String orderField, String order, boolean distinct, int number, int start, Boolean withPrettyNames, String className, UriInfo uriInfo) throws Exception {
    XWikiContext xwikiContext = this.xcontextProvider.get();
    XWiki xwikiApi = new XWiki(xwikiContext.getWiki(), xwikiContext);
    if (partialQueryString == null || StringUtils.startsWithIgnoreCase(partialQueryString, "select")) {
        return Collections.emptyList();
    }
    String queryString = resolveQuery(distinct, partialQueryString);
    Query query = this.queryManager.createQuery(queryString, this.queryLanguage);
    query.setLimit(number).setOffset(start);
    query.setWiki(wikiName);
    List<Object> queryResult = query.execute();
    WikiReference wikiReference = new WikiReference(wikiName);
    /* Build the result. */
    List<SearchResult> result = new ArrayList<>();
    for (Object object : queryResult) {
        Object[] fields = (Object[]) object;
        String fullName = (String) fields[0];
        String language = (String) fields[3];
        DocumentReference documentReference = this.resolver.resolve(fullName, wikiReference);
        /* Check if the user has the right to see the found document */
        if (this.authorization.hasAccess(Right.VIEW, documentReference)) {
            Document doc = xwikiApi.getDocument(documentReference);
            String title = doc.getDisplayTitle();
            SearchResult searchResult = this.objectFactory.createSearchResult();
            searchResult.setType("page");
            searchResult.setId(doc.getPrefixedFullName());
            searchResult.setPageFullName(doc.getFullName());
            searchResult.setTitle(title);
            searchResult.setWiki(wikiName);
            searchResult.setSpace(doc.getSpace());
            searchResult.setPageName(doc.getName());
            searchResult.setVersion(doc.getVersion());
            searchResult.setAuthor(doc.getAuthor());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(doc.getDate());
            searchResult.setModified(calendar);
            if (withPrettyNames) {
                searchResult.setAuthorName(xwikiApi.getUserName(doc.getAuthor(), false));
            }
            /*
                 * Avoid to return object information if the user is not authenticated. This will prevent crawlers to
                 * retrieve information such as email addresses and passwords from user's profiles.
                 */
            if (StringUtils.isNotEmpty(className) && xwikiContext.getUserReference() != null) {
                XWikiDocument xdocument = xwikiContext.getWiki().getDocument(doc.getDocumentReference(), xwikiContext);
                BaseObject baseObject = xdocument.getObject(className);
                if (baseObject != null) {
                    searchResult.setObject(this.modelFactory.toRestObject(uriInfo.getBaseUri(), doc, baseObject, false, false));
                }
            }
            String pageUri;
            if (StringUtils.isBlank(language)) {
                pageUri = Utils.createURI(uriInfo.getBaseUri(), PageResource.class, wikiName, Utils.getSpacesHierarchy(documentReference.getLastSpaceReference()), documentReference.getName()).toString();
            } else {
                searchResult.setLanguage(language);
                pageUri = Utils.createURI(uriInfo.getBaseUri(), PageTranslationResource.class, wikiName, Utils.getSpacesHierarchy(documentReference.getLastSpaceReference()), documentReference.getName(), language).toString();
            }
            Link pageLink = new Link();
            pageLink.setHref(pageUri);
            pageLink.setRel(Relations.PAGE);
            searchResult.getLinks().add(pageLink);
            result.add(searchResult);
        }
    }
    return result;
}
Also used : Query(org.xwiki.query.Query) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) XWikiContext(com.xpn.xwiki.XWikiContext) XWiki(com.xpn.xwiki.api.XWiki) SearchResult(org.xwiki.rest.model.jaxb.SearchResult) Document(com.xpn.xwiki.api.Document) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) BaseObject(com.xpn.xwiki.objects.BaseObject) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) BaseObject(com.xpn.xwiki.objects.BaseObject) WikiReference(org.xwiki.model.reference.WikiReference) DocumentReference(org.xwiki.model.reference.DocumentReference) Link(org.xwiki.rest.model.jaxb.Link)

Example 37 with Query

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

the class DefaultEventStatusManager method getEventStatus.

@Override
public List<EventStatus> getEventStatus(List<Event> events, List<String> entityIds) throws Exception {
    List<EventStatus> results = new ArrayList<>();
    // Don't perform any query if the list of events or entities is actually empty
    if (events.isEmpty() || entityIds.isEmpty()) {
        return results;
    }
    // Get the ActivityEventStatus from the database and convert them
    Query query = queryManager.createQuery("select eventStatus from ActivityEventStatusImpl eventStatus " + "where eventStatus.activityEvent.id in :eventIds and eventStatus.entityId in :entityIds", Query.HQL);
    query.bindValue("eventIds", getEventIds(events));
    query.bindValue("entityIds", entityIds);
    for (ActivityEventStatus activityEventStatus : query.<ActivityEventStatus>execute()) {
        results.add(new DefaultEventStatus(eventConverter.convertActivityToEvent(activityEventStatus.getActivityEvent()), activityEventStatus.getEntityId(), activityEventStatus.isRead()));
    }
    // For status that are not present in the database, we create objects with read = false
    for (Event event : events) {
        for (String entityId : entityIds) {
            if (!isPresent(event, entityId, results)) {
                results.add(new DefaultEventStatus(event, entityId, false));
            }
        }
    }
    // Sort statuses by date, in the descending order, like notifications, otherwise the order is lost
    Collections.sort(results, (status1, status2) -> status2.getEvent().getDate().compareTo(status1.getEvent().getDate()));
    return results;
}
Also used : ActivityEventStatus(com.xpn.xwiki.plugin.activitystream.api.ActivityEventStatus) Query(org.xwiki.query.Query) DefaultEventStatus(org.xwiki.eventstream.internal.DefaultEventStatus) DefaultEventStatus(org.xwiki.eventstream.internal.DefaultEventStatus) EventStatus(org.xwiki.eventstream.EventStatus) ActivityEventStatus(com.xpn.xwiki.plugin.activitystream.api.ActivityEventStatus) ArrayList(java.util.ArrayList) Event(org.xwiki.eventstream.Event)

Example 38 with Query

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

the class X509KeyWikiStoreTest 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(PRIVATEKEY, 64)).thenReturn(ENCODED_PRIVATEKEY);
    when(encoder.decode(ENCODED_PRIVATEKEY)).thenReturn(PRIVATEKEY);
    when(encoder.encode(ENCRYPTED_PRIVATEKEY, 64)).thenReturn(ENCODED_ENCRYPTED_PRIVATEKEY);
    when(encoder.decode(ENCODED_ENCRYPTED_PRIVATEKEY)).thenReturn(ENCRYPTED_PRIVATEKEY);
    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);
    privateKey = mock(PrivateKeyParameters.class);
    when(privateKey.getEncoded()).thenReturn(PRIVATEKEY);
    AsymmetricKeyFactory keyFactory = mocker.getInstance(AsymmetricKeyFactory.class);
    when(keyFactory.fromPKCS8(PRIVATEKEY)).thenReturn(privateKey);
    PrivateKeyPasswordBasedEncryptor encryptor = mocker.getInstance(PrivateKeyPasswordBasedEncryptor.class);
    when(encryptor.encrypt(PASSWORD, privateKey)).thenReturn(ENCRYPTED_PRIVATEKEY);
    when(encryptor.decrypt(PASSWORD, ENCRYPTED_PRIVATEKEY)).thenReturn(privateKey);
    certificate = mock(X509CertifiedPublicKey.class);
    when(certificate.getSerialNumber()).thenReturn(SERIAL);
    when(certificate.getIssuer()).thenReturn(new DistinguishedName(ISSUER));
    when(certificate.getSubject()).thenReturn(new DistinguishedName(SUBJECT));
    when(certificate.getEncoded()).thenReturn(CERTIFICATE);
    CertificateFactory certificateFactory = mocker.getInstance(CertificateFactory.class, "X509");
    when(certificateFactory.decode(CERTIFICATE)).thenReturn(certificate);
    X509Extensions extensions = mock(X509Extensions.class);
    when(certificate.getExtensions()).thenReturn(extensions);
    when(extensions.getSubjectKeyIdentifier()).thenReturn(SUBJECT_KEYID);
    when(certificate.getSubjectKeyIdentifier()).thenReturn(SUBJECT_KEYID);
    keyPair = new CertifiedKeyPair(privateKey, certificate);
    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) Query(org.xwiki.query.Query) DistinguishedName(org.xwiki.crypto.pkix.params.x509certificate.DistinguishedName) PrivateKeyParameters(org.xwiki.crypto.params.cipher.asymmetric.PrivateKeyParameters) XWikiContext(com.xpn.xwiki.XWikiContext) XWiki(com.xpn.xwiki.XWiki) X509Extensions(org.xwiki.crypto.pkix.params.x509certificate.extension.X509Extensions) CertificateFactory(org.xwiki.crypto.pkix.CertificateFactory) AsymmetricKeyFactory(org.xwiki.crypto.AsymmetricKeyFactory) EntityReferenceProvider(org.xwiki.model.reference.EntityReferenceProvider) X509CertifiedPublicKey(org.xwiki.crypto.pkix.params.x509certificate.X509CertifiedPublicKey) QueryManager(org.xwiki.query.QueryManager) PrivateKeyPasswordBasedEncryptor(org.xwiki.crypto.password.PrivateKeyPasswordBasedEncryptor) CertifiedKeyPair(org.xwiki.crypto.pkix.params.CertifiedKeyPair) Before(org.junit.Before)

Example 39 with Query

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

the class DefaultIconSetManager method getIconSetNames.

@Override
public List<String> getIconSetNames() throws IconException {
    try {
        String xwql = "SELECT obj.name FROM Document doc, doc.object(IconThemesCode.IconThemeClass) obj " + "ORDER BY obj.name";
        Query query = queryManager.createQuery(xwql, Query.XWQL);
        return query.execute();
    } catch (QueryException e) {
        throw new IconException("Failed to get the name of all icon sets.", e);
    }
}
Also used : QueryException(org.xwiki.query.QueryException) Query(org.xwiki.query.Query) IconException(org.xwiki.icon.IconException)

Example 40 with Query

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

the class DefaultIconSetManagerTest method getIconSetWhenDoesNotExists.

@Test
public void getIconSetWhenDoesNotExists() throws Exception {
    // Mocks
    Query query = mock(Query.class);
    when(queryManager.createQuery("FROM doc.object(IconThemesCode.IconThemeClass) obj WHERE obj.name = :name", Query.XWQL)).thenReturn(query);
    List<String> results = new ArrayList<>();
    when(query.<String>execute()).thenReturn(results);
    // Test
    assertNull(mocker.getComponentUnderTest().getIconSet("silk"));
    // Verify
    verify(query).bindValue("name", "silk");
}
Also used : Query(org.xwiki.query.Query) ArrayList(java.util.ArrayList) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.Test)

Aggregations

Query (org.xwiki.query.Query)129 DocumentReference (org.xwiki.model.reference.DocumentReference)41 Test (org.junit.Test)39 QueryException (org.xwiki.query.QueryException)36 ArrayList (java.util.ArrayList)29 XWikiException (com.xpn.xwiki.XWikiException)18 QueryFilter (org.xwiki.query.QueryFilter)18 QueryManager (org.xwiki.query.QueryManager)18 XWikiContext (com.xpn.xwiki.XWikiContext)15 HashMap (java.util.HashMap)14 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)12 Map (java.util.Map)11 List (java.util.List)9 Before (org.junit.Before)9 SecureQuery (org.xwiki.query.SecureQuery)9 XWiki (com.xpn.xwiki.XWiki)8 BaseObject (com.xpn.xwiki.objects.BaseObject)8 SQLQuery (org.hibernate.SQLQuery)8 WikiReference (org.xwiki.model.reference.WikiReference)8 WrappingQuery (org.xwiki.query.WrappingQuery)8