Search in sources :

Example 1 with Scope

use of com.opensymphony.xwork2.inject.Scope in project struts by apache.

the class XmlConfigurationProvider method register.

public void register(ContainerBuilder containerBuilder, LocatableProperties props) throws ConfigurationException {
    LOG.trace("Parsing configuration file [{}]", configFileName);
    Map<String, Node> loadedBeans = new HashMap<>();
    for (Document doc : documents) {
        Element rootElement = doc.getDocumentElement();
        NodeList children = rootElement.getChildNodes();
        int childSize = children.getLength();
        for (int i = 0; i < childSize; i++) {
            Node childNode = children.item(i);
            if (childNode instanceof Element) {
                Element child = (Element) childNode;
                final String nodeName = child.getNodeName();
                if ("bean-selection".equals(nodeName)) {
                    String name = child.getAttribute("name");
                    String impl = child.getAttribute("class");
                    try {
                        Class classImpl = ClassLoaderUtil.loadClass(impl, getClass());
                        if (BeanSelectionProvider.class.isAssignableFrom(classImpl)) {
                            BeanSelectionProvider provider = (BeanSelectionProvider) classImpl.newInstance();
                            provider.register(containerBuilder, props);
                        } else {
                            throw new ConfigurationException("The bean-provider: name:" + name + " class:" + impl + " does not implement " + BeanSelectionProvider.class.getName(), childNode);
                        }
                    } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                        throw new ConfigurationException("Unable to load bean-provider: name:" + name + " class:" + impl, e, childNode);
                    }
                } else if ("bean".equals(nodeName)) {
                    String type = child.getAttribute("type");
                    String name = child.getAttribute("name");
                    String impl = child.getAttribute("class");
                    String onlyStatic = child.getAttribute("static");
                    String scopeStr = child.getAttribute("scope");
                    boolean optional = "true".equals(child.getAttribute("optional"));
                    Scope scope;
                    if ("prototype".equals(scopeStr)) {
                        scope = Scope.PROTOTYPE;
                    } else if ("request".equals(scopeStr)) {
                        scope = Scope.REQUEST;
                    } else if ("session".equals(scopeStr)) {
                        scope = Scope.SESSION;
                    } else if ("singleton".equals(scopeStr)) {
                        scope = Scope.SINGLETON;
                    } else if ("thread".equals(scopeStr)) {
                        scope = Scope.THREAD;
                    } else {
                        scope = Scope.SINGLETON;
                    }
                    if (StringUtils.isEmpty(name)) {
                        name = Container.DEFAULT_NAME;
                    }
                    try {
                        Class classImpl = ClassLoaderUtil.loadClass(impl, getClass());
                        Class classType = classImpl;
                        if (StringUtils.isNotEmpty(type)) {
                            classType = ClassLoaderUtil.loadClass(type, getClass());
                        }
                        if ("true".equals(onlyStatic)) {
                            // Force loading of class to detect no class def found exceptions
                            classImpl.getDeclaredClasses();
                            containerBuilder.injectStatics(classImpl);
                        } else {
                            if (containerBuilder.contains(classType, name)) {
                                Location loc = LocationUtils.getLocation(loadedBeans.get(classType.getName() + name));
                                if (throwExceptionOnDuplicateBeans) {
                                    throw new ConfigurationException("Bean type " + classType + " with the name " + name + " has already been loaded by " + loc, child);
                                }
                            }
                            // Force loading of class to detect no class def found exceptions
                            classImpl.getDeclaredConstructors();
                            LOG.debug("Loaded type: {} name: {} impl: {}", type, name, impl);
                            containerBuilder.factory(classType, name, new LocatableFactory(name, classType, classImpl, scope, childNode), scope);
                        }
                        loadedBeans.put(classType.getName() + name, child);
                    } catch (Throwable ex) {
                        if (!optional) {
                            throw new ConfigurationException("Unable to load bean: type:" + type + " class:" + impl, ex, childNode);
                        } else {
                            LOG.debug("Unable to load optional class: {}", impl);
                        }
                    }
                } else if ("constant".equals(nodeName)) {
                    String name = child.getAttribute("name");
                    String value = child.getAttribute("value");
                    if (valueSubstitutor != null) {
                        LOG.debug("Substituting value [{}] using [{}]", value, valueSubstitutor.getClass().getName());
                        value = valueSubstitutor.substitute(value);
                    }
                    props.setProperty(name, value, childNode);
                } else if (nodeName.equals("unknown-handler-stack")) {
                    List<UnknownHandlerConfig> unknownHandlerStack = new ArrayList<UnknownHandlerConfig>();
                    NodeList unknownHandlers = child.getElementsByTagName("unknown-handler-ref");
                    int unknownHandlersSize = unknownHandlers.getLength();
                    for (int k = 0; k < unknownHandlersSize; k++) {
                        Element unknownHandler = (Element) unknownHandlers.item(k);
                        Location location = LocationUtils.getLocation(unknownHandler);
                        unknownHandlerStack.add(new UnknownHandlerConfig(unknownHandler.getAttribute("name"), location));
                    }
                    if (!unknownHandlerStack.isEmpty())
                        configuration.setUnknownHandlerStack(unknownHandlerStack);
                }
            }
        }
    }
}
Also used : BeanSelectionProvider(com.opensymphony.xwork2.config.BeanSelectionProvider) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) LocatableFactory(com.opensymphony.xwork2.config.impl.LocatableFactory) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) UnknownHandlerConfig(com.opensymphony.xwork2.config.entities.UnknownHandlerConfig) Scope(com.opensymphony.xwork2.inject.Scope) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException) List(java.util.List) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) Location(com.opensymphony.xwork2.util.location.Location)

