Search in sources :

Example 6 with SlingException

use of org.apache.sling.api.SlingException in project sling by apache.

the class OldStylePostOperationExample method run.

public void run(SlingHttpServletRequest request, HtmlResponse response, SlingPostProcessor[] processors) {
    final Resource r = request.getResource();
    final Node n = r.adaptTo(Node.class);
    try {
        response.setPath(r.getPath());
        response.setTitle("Content modified by " + getClass().getSimpleName());
        n.setProperty(getClass().getName(), "Old-style operation was applied to " + n.getPath());
        n.getSession().save();
    } catch (RepositoryException re) {
        throw new SlingException(getClass().getSimpleName() + " failed", re);
    }
}
Also used : Node(javax.jcr.Node) Resource(org.apache.sling.api.resource.Resource) SlingException(org.apache.sling.api.SlingException) RepositoryException(javax.jcr.RepositoryException)

Example 7 with SlingException

use of org.apache.sling.api.SlingException in project sling by apache.

the class SlingIOProvider method lastModified.

/**
     * Returns the value of the last modified meta data field of the resource
     * found at file name or zero if the meta data field is not set. If the
     * resource does not exist or an error occurrs finding the resource, -1 is
     * returned.
     */
public long lastModified(String fileName) {
    try {
        final Resource resource = getResourceInternal(fileName);
        if (resource != null) {
            final ResourceMetadata meta = resource.getResourceMetadata();
            final long modTime = meta.getModificationTime();
            return (modTime > 0) ? modTime : 0;
        }
    } catch (SlingException se) {
        logger.error("Cannot get last modification time for " + fileName, se);
    }
    // fallback to "non-existant" in case of problems
    return -1;
}
Also used : Resource(org.apache.sling.api.resource.Resource) SlingException(org.apache.sling.api.SlingException) ResourceMetadata(org.apache.sling.api.resource.ResourceMetadata)

Example 8 with SlingException

use of org.apache.sling.api.SlingException in project sling by apache.

the class RewriterResponse method getProcessor.

/**
     * Search the first matching processor
     */
private Processor getProcessor() {
    final ProcessingContext processorContext = new ServletProcessingContext(this.request, this, this.getSlingResponse(), this.contentType);
    Processor found = null;
    final List<ProcessorConfiguration> processorConfigs = this.processorManager.getProcessorConfigurations();
    final Iterator<ProcessorConfiguration> i = processorConfigs.iterator();
    while (found == null && i.hasNext()) {
        final ProcessorConfiguration config = i.next();
        if (config.match(processorContext)) {
            try {
                found = this.processorManager.getProcessor(config, processorContext);
                this.request.getRequestProgressTracker().log("Found processor for post processing {0}", config);
            } catch (final SlingException se) {
                // already processing an error, we ignore this!
                if (processorContext.getRequest().getAttribute("javax.servlet.error.status_code") != null) {
                    this.request.getRequestProgressTracker().log("Ignoring found processor for post processing {0}" + " as an error occured ({1}) during setup while processing another error.", config, se);
                } else {
                    throw se;
                }
            }
        }
    }
    return found;
}
Also used : ProcessorConfiguration(org.apache.sling.rewriter.ProcessorConfiguration) ProcessingContext(org.apache.sling.rewriter.ProcessingContext) Processor(org.apache.sling.rewriter.Processor) SlingException(org.apache.sling.api.SlingException)

Example 9 with SlingException

use of org.apache.sling.api.SlingException 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 10 with SlingException

use of org.apache.sling.api.SlingException in project sling by apache.

the class JcrResourceProvider method updateListeners.

/**
     * Update observation listeners.
     */
private void updateListeners() {
    if (this.listenerConfig == null) {
        this.unregisterListeners();
        this.registerListeners();
    } else {
        logger.debug("Updating resource listeners...");
        final Map<ObserverConfiguration, Closeable> oldMap = new HashMap<>(this.listeners);
        this.listeners.clear();
        try {
            for (final ObserverConfiguration config : this.getProviderContext().getObservationReporter().getObserverConfigurations()) {
                // check if such a listener already exists
                Closeable listener = oldMap.remove(config);
                if (listener == null) {
                    logger.debug("Registering listener for {}", config.getPaths());
                    listener = new JcrResourceListener(this.listenerConfig, config);
                } else {
                    logger.debug("Updating listener for {}", config.getPaths());
                    ((JcrResourceListener) listener).update(config);
                }
                this.listeners.put(config, listener);
            }
        } catch (final RepositoryException e) {
            throw new SlingException("Can't create the JCR event listener.", e);
        }
        for (final Closeable c : oldMap.values()) {
            try {
                logger.debug("Removing listener for {}", ((JcrResourceListener) c).getConfig().getPaths());
                c.close();
            } catch (final IOException e) {
            // ignore this as the method above does not throw it
            }
        }
        logger.debug("Updated resource listeners");
    }
}
Also used : HashMap(java.util.HashMap) Closeable(java.io.Closeable) ObserverConfiguration(org.apache.sling.spi.resource.provider.ObserverConfiguration) SlingException(org.apache.sling.api.SlingException) RepositoryException(javax.jcr.RepositoryException) JcrResourceListener(org.apache.sling.jcr.resource.internal.JcrResourceListener) IOException(java.io.IOException)

Aggregations

SlingException (org.apache.sling.api.SlingException)20 Resource (org.apache.sling.api.resource.Resource)10 IOException (java.io.IOException)8 RepositoryException (javax.jcr.RepositoryException)6 SlingHttpServletRequest (org.apache.sling.api.SlingHttpServletRequest)4 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)4 ServletException (javax.servlet.ServletException)3 SlingIOException (org.apache.sling.api.SlingIOException)3 SlingServletException (org.apache.sling.api.SlingServletException)3 SlingBindings (org.apache.sling.api.scripting.SlingBindings)3 Closeable (java.io.Closeable)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 Node (javax.jcr.Node)2 ScriptException (javax.script.ScriptException)2 UnavailableException (javax.servlet.UnavailableException)2 StringUtils.defaultString (org.apache.commons.lang3.StringUtils.defaultString)2 PersistenceException (org.apache.sling.api.resource.PersistenceException)2 ResourceMetadata (org.apache.sling.api.resource.ResourceMetadata)2 ResourceNotFoundException (org.apache.sling.api.resource.ResourceNotFoundException)2