Search in sources :

Example 1 with RuntimeObjectModel

use of org.apache.sling.scripting.sightly.render.RuntimeObjectModel in project sling by apache.

the class URIManipulationFilterExtension method call.

@Override
@SuppressWarnings("unchecked")
public Object call(RenderContext renderContext, Object... arguments) {
    ExtensionUtils.checkArgumentCount(RuntimeFunction.URI_MANIPULATION, arguments, 2);
    RuntimeObjectModel runtimeObjectModel = renderContext.getObjectModel();
    String uriString = runtimeObjectModel.toString(arguments[0]);
    Map<String, Object> options = runtimeObjectModel.toMap(arguments[1]);
    StringBuilder sb = new StringBuilder();
    PathInfo pathInfo = new PathInfo(uriString);
    uriAppender(sb, SCHEME, options, pathInfo.getScheme());
    if (sb.length() > 0) {
        sb.append(":");
        sb.append(StringUtils.defaultIfEmpty(pathInfo.getBeginPathSeparator(), "//"));
    }
    if (sb.length() > 0) {
        uriAppender(sb, DOMAIN, options, pathInfo.getHost());
    } else {
        String domain = getOption(DOMAIN, options, pathInfo.getHost());
        if (StringUtils.isNotEmpty(domain)) {
            sb.append("//").append(domain);
        }
    }
    if (pathInfo.getPort() > -1) {
        sb.append(":").append(pathInfo.getPort());
    }
    String prependPath = getOption(PREPEND_PATH, options, StringUtils.EMPTY);
    if (prependPath == null) {
        prependPath = StringUtils.EMPTY;
    }
    String path = getOption(PATH, options, pathInfo.getPath());
    if (StringUtils.isEmpty(path)) {
        // if the path is forced to be empty don't remove the path
        path = pathInfo.getPath();
    }
    if (StringUtils.isNotEmpty(path) && !"/".equals(path)) {
        if (StringUtils.isNotEmpty(prependPath)) {
            if (sb.length() > 0 && !prependPath.startsWith("/")) {
                prependPath = "/" + prependPath;
            }
            if (!prependPath.endsWith("/")) {
                prependPath += "/";
            }
        }
        String appendPath = getOption(APPEND_PATH, options, StringUtils.EMPTY);
        if (appendPath == null) {
            appendPath = StringUtils.EMPTY;
        }
        if (StringUtils.isNotEmpty(appendPath)) {
            if (!appendPath.startsWith("/")) {
                appendPath = "/" + appendPath;
            }
        }
        String newPath;
        try {
            newPath = new URI(prependPath + path + appendPath).normalize().getPath();
        } catch (URISyntaxException e) {
            newPath = prependPath + path + appendPath;
        }
        if (sb.length() > 0 && sb.lastIndexOf("/") != sb.length() - 1 && StringUtils.isNotEmpty(newPath) && !newPath.startsWith("/")) {
            sb.append("/");
        }
        sb.append(newPath);
        Set<String> selectors = pathInfo.getSelectors();
        handleSelectors(runtimeObjectModel, selectors, options);
        for (String selector : selectors) {
            if (StringUtils.isNotBlank(selector) && !selector.contains(" ")) {
                // make sure not to append empty or invalid selectors
                sb.append(".").append(selector);
            }
        }
        String extension = getOption(EXTENSION, options, pathInfo.getExtension());
        if (StringUtils.isNotEmpty(extension)) {
            sb.append(".").append(extension);
        }
        String prependSuffix = getOption(PREPEND_SUFFIX, options, StringUtils.EMPTY);
        if (StringUtils.isNotEmpty(prependSuffix)) {
            if (!prependSuffix.startsWith("/")) {
                prependSuffix = "/" + prependSuffix;
            }
            if (!prependSuffix.endsWith("/")) {
                prependSuffix += "/";
            }
        }
        String pathInfoSuffix = pathInfo.getSuffix();
        String suffix = getOption(SUFFIX, options, pathInfoSuffix == null ? StringUtils.EMPTY : pathInfoSuffix);
        if (suffix == null) {
            suffix = StringUtils.EMPTY;
        }
        String appendSuffix = getOption(APPEND_SUFFIX, options, StringUtils.EMPTY);
        if (StringUtils.isNotEmpty(appendSuffix)) {
            appendSuffix = "/" + appendSuffix;
        }
        String newSuffix = FilenameUtils.normalize(prependSuffix + suffix + appendSuffix, true);
        if (StringUtils.isNotEmpty(newSuffix)) {
            if (!newSuffix.startsWith("/")) {
                sb.append("/");
            }
            sb.append(newSuffix);
        }
    } else if ("/".equals(path)) {
        sb.append(path);
    }
    Map<String, Collection<String>> parameters = pathInfo.getParameters();
    handleParameters(runtimeObjectModel, parameters, options);
    if (sb.length() > 0 && !parameters.isEmpty()) {
        if (StringUtils.isEmpty(path)) {
            sb.append("/");
        }
        sb.append("?");
        for (Map.Entry<String, Collection<String>> entry : parameters.entrySet()) {
            for (String value : entry.getValue()) {
                sb.append(entry.getKey()).append("=").append(value).append("&");
            }
        }
        // delete the last &
        sb.deleteCharAt(sb.length() - 1);
    }
    String fragment = getOption(FRAGMENT, options, pathInfo.getFragment());
    if (StringUtils.isNotEmpty(fragment)) {
        sb.append("#").append(fragment);
    }
    return sb.toString();
}
Also used : RuntimeObjectModel(org.apache.sling.scripting.sightly.render.RuntimeObjectModel) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) Collection(java.util.Collection) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 2 with RuntimeObjectModel