Example 2 with Scope

use of com.opensymphony.xwork2.inject.Scope in project struts by apache.

the class FreemarkerTemplateEngine method renderTemplate.

public void renderTemplate(TemplateRenderingContext templateContext) throws Exception {
    // get the various items required from the stack
    ValueStack stack = templateContext.getStack();
    ActionContext context = stack.getActionContext();
    ServletContext servletContext = context.getServletContext();
    HttpServletRequest req = context.getServletRequest();
    HttpServletResponse res = context.getServletResponse();
    // prepare freemarker
    Configuration config = freemarkerManager.getConfiguration(servletContext);
    // get the list of templates we can use
    List<Template> templates = templateContext.getTemplate().getPossibleTemplates(this);
    // find the right template
    freemarker.template.Template template = null;
    String templateName = null;
    Exception exception = null;
    for (Template t : templates) {
        templateName = getFinalTemplateName(t);
        try {
            // try to load, and if it works, stop at the first one
            template = config.getTemplate(templateName);
            break;
        } catch (ParseException e) {
            // template was found but was invalid - always report this.
            exception = e;
            break;
        } catch (IOException e) {
            // FileNotFoundException is anticipated - report the first IOException if no template found
            if (exception == null) {
                exception = e;
            }
        }
    }
    if (template == null) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not load the FreeMarker template named '{}':", templateContext.getTemplate().getName());
            for (Template t : templates) {
                LOG.error("Attempted: {}", getFinalTemplateName(t));
            }
            LOG.error("The TemplateLoader provided by the FreeMarker Configuration was a: {}", config.getTemplateLoader().getClass().getName());
        }
        if (exception != null) {
            throw exception;
        } else {
            return;
        }
    }
    LOG.debug("Rendering template: {}", templateName);
    ActionInvocation ai = ActionContext.getContext().getActionInvocation();
    Object action = (ai == null) ? null : ai.getAction();
    if (action == null) {
        LOG.warn("Rendering tag {} out of Action scope, accessing directly JSPs is not recommended! " + "Please read https://struts.apache.org/security/#never-expose-jsp-files-directly", templateName);
    }
    SimpleHash model = freemarkerManager.buildTemplateModel(stack, action, servletContext, req, res, config.getObjectWrapper());
    model.put("tag", templateContext.getTag());
    model.put("themeProperties", getThemeProps(templateContext.getTemplate()));
    // the BodyContent JSP writer doesn't like it when FM flushes automatically --
    // so let's just not do it (it will be flushed eventually anyway)
    Writer writer = templateContext.getWriter();
    final Writer wrapped = writer;
    writer = new Writer() {

        public void write(char[] cbuf, int off, int len) throws IOException {
            wrapped.write(cbuf, off, len);
        }

        public void flush() throws IOException {
        // nothing!
        }

        public void close() throws IOException {
            wrapped.close();
        }
    };
    LOG.debug("Push tag on top of the stack");
    stack.push(templateContext.getTag());
    try {
        template.process(model, writer);
    } finally {
        LOG.debug("Removes tag from top of the stack");
        stack.pop();
    }
}
Also used : ValueStack(com.opensymphony.xwork2.util.ValueStack) Configuration(freemarker.template.Configuration) ActionInvocation(com.opensymphony.xwork2.ActionInvocation) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ServletActionContext(org.apache.struts2.ServletActionContext) ActionContext(com.opensymphony.xwork2.ActionContext) IOException(java.io.IOException) ParseException(freemarker.core.ParseException) HttpServletRequest(javax.servlet.http.HttpServletRequest) SimpleHash(freemarker.template.SimpleHash) ServletContext(javax.servlet.ServletContext) ParseException(freemarker.core.ParseException) Writer(java.io.Writer)

