Search in sources :

Example 1 with QuerySyntaxException

use of org.apache.sling.api.resource.QuerySyntaxException in project sling by apache.

the class JobManagerImpl method findJobs.

/**
     * @see org.apache.sling.event.jobs.JobManager#findJobs(org.apache.sling.event.jobs.JobManager.QueryType, java.lang.String, long, java.util.Map[])
     */
@Override
public Collection<Job> findJobs(final QueryType type, final String topic, final long limit, final Map<String, Object>... templates) {
    final boolean isHistoryQuery = type == QueryType.HISTORY || type == QueryType.SUCCEEDED || type == QueryType.CANCELLED || type == QueryType.DROPPED || type == QueryType.ERROR || type == QueryType.GIVEN_UP || type == QueryType.STOPPED;
    final List<Job> result = new ArrayList<>();
    final ResourceResolver resolver = this.configuration.createResourceResolver();
    final StringBuilder buf = new StringBuilder(64);
    try {
        buf.append("/jcr:root");
        buf.append(this.configuration.getJobsBasePathWithSlash());
        buf.append("/element(*,");
        buf.append(ResourceHelper.RESOURCE_TYPE_JOB);
        buf.append(")[@");
        buf.append(ISO9075.encode(ResourceHelper.PROPERTY_JOB_TOPIC));
        if (topic != null) {
            buf.append(" = '");
            buf.append(topic);
            buf.append("'");
        }
        // restricting on the type - history or unfinished
        if (isHistoryQuery) {
            buf.append(" and @");
            buf.append(ISO9075.encode(JobImpl.PROPERTY_FINISHED_STATE));
            if (type == QueryType.SUCCEEDED || type == QueryType.DROPPED || type == QueryType.ERROR || type == QueryType.GIVEN_UP || type == QueryType.STOPPED) {
                buf.append(" = '");
                buf.append(type.name());
                buf.append("'");
            } else if (type == QueryType.CANCELLED) {
                buf.append(" and (@");
                buf.append(ISO9075.encode(JobImpl.PROPERTY_FINISHED_STATE));
                buf.append(" = '");
                buf.append(QueryType.DROPPED.name());
                buf.append("' or @");
                buf.append(ISO9075.encode(JobImpl.PROPERTY_FINISHED_STATE));
                buf.append(" = '");
                buf.append(QueryType.ERROR.name());
                buf.append("' or @");
                buf.append(ISO9075.encode(JobImpl.PROPERTY_FINISHED_STATE));
                buf.append(" = '");
                buf.append(QueryType.GIVEN_UP.name());
                buf.append("' or @");
                buf.append(ISO9075.encode(JobImpl.PROPERTY_FINISHED_STATE));
                buf.append(" = '");
                buf.append(QueryType.STOPPED.name());
                buf.append("')");
            }
        } else {
            buf.append(" and not(@");
            buf.append(ISO9075.encode(JobImpl.PROPERTY_FINISHED_STATE));
            buf.append(")");
            if (type == QueryType.ACTIVE) {
                buf.append(" and @");
                buf.append(ISO9075.encode(Job.PROPERTY_JOB_STARTED_TIME));
            } else if (type == QueryType.QUEUED) {
                buf.append(" and not(@");
                buf.append(ISO9075.encode(Job.PROPERTY_JOB_STARTED_TIME));
                buf.append(")");
            }
        }
        if (templates != null && templates.length > 0) {
            int index = 0;
            for (final Map<String, Object> template : templates) {
                // skip empty templates
                if (template.size() == 0) {
                    continue;
                }
                if (index == 0) {
                    buf.append(" and (");
                } else {
                    buf.append(" or ");
                }
                buf.append('(');
                final Iterator<Map.Entry<String, Object>> i = template.entrySet().iterator();
                boolean first = true;
                while (i.hasNext()) {
                    final Map.Entry<String, Object> current = i.next();
                    final String key = ISO9075.encode(current.getKey());
                    final char firstChar = key.length() > 0 ? key.charAt(0) : 0;
                    final String propName;
                    final Operation op;
                    if (firstChar == '=') {
                        propName = key.substring(1);
                        op = Operation.EQUALS;
                    } else if (firstChar == '<') {
                        final char secondChar = key.length() > 1 ? key.charAt(1) : 0;
                        if (secondChar == '=') {
                            op = Operation.LESS_OR_EQUALS;
                            propName = key.substring(2);
                        } else {
                            op = Operation.LESS;
                            propName = key.substring(1);
                        }
                    } else if (firstChar == '>') {
                        final char secondChar = key.length() > 1 ? key.charAt(1) : 0;
                        if (secondChar == '=') {
                            op = Operation.GREATER_OR_EQUALS;
                            propName = key.substring(2);
                        } else {
                            op = Operation.GREATER;
                            propName = key.substring(1);
                        }
                    } else {
                        propName = key;
                        op = Operation.EQUALS;
                    }
                    if (first) {
                        first = false;
                        buf.append('@');
                    } else {
                        buf.append(" and @");
                    }
                    buf.append(propName);
                    buf.append(' ');
                    switch(op) {
                        case EQUALS:
                            buf.append('=');
                            break;
                        case LESS:
                            buf.append('<');
                            break;
                        case LESS_OR_EQUALS:
                            buf.append("<=");
                            break;
                        case GREATER:
                            buf.append('>');
                            break;
                        case GREATER_OR_EQUALS:
                            buf.append(">=");
                            break;
                    }
                    buf.append(" '");
                    buf.append(current.getValue());
                    buf.append("'");
                }
                buf.append(')');
                index++;
            }
            if (index > 0) {
                buf.append(')');
            }
        }
        buf.append("] order by @");
        if (isHistoryQuery) {
            buf.append(JobImpl.PROPERTY_FINISHED_DATE);
            buf.append(" descending");
        } else {
            buf.append(Job.PROPERTY_JOB_CREATED);
            buf.append(" ascending");
        }
        final Iterator<Resource> iter = resolver.findResources(buf.toString(), "xpath");
        long count = 0;
        while (iter.hasNext() && (limit < 1 || count < limit)) {
            final Resource jobResource = iter.next();
            // sanity check for the path
            if (this.configuration.isJob(jobResource.getPath())) {
                final JobImpl job = Utility.readJob(logger, jobResource);
                if (job != null) {
                    count++;
                    result.add(job);
                }
            }
        }
    } catch (final QuerySyntaxException qse) {
        logger.warn("Query syntax wrong " + buf.toString(), qse);
    } finally {
        resolver.close();
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) Resource(org.apache.sling.api.resource.Resource) QuerySyntaxException(org.apache.sling.api.resource.QuerySyntaxException) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Job(org.apache.sling.event.jobs.Job) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with QuerySyntaxException

use of org.apache.sling.api.resource.QuerySyntaxException in project sling by apache.

the class BasicQueryLanguageProvider method queryResources.

@Override
public Iterator<ValueMap> queryResources(final ResolveContext<JcrProviderState> ctx, final String query, final String language) {
    final String queryLanguage = ArrayUtils.contains(getSupportedLanguages(ctx), language) ? language : DEFAULT_QUERY_LANGUAGE;
    try {
        final QueryResult result = JcrResourceUtil.query(ctx.getProviderState().getSession(), query, queryLanguage);
        final String[] colNames = result.getColumnNames();
        final RowIterator rows = result.getRows();
        return new Iterator<ValueMap>() {

            private ValueMap next;

            {
                next = seek();
            }

            @Override
            public boolean hasNext() {
                return next != null;
            }

            ;

            @Override
            public ValueMap next() {
                if (next == null) {
                    throw new NoSuchElementException();
                }
                final ValueMap result = next;
                next = seek();
                return result;
            }

            private ValueMap seek() {
                ValueMap result = null;
                while (result == null && rows.hasNext()) {
                    try {
                        final Row jcrRow = rows.nextRow();
                        final String resourcePath = jcrRow.getPath();
                        if (resourcePath != null && providerContext.getExcludedPaths().matches(resourcePath) == null) {
                            final Map<String, Object> row = new HashMap<String, Object>();
                            boolean didPath = false;
                            boolean didScore = false;
                            final Value[] values = jcrRow.getValues();
                            for (int i = 0; i < values.length; i++) {
                                Value v = values[i];
                                if (v != null) {
                                    String colName = colNames[i];
                                    row.put(colName, JcrResourceUtil.toJavaObject(values[i]));
                                    if (colName.equals(QUERY_COLUMN_PATH)) {
                                        didPath = true;
                                        row.put(colName, JcrResourceUtil.toJavaObject(values[i]).toString());
                                    }
                                    if (colName.equals(QUERY_COLUMN_SCORE)) {
                                        didScore = true;
                                    }
                                }
                            }
                            if (!didPath) {
                                row.put(QUERY_COLUMN_PATH, jcrRow.getPath());
                            }
                            if (!didScore) {
                                row.put(QUERY_COLUMN_SCORE, jcrRow.getScore());
                            }
                            result = new ValueMapDecorator(row);
                        }
                    } catch (final RepositoryException re) {
                        logger.error("queryResources$next: Problem accessing row values", re);
                    }
                }
                return result;
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("remove");
            }
        };
    } catch (final javax.jcr.query.InvalidQueryException iqe) {
        throw new QuerySyntaxException(iqe.getMessage(), query, language, iqe);
    } catch (final RepositoryException re) {
        throw new SlingException(re.getMessage(), re);
    }
}
Also used : HashMap(java.util.HashMap) ValueMap(org.apache.sling.api.resource.ValueMap) ValueMapDecorator(org.apache.sling.api.wrappers.ValueMapDecorator) RepositoryException(javax.jcr.RepositoryException) QueryResult(javax.jcr.query.QueryResult) QuerySyntaxException(org.apache.sling.api.resource.QuerySyntaxException) RowIterator(javax.jcr.query.RowIterator) Iterator(java.util.Iterator) RowIterator(javax.jcr.query.RowIterator) Value(javax.jcr.Value) SlingException(org.apache.sling.api.SlingException) Row(javax.jcr.query.Row) NoSuchElementException(java.util.NoSuchElementException)

Example 3 with QuerySyntaxException

use of org.apache.sling.api.resource.QuerySyntaxException in project sling by apache.

the class JobManagerImpl method getJobById.

/**
     * @see org.apache.sling.event.jobs.JobManager#getJobById(java.lang.String)
     */
@Override
public Job getJobById(final String id) {
    logger.debug("Getting job by id: {}", id);
    final ResourceResolver resolver = this.configuration.createResourceResolver();
    final StringBuilder buf = new StringBuilder(64);
    try {
        buf.append("/jcr:root");
        buf.append(this.configuration.getJobsBasePathWithSlash());
        buf.append("/element(*,");
        buf.append(ResourceHelper.RESOURCE_TYPE_JOB);
        buf.append(")[@");
        buf.append(ResourceHelper.PROPERTY_JOB_ID);
        buf.append(" = '");
        buf.append(id);
        buf.append("']");
        if (logger.isDebugEnabled()) {
            logger.debug("Exceuting query: {}", buf.toString());
        }
        final Iterator<Resource> result = resolver.findResources(buf.toString(), "xpath");
        while (result.hasNext()) {
            final Resource jobResource = result.next();
            // sanity check for the path
            if (this.configuration.isJob(jobResource.getPath())) {
                final JobImpl job = Utility.readJob(logger, jobResource);
                if (job != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Found job with id {} = {}", id, Utility.toString(job));
                    }
                    return job;
                }
            }
        }
    } catch (final QuerySyntaxException qse) {
        logger.warn("Query syntax wrong " + buf.toString(), qse);
    } finally {
        resolver.close();
    }
    logger.debug("Job not found with id: {}", id);
    return null;
}
Also used : QuerySyntaxException(org.apache.sling.api.resource.QuerySyntaxException) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource)

Aggregations

QuerySyntaxException (org.apache.sling.api.resource.QuerySyntaxException)3 HashMap (java.util.HashMap)2 Resource (org.apache.sling.api.resource.Resource)2 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)2 ArrayList (java.util.ArrayList)1 Iterator (java.util.Iterator)1 Map (java.util.Map)1 NoSuchElementException (java.util.NoSuchElementException)1 RepositoryException (javax.jcr.RepositoryException)1 Value (javax.jcr.Value)1 QueryResult (javax.jcr.query.QueryResult)1 Row (javax.jcr.query.Row)1 RowIterator (javax.jcr.query.RowIterator)1 SlingException (org.apache.sling.api.SlingException)1 ValueMap (org.apache.sling.api.resource.ValueMap)1 ValueMapDecorator (org.apache.sling.api.wrappers.ValueMapDecorator)1 Job (org.apache.sling.event.jobs.Job)1