use of org.apache.sling.scripting.sightly.render.RuntimeObjectModel in project sling by apache.

the class UseRuntimeExtension method call.

@Override
public Object call(final RenderContext renderContext, Object... arguments) {
    ExtensionUtils.checkArgumentCount(RuntimeFunction.USE, arguments, 2);
    RuntimeObjectModel runtimeObjectModel = renderContext.getObjectModel();
    String identifier = runtimeObjectModel.toString(arguments[0]);
    if (StringUtils.isEmpty(identifier)) {
        throw new SightlyException("data-sly-use needs to be passed an identifier");
    }
    Map<String, Object> useArgumentsMap = runtimeObjectModel.toMap(arguments[1]);
    Bindings useArguments = new SimpleBindings(Collections.unmodifiableMap(useArgumentsMap));
    ArrayList<UseProvider> providers = new ArrayList<>(providersMap.values());
    ListIterator<UseProvider> iterator = providers.listIterator(providers.size());
    while (iterator.hasPrevious()) {
        UseProvider provider = iterator.previous();
        ProviderOutcome outcome = provider.provide(identifier, renderContext, useArguments);
        Throwable failureCause;
        if (outcome.isSuccess()) {
            return outcome.getResult();
        } else if ((failureCause = outcome.getCause()) != null) {
            throw new SightlyException("Identifier " + identifier + " cannot be correctly instantiated by the Use API", failureCause);
        }
    }
    throw new SightlyException("No use provider could resolve identifier " + identifier);
}
Also used : RuntimeObjectModel(org.apache.sling.scripting.sightly.render.RuntimeObjectModel) ArrayList(java.util.ArrayList) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) ProviderOutcome(org.apache.sling.scripting.sightly.use.ProviderOutcome) UseProvider(org.apache.sling.scripting.sightly.use.UseProvider) SightlyException(org.apache.sling.scripting.sightly.SightlyException) SimpleBindings(javax.script.SimpleBindings)

Example 3 with RuntimeObjectModel

use of org.apache.sling.scripting.sightly.render.RuntimeObjectModel in project sling by apache.

the class JoinFilterExtension method call.

@Override
public Object call(final RenderContext renderContext, Object... arguments) {
    ExtensionUtils.checkArgumentCount(RuntimeFunction.JOIN, arguments, 2);
    Object joinArgument = arguments[0];
    RuntimeObjectModel runtimeObjectModel = renderContext.getObjectModel();
    Collection<?> collection = runtimeObjectModel.toCollection(joinArgument);
    String joinString = runtimeObjectModel.toString(arguments[1]);
    return join(runtimeObjectModel, collection, joinString);
}
Also used : RuntimeObjectModel(org.apache.sling.scripting.sightly.render.RuntimeObjectModel)

Example 4 with RuntimeObjectModel

use of org.apache.sling.scripting.sightly.render.RuntimeObjectModel in project sling by apache.

the class ResourceRuntimeExtension method provideResource.

private String provideResource(final RenderContext renderContext, Object pathObj, Map<String, Object> options) {
    Map<String, Object> opts = new HashMap<>(options);
    final Bindings bindings = renderContext.getBindings();
    SlingHttpServletRequest request = BindingsUtils.getRequest(bindings);
    Map originalAttributes = ExtensionUtils.setRequestAttributes(request, (Map) options.remove(OPTION_REQUEST_ATTRIBUTES));
    RuntimeObjectModel runtimeObjectModel = renderContext.getObjectModel();
    String resourceType = runtimeObjectModel.toString(getAndRemoveOption(opts, OPTION_RESOURCE_TYPE));
    StringWriter writer = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    if (pathObj instanceof Resource) {
        Resource includedResource = (Resource) pathObj;
        Map<String, String> dispatcherOptionsMap = handleSelectors(request, new LinkedHashSet<String>(), opts, runtimeObjectModel);
        String dispatcherOptions = createDispatcherOptions(dispatcherOptionsMap);
        includeResource(bindings, printWriter, includedResource, dispatcherOptions, resourceType);
    } else {
        String includePath = runtimeObjectModel.toString(pathObj);
        // build path completely
        includePath = buildPath(includePath, options, request.getResource());
        if (includePath != null) {
            // check if path identifies an existing resource
            Resource includedResource = request.getResourceResolver().getResource(includePath);
            PathInfo pathInfo;
            if (includedResource != null) {
                Map<String, String> dispatcherOptionsMap = handleSelectors(request, new LinkedHashSet<String>(), opts, runtimeObjectModel);
                String dispatcherOptions = createDispatcherOptions(dispatcherOptionsMap);
                includeResource(bindings, printWriter, includedResource, dispatcherOptions, resourceType);
            } else {
                // analyse path and decompose potential selectors from the path
                pathInfo = new PathInfo(includePath);
                Map<String, String> dispatcherOptionsMap = handleSelectors(request, pathInfo.selectors, opts, runtimeObjectModel);
                String dispatcherOptions = createDispatcherOptions(dispatcherOptionsMap);
                includeResource(bindings, printWriter, pathInfo.path, dispatcherOptions, resourceType);
            }
        } else {
            // use the current resource
            Map<String, String> dispatcherOptionsMap = handleSelectors(request, new LinkedHashSet<String>(), opts, runtimeObjectModel);
            String dispatcherOptions = createDispatcherOptions(dispatcherOptionsMap);
            includeResource(bindings, printWriter, request.getResource(), dispatcherOptions, resourceType);
        }
    }
    ExtensionUtils.setRequestAttributes(request, originalAttributes);
    return writer.toString();
}
Also used : HashMap(java.util.HashMap) RuntimeObjectModel(org.apache.sling.scripting.sightly.render.RuntimeObjectModel) Resource(org.apache.sling.api.resource.Resource) SyntheticResource(org.apache.sling.api.resource.SyntheticResource) Bindings(javax.script.Bindings) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) Map(java.util.Map) PrintWriter(java.io.PrintWriter)

Example 5 with RuntimeObjectModel

use of org.apache.sling.scripting.sightly.render.RuntimeObjectModel in project sling by apache.

the class FormatFilterExtension method call.

@Override
public Object call(final RenderContext renderContext, Object... arguments) {
    ExtensionUtils.checkArgumentCount(RuntimeFunction.FORMAT, arguments, 2);
    RuntimeObjectModel runtimeObjectModel = renderContext.getObjectModel();
    String source = runtimeObjectModel.toString(arguments[0]);
    Map<String, Object> options = (Map<String, Object>) arguments[1];
    String formattingType = runtimeObjectModel.toString(options.get(TYPE_OPTION));
    Object formatObject = options.get(FORMAT_OPTION);
    boolean hasPlaceHolders = PLACEHOLDER_REGEX.matcher(source).find();
    if (STRING_FORMAT_TYPE.equals(formattingType)) {
        Object[] params = decodeParams(runtimeObjectModel, formatObject);
        return formatString(runtimeObjectModel, source, params);
    } else if (DATE_FORMAT_TYPE.equals(formattingType) || (!hasPlaceHolders && runtimeObjectModel.isDate(formatObject))) {
        Locale locale = getLocale(runtimeObjectModel, options);
        TimeZone timezone = getTimezone(runtimeObjectModel, options);
        return formatDate(source, runtimeObjectModel.toDate(formatObject), locale, timezone);
    } else if (NUMBER_FORMAT_TYPE.equals(formattingType) || (!hasPlaceHolders && runtimeObjectModel.isNumber(formatObject))) {
        Locale locale = getLocale(runtimeObjectModel, options);
        return formatNumber(source, runtimeObjectModel.toNumber(formatObject), locale);
    }
    if (hasPlaceHolders) {
        Object[] params = decodeParams(runtimeObjectModel, formatObject);
        return formatString(runtimeObjectModel, source, params);
    }
    return null;
}
Also used : Locale(java.util.Locale) TimeZone(java.util.TimeZone) RuntimeObjectModel(org.apache.sling.scripting.sightly.render.RuntimeObjectModel) Map(java.util.Map)

Aggregations

RuntimeObjectModel (org.apache.sling.scripting.sightly.render.RuntimeObjectModel)7 Map (java.util.Map)5 Bindings (javax.script.Bindings)4 PrintWriter (java.io.PrintWriter)2 StringWriter (java.io.StringWriter)2 SlingHttpServletRequest (org.apache.sling.api.SlingHttpServletRequest)2 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1 Locale (java.util.Locale)1 TimeZone (java.util.TimeZone)1 SimpleBindings (javax.script.SimpleBindings)1 Resource (org.apache.sling.api.resource.Resource)1 SyntheticResource (org.apache.sling.api.resource.SyntheticResource)1 SightlyException (org.apache.sling.scripting.sightly.SightlyException)1 ProviderOutcome (org.apache.sling.scripting.sightly.use.ProviderOutcome)1 UseProvider (org.apache.sling.scripting.sightly.use.UseProvider)1