Example 3 with Scope

use of com.opensymphony.xwork2.inject.Scope in project struts by apache.

the class AbstractBeanSelectionProvider method alias.

protected void alias(Class type, String key, ContainerBuilder builder, Properties props, Scope scope) {
    if (!builder.contains(type, Container.DEFAULT_NAME)) {
        String foundName = props.getProperty(key, DEFAULT_BEAN_NAME);
        if (builder.contains(type, foundName)) {
            LOG.trace("Choosing bean ({}) for ({})", foundName, type.getName());
            builder.alias(type, foundName, Container.DEFAULT_NAME);
        } else {
            try {
                Class cls = ClassLoaderUtil.loadClass(foundName, this.getClass());
                LOG.trace("Choosing bean ({}) for ({})", cls.getName(), type.getName());
                builder.factory(type, cls, scope);
            } catch (ClassNotFoundException ex) {
                // Perhaps a spring bean id, so we'll delegate to the object factory at runtime
                LOG.trace("Choosing bean ({}) for ({}) to be loaded from the ObjectFactory", foundName, type.getName());
                if (DEFAULT_BEAN_NAME.equals(foundName)) {
                // Probably an optional bean, will ignore
                } else {
                    if (ObjectFactory.class != type) {
                        builder.factory(type, new ObjectFactoryDelegateFactory(foundName, type), scope);
                    } else {
                        throw new ConfigurationException("Cannot locate the chosen ObjectFactory implementation: " + foundName);
                    }
                }
            }
        }
    } else {
        LOG.warn("Unable to alias bean type ({}), default mapping already assigned.", type.getName());
    }
}
Also used : ObjectFactory(com.opensymphony.xwork2.ObjectFactory) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException)

Example 4 with Scope

use of com.opensymphony.xwork2.inject.Scope in project struts by apache.

the class ServletUrlRenderer method renderUrl.

/**
 * {@inheritDoc}
 */
@Override
public void renderUrl(Writer writer, UrlProvider urlComponent) {
    String scheme = urlComponent.getHttpServletRequest().getScheme();
    if (urlComponent.getScheme() != null) {
        ValueStack vs = ActionContext.getContext().getValueStack();
        scheme = vs.findString(urlComponent.getScheme());
        if (scheme == null) {
            scheme = urlComponent.getScheme();
        }
    }
    String result;
    ActionInvocation ai = ActionContext.getContext().getActionInvocation();
    if (urlComponent.getValue() == null && urlComponent.getAction() != null) {
        result = urlComponent.determineActionURL(urlComponent.getAction(), urlComponent.getNamespace(), urlComponent.getMethod(), urlComponent.getHttpServletRequest(), urlComponent.getHttpServletResponse(), urlComponent.getParameters(), scheme, urlComponent.isIncludeContext(), urlComponent.isEncode(), urlComponent.isForceAddSchemeHostAndPort(), urlComponent.isEscapeAmp());
    } else if (urlComponent.getValue() == null && urlComponent.getAction() == null && ai != null) {
        // both are null, we will default to the current action
        final String action = ai.getProxy().getActionName();
        final String namespace = ai.getProxy().getNamespace();
        final String method = urlComponent.getMethod() != null || !ai.getProxy().isMethodSpecified() ? urlComponent.getMethod() : ai.getProxy().getMethod();
        result = urlComponent.determineActionURL(action, namespace, method, urlComponent.getHttpServletRequest(), urlComponent.getHttpServletResponse(), urlComponent.getParameters(), scheme, urlComponent.isIncludeContext(), urlComponent.isEncode(), urlComponent.isForceAddSchemeHostAndPort(), urlComponent.isEscapeAmp());
    } else {
        String _value = urlComponent.getValue();
        // prioritised before this [in start(Writer) method]
        if (_value != null && _value.indexOf('?') > 0) {
            _value = _value.substring(0, _value.indexOf('?'));
        }
        result = urlHelper.buildUrl(_value, urlComponent.getHttpServletRequest(), urlComponent.getHttpServletResponse(), urlComponent.getParameters(), scheme, urlComponent.isIncludeContext(), urlComponent.isEncode(), urlComponent.isForceAddSchemeHostAndPort(), urlComponent.isEscapeAmp());
    }
    String anchor = urlComponent.getAnchor();
    if (StringUtils.isNotEmpty(anchor)) {
        result += '#' + urlComponent.findString(anchor);
    }
    if (urlComponent.isPutInContext()) {
        String var = urlComponent.getVar();
        if (StringUtils.isNotEmpty(var)) {
            urlComponent.putInContext(result);
            // Note: Old comments stated that var was placed in the page scope, but interactive checks with EL on JSPs prove otherwise.
            // Add the var attribute to the request scope as well.
            urlComponent.getHttpServletRequest().setAttribute(var, result);
        } else {
            try {
                writer.write(result);
            } catch (IOException e) {
                throw new StrutsException("IOError: " + e.getMessage(), e);
            }
        }
    } else {
        try {
            writer.write(result);
        } catch (IOException e) {
            throw new StrutsException("IOError: " + e.getMessage(), e);
        }
    }
}
Also used : StrutsException(org.apache.struts2.StrutsException) ValueStack(com.opensymphony.xwork2.util.ValueStack) ActionInvocation(com.opensymphony.xwork2.ActionInvocation) IOException(java.io.IOException)

Example 5 with Scope

use of com.opensymphony.xwork2.inject.Scope in project struts by apache.

the class Set method end.

@Override
public boolean end(Writer writer, String body) {
    ValueStack stack = getStack();
    Object o;
    if (value == null) {
        if (body == null) {
            o = findValue("top");
        } else {
            o = body;
        }
    } else {
        o = findValue(value);
    }
    body = "";
    if ("application".equalsIgnoreCase(scope)) {
        stack.setValue("#application['" + getVar() + "']", o);
    } else if ("session".equalsIgnoreCase(scope)) {
        stack.setValue("#session['" + getVar() + "']", o);
    } else if ("request".equalsIgnoreCase(scope)) {
        stack.setValue("#request['" + getVar() + "']", o);
    } else if ("page".equalsIgnoreCase(scope)) {
        stack.setValue("#attr['" + getVar() + "']", o, false);
    } else {
        // Default scope is action.  Note: The action acope handling also adds the var to the page scope.
        stack.getContext().put(getVar(), o);
        stack.setValue("#attr['" + getVar() + "']", o, false);
    }
    return super.end(writer, body);
}
Also used : ValueStack(com.opensymphony.xwork2.util.ValueStack)

Aggregations

ValueStack (com.opensymphony.xwork2.util.ValueStack)6 ActionContext (com.opensymphony.xwork2.ActionContext)3 ActionInvocation (com.opensymphony.xwork2.ActionInvocation)3 ConfigurationException (com.opensymphony.xwork2.config.ConfigurationException)2 ActionConfig (com.opensymphony.xwork2.config.entities.ActionConfig)2 Scope (com.opensymphony.xwork2.inject.Scope)2 IOException (java.io.IOException)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 ServletActionContext (org.apache.struts2.ServletActionContext)2 StrutsException (org.apache.struts2.StrutsException)2 ObjectFactory (com.opensymphony.xwork2.ObjectFactory)1 Result (com.opensymphony.xwork2.Result)1 TestBean (com.opensymphony.xwork2.TestBean)1 BeanSelectionProvider (com.opensymphony.xwork2.config.BeanSelectionProvider)1 UnknownHandlerConfig (com.opensymphony.xwork2.config.entities.UnknownHandlerConfig)1 LocatableFactory (com.opensymphony.xwork2.config.impl.LocatableFactory)1 MockActionInvocation (com.opensymphony.xwork2.mock.MockActionInvocation)1 MockActionProxy (com.opensymphony.xwork2.mock.MockActionProxy)1 User (com.opensymphony.xwork2.test.User)1