Search in sources :

Example 1 with QueryException

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

the class ExplicitlyAllowedValuesDBListQueryBuilder method build.

@Override
public Query build(DBListClass dbListClass) throws QueryException {
    String statement = dbListClass.getSql();
    DocumentReference authorReference = dbListClass.getOwnerDocument().getAuthorReference();
    if (this.authorizationManager.hasAccess(Right.SCRIPT, authorReference, dbListClass.getReference())) {
        String namespace = this.entityReferenceSerializer.serialize(dbListClass.getDocumentReference());
        try {
            statement = this.authorExecutor.call(() -> {
                return evaluateVelocityCode(dbListClass.getSql(), namespace);
            }, authorReference);
        } catch (Exception e) {
            this.logger.warn("Failed to evaluate the Velocity code from the query [{}]." + " Root cause is [{}]. Continuing with the raw query.", statement, ExceptionUtils.getRootCauseMessage(e));
        }
    }
    Query query = this.secureQueryManager.createQuery(statement, Query.HQL);
    query.setWiki(dbListClass.getOwnerDocument().getDocumentReference().getWikiReference().getName());
    return query;
}
Also used : Query(org.xwiki.query.Query) DocumentReference(org.xwiki.model.reference.DocumentReference) QueryException(org.xwiki.query.QueryException)

Example 2 with QueryException

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

the class XClassMigratorListener method onEvent.

@Override
public void onEvent(Event event, Object source, Object data) {
    XClassPropertyUpdatedEvent propertyEvent = (XClassPropertyUpdatedEvent) event;
    XWikiDocument newDocument = (XWikiDocument) source;
    XWikiDocument previousDocument = newDocument.getOriginalDocument();
    PropertyClass newPropertyClass = (PropertyClass) newDocument.getXClass().getField(propertyEvent.getReference().getName());
    PropertyClass previousPropertyClass = (PropertyClass) previousDocument.getXClass().getField(propertyEvent.getReference().getName());
    if (newPropertyClass != null && previousPropertyClass != null) {
        BaseProperty newProperty = newPropertyClass.newProperty();
        BaseProperty previousProperty = previousPropertyClass.newProperty();
        // New and previous class property generate different kind of properties
        if (newProperty.getClass() != previousProperty.getClass()) {
            try {
                migrate(newPropertyClass);
            } catch (QueryException e) {
                this.logger.error("Failed to migrate XClass property [{}]", newPropertyClass.getReference(), e);
            }
        }
    }
}
Also used : XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) QueryException(org.xwiki.query.QueryException) XClassPropertyUpdatedEvent(com.xpn.xwiki.internal.event.XClassPropertyUpdatedEvent) BaseProperty(com.xpn.xwiki.objects.BaseProperty) PropertyClass(com.xpn.xwiki.objects.classes.PropertyClass)

Example 3 with QueryException

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

the class XWQLQueryExecutor method execute.

@Override
public <T> List<T> execute(Query query) throws QueryException {
    EntityReference currentEntityReference = this.context.getCurrentEntityReference();
    Query nativeQuery;
    try {
        this.progress.startStep(query, "query.xwql.progress.execute", "Execute XWQL query [{}]", query);
        if (query.getWiki() != null) {
            if (currentEntityReference.getType() == EntityType.WIKI) {
                this.context.setCurrentEntityReference(new WikiReference(query.getWiki()));
            } else {
                this.context.setCurrentEntityReference(currentEntityReference.replaceParent(currentEntityReference.extractReference(EntityType.WIKI), new WikiReference(query.getWiki())));
            }
        }
        nativeQuery = getQueryManager().createQuery(this.translator.translate(query.getStatement()), this.translator.getOutputLanguage());
        nativeQuery.setLimit(query.getLimit());
        nativeQuery.setOffset(query.getOffset());
        nativeQuery.setWiki(query.getWiki());
        if (query.getFilters() != null) {
            for (QueryFilter filter : query.getFilters()) {
                nativeQuery.addFilter(filter);
            }
        }
        for (Entry<String, Object> e : query.getNamedParameters().entrySet()) {
            nativeQuery.bindValue(e.getKey(), e.getValue());
        }
        for (Entry<Integer, Object> e : query.getPositionalParameters().entrySet()) {
            nativeQuery.bindValue(e.getKey(), e.getValue());
        }
        if (nativeQuery instanceof SecureQuery && query instanceof SecureQuery) {
            // No need to validate the HQL query for short XWQL queries
            if (((SecureQuery) query).isCurrentAuthorChecked() && !isShortFormStatement(query.getStatement())) {
                ((SecureQuery) nativeQuery).checkCurrentAuthor(true);
            }
            // Let HQL module take care of that is supported
            ((SecureQuery) nativeQuery).checkCurrentUser(((SecureQuery) query).isCurrentUserChecked());
        }
        return nativeQuery.execute();
    } catch (Exception e) {
        if (e instanceof QueryException) {
            throw (QueryException) e;
        }
        throw new QueryException("Exception while translating [" + query.getStatement() + "] XWQL query to the [" + this.translator.getOutputLanguage() + "] language", query, e);
    } finally {
        this.context.setCurrentEntityReference(currentEntityReference);
        this.progress.endStep(query);
    }
}
Also used : QueryFilter(org.xwiki.query.QueryFilter) QueryException(org.xwiki.query.QueryException) Query(org.xwiki.query.Query) SecureQuery(org.xwiki.query.SecureQuery) EntityReference(org.xwiki.model.reference.EntityReference) WikiReference(org.xwiki.model.reference.WikiReference) SecureQuery(org.xwiki.query.SecureQuery) QueryException(org.xwiki.query.QueryException) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException)

Example 4 with QueryException

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

the class RepositoryManager method importExtension.

public DocumentReference importExtension(String extensionId, ExtensionRepository repository, Type type) throws QueryException, XWikiException, ResolveException {
    TreeMap<Version, String> versions = new TreeMap<Version, String>();
    Version lastVersion = getVersions(extensionId, repository, type, versions);
    if (lastVersion == null) {
        throw new ExtensionNotFoundException("Can't find any version for the extension [" + extensionId + "] on repository [" + repository + "]");
    } else if (versions.isEmpty()) {
        // If no valid version import the last version
        versions.put(lastVersion, extensionId);
    } else {
        // Select the last valid version
        lastVersion = versions.lastKey();
    }
    Extension extension = repository.resolve(new ExtensionId(extensionId, lastVersion));
    // Get former ids versions
    Collection<ExtensionId> features = extension.getExtensionFeatures();
    for (ExtensionId feature : features) {
        try {
            getVersions(feature.getId(), repository, type, versions);
        } catch (ResolveException e) {
        // Ignore
        }
    }
    XWikiContext xcontext = this.xcontextProvider.get();
    boolean needSave = false;
    XWikiDocument document = getExistingExtensionDocumentById(extensionId);
    if (document == null) {
        // Create document
        document = xcontext.getWiki().getDocument(new DocumentReference(xcontext.getWikiId(), Arrays.asList("Extension", extension.getName()), "WebHome"), xcontext);
        for (int i = 1; !document.isNew(); ++i) {
            document = xcontext.getWiki().getDocument(new DocumentReference(xcontext.getWikiId(), Arrays.asList("Extension", extension.getName() + ' ' + i), "WebHome"), xcontext);
        }
        document.readFromTemplate(this.currentResolver.resolve(XWikiRepositoryModel.EXTENSION_TEMPLATEREFERENCE), xcontext);
        needSave = true;
    }
    // Update document
    BaseObject extensionObject = document.getXObject(XWikiRepositoryModel.EXTENSION_CLASSREFERENCE);
    if (extensionObject == null) {
        extensionObject = document.newXObject(XWikiRepositoryModel.EXTENSION_CLASSREFERENCE, xcontext);
        needSave = true;
    }
    if (!StringUtils.equals(extensionId, getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_ID, (String) null))) {
        extensionObject.set(XWikiRepositoryModel.PROP_EXTENSION_ID, extensionId, xcontext);
        needSave = true;
    }
    // Update extension informations
    needSave |= updateExtension(extension, extensionObject, xcontext);
    // Proxy marker
    BaseObject extensionProxyObject = document.getXObject(XWikiRepositoryModel.EXTENSIONPROXY_CLASSREFERENCE);
    if (extensionProxyObject == null) {
        extensionProxyObject = document.newXObject(XWikiRepositoryModel.EXTENSIONPROXY_CLASSREFERENCE, xcontext);
        extensionProxyObject.setIntValue(XWikiRepositoryModel.PROP_PROXY_AUTOUPDATE, 1);
        needSave = true;
    }
    needSave |= update(extensionProxyObject, XWikiRepositoryModel.PROP_PROXY_REPOSITORYID, repository.getDescriptor().getId());
    needSave |= update(extensionProxyObject, XWikiRepositoryModel.PROP_PROXY_REPOSITORYTYPE, repository.getDescriptor().getType());
    needSave |= update(extensionProxyObject, XWikiRepositoryModel.PROP_PROXY_REPOSITORYURI, repository.getDescriptor().getURI().toString());
    // Remove unexisting versions
    Set<String> validVersions = new HashSet<String>();
    List<BaseObject> versionObjects = document.getXObjects(XWikiRepositoryModel.EXTENSIONVERSION_CLASSREFERENCE);
    if (versionObjects != null) {
        for (BaseObject versionObject : versionObjects) {
            if (versionObject != null) {
                String version = getValue(versionObject, XWikiRepositoryModel.PROP_VERSION_VERSION);
                if (StringUtils.isBlank(version) || (isVersionProxyingEnabled(document) && !new DefaultVersion(version).equals(extension.getId().getVersion()))) {
                    // Empty version OR old versions should be proxied
                    document.removeXObject(versionObject);
                    needSave = true;
                } else {
                    if (!versions.containsKey(new DefaultVersion(version))) {
                        // The version does not exist on remote repository
                        if (!isVersionValid(document, versionObject, xcontext)) {
                            // The version is invalid, removing it to not make the whole extension invalid
                            document.removeXObject(versionObject);
                            needSave = true;
                        } else {
                            // The version is valid, lets keep it
                            validVersions.add(version);
                        }
                    } else {
                        // This version exist on remote repository
                        validVersions.add(version);
                    }
                }
            }
        }
    }
    List<BaseObject> dependencyObjects = document.getXObjects(XWikiRepositoryModel.EXTENSIONDEPENDENCY_CLASSREFERENCE);
    if (dependencyObjects != null) {
        for (BaseObject dependencyObject : dependencyObjects) {
            if (dependencyObject != null) {
                String version = getValue(dependencyObject, XWikiRepositoryModel.PROP_DEPENDENCY_EXTENSIONVERSION);
                if (!validVersions.contains(version)) {
                    // The version is invalid, removing it to not make the whole extension invalid
                    document.removeXObject(dependencyObject);
                    needSave = true;
                }
            }
        }
    }
    for (Map.Entry<Version, String> entry : versions.entrySet()) {
        Version version = entry.getKey();
        String id = entry.getValue();
        try {
            Extension versionExtension;
            if (version.equals(extension.getId().getVersion())) {
                versionExtension = extension;
            } else if (isVersionProxyingEnabled(document)) {
                continue;
            } else {
                versionExtension = repository.resolve(new ExtensionId(id, version));
            }
            // Update version related informations
            needSave |= updateExtensionVersion(document, versionExtension);
        } catch (Exception e) {
            this.logger.error("Failed to resolve extension with id [" + id + "] and version [" + version + "] on repository [" + repository + "]", e);
        }
    }
    if (needSave) {
        document.setAuthorReference(xcontext.getUserReference());
        if (document.isNew()) {
            document.setContentAuthorReference(xcontext.getUserReference());
            document.setCreatorReference(xcontext.getUserReference());
        }
        xcontext.getWiki().saveDocument(document, "Imported extension [" + extensionId + "] from repository [" + repository.getDescriptor() + "]", true, xcontext);
    }
    return document.getDocumentReference();
}
Also used : ExtensionNotFoundException(org.xwiki.extension.ExtensionNotFoundException) DefaultVersion(org.xwiki.extension.version.internal.DefaultVersion) XWikiContext(com.xpn.xwiki.XWikiContext) ExtensionId(org.xwiki.extension.ExtensionId) TreeMap(java.util.TreeMap) DefaultVersionConstraint(org.xwiki.extension.version.internal.DefaultVersionConstraint) XWikiException(com.xpn.xwiki.XWikiException) ComponentLifecycleException(org.xwiki.component.manager.ComponentLifecycleException) InitializationException(org.xwiki.component.phase.InitializationException) ExtensionNotFoundException(org.xwiki.extension.ExtensionNotFoundException) WebApplicationException(javax.ws.rs.WebApplicationException) QueryException(org.xwiki.query.QueryException) ResolveException(org.xwiki.extension.ResolveException) CacheException(org.xwiki.cache.CacheException) BaseObject(com.xpn.xwiki.objects.BaseObject) Extension(org.xwiki.extension.Extension) ResolveException(org.xwiki.extension.ResolveException) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) Version(org.xwiki.extension.version.Version) DefaultVersion(org.xwiki.extension.version.internal.DefaultVersion) Map(java.util.Map) TreeMap(java.util.TreeMap) DocumentReference(org.xwiki.model.reference.DocumentReference) HashSet(java.util.HashSet)

Example 5 with QueryException

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

the class ExtensionVersionFileRESTResource method downloadLocalExtension.

private ResponseBuilder downloadLocalExtension(String extensionId, String extensionVersion) throws ResolveException, IOException, QueryException, XWikiException {
    XWikiDocument extensionDocument = getExistingExtensionDocumentById(extensionId);
    checkRights(extensionDocument);
    ResourceReference resourceReference = repositoryManager.getDownloadReference(extensionDocument, extensionVersion);
    ResponseBuilder response = null;
    if (ResourceType.ATTACHMENT.equals(resourceReference.getType())) {
        // It's an attachment
        AttachmentReference attachmentReference = this.attachmentResolver.resolve(resourceReference.getReference(), extensionDocument.getDocumentReference());
        XWikiContext xcontext = getXWikiContext();
        XWikiDocument document = xcontext.getWiki().getDocument(attachmentReference.getDocumentReference(), xcontext);
        checkRights(document);
        XWikiAttachment xwikiAttachment = document.getAttachment(attachmentReference.getName());
        response = getAttachmentResponse(xwikiAttachment);
    } else if (ResourceType.URL.equals(resourceReference.getType())) {
        // It's an URL
        URL url = new URL(resourceReference.getReference());
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "XWikiExtensionRepository");
        httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
        httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        httpClient.setRoutePlanner(routePlanner);
        HttpGet getMethod = new HttpGet(url.toString());
        HttpResponse subResponse;
        try {
            subResponse = httpClient.execute(getMethod);
        } catch (Exception e) {
            throw new IOException("Failed to request [" + getMethod.getURI() + "]", e);
        }
        response = Response.status(subResponse.getStatusLine().getStatusCode());
        // TODO: find a proper way to do a perfect proxy of the URL without directly using Restlet classes.
        // Should probably use javax.ws.rs.ext.MessageBodyWriter
        HttpEntity entity = subResponse.getEntity();
        InputRepresentation content = new InputRepresentation(entity.getContent(), entity.getContentType() != null ? new MediaType(entity.getContentType().getValue()) : MediaType.APPLICATION_OCTET_STREAM, entity.getContentLength());
        BaseObject extensionObject = getExtensionObject(extensionDocument);
        String type = getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_TYPE);
        Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT);
        disposition.setFilename(extensionId + '-' + extensionVersion + '.' + type);
        content.setDisposition(disposition);
        response.entity(content);
    } else if (ExtensionResourceReference.TYPE.equals(resourceReference.getType())) {
        ExtensionResourceReference extensionResource;
        if (resourceReference instanceof ExtensionResourceReference) {
            extensionResource = (ExtensionResourceReference) resourceReference;
        } else {
            extensionResource = new ExtensionResourceReference(resourceReference.getReference());
        }
        response = downloadRemoteExtension(extensionResource);
    } else {
        throw new WebApplicationException(Status.NOT_FOUND);
    }
    return response;
}
Also used : AttachmentReference(org.xwiki.model.reference.AttachmentReference) HttpEntity(org.apache.http.HttpEntity) InputRepresentation(org.restlet.representation.InputRepresentation) WebApplicationException(javax.ws.rs.WebApplicationException) HttpGet(org.apache.http.client.methods.HttpGet) XWikiContext(com.xpn.xwiki.XWikiContext) HttpResponse(org.apache.http.HttpResponse) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) IOException(java.io.IOException) URL(java.net.URL) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) XWikiException(com.xpn.xwiki.XWikiException) URISyntaxException(java.net.URISyntaxException) WebApplicationException(javax.ws.rs.WebApplicationException) QueryException(org.xwiki.query.QueryException) IOException(java.io.IOException) ResolveException(org.xwiki.extension.ResolveException) BaseObject(com.xpn.xwiki.objects.BaseObject) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) ProxySelectorRoutePlanner(org.apache.http.impl.conn.ProxySelectorRoutePlanner) Disposition(org.restlet.data.Disposition) MediaType(org.restlet.data.MediaType) ResourceReference(org.xwiki.rendering.listener.reference.ResourceReference) ExtensionResourceReference(org.xwiki.repository.internal.reference.ExtensionResourceReference) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ExtensionResourceReference(org.xwiki.repository.internal.reference.ExtensionResourceReference)

Aggregations

QueryException (org.xwiki.query.QueryException)57 Query (org.xwiki.query.Query)32 DocumentReference (org.xwiki.model.reference.DocumentReference)19 XWikiException (com.xpn.xwiki.XWikiException)18 ArrayList (java.util.ArrayList)14 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)11 BaseObject (com.xpn.xwiki.objects.BaseObject)8 Test (org.junit.Test)8 QueryFilter (org.xwiki.query.QueryFilter)7 XWikiContext (com.xpn.xwiki.XWikiContext)6 HashMap (java.util.HashMap)6 XWikiRestException (org.xwiki.rest.XWikiRestException)6 Event (org.xwiki.eventstream.Event)5 WikiReference (org.xwiki.model.reference.WikiReference)5 Date (java.util.Date)4 List (java.util.List)4 IconException (org.xwiki.icon.IconException)4 QueryManager (org.xwiki.query.QueryManager)4 SecureQuery (org.xwiki.query.SecureQuery)4 XWiki (com.xpn.xwiki.XWiki)3