Search in sources :

Example 6 with Location

use of com.opensymphony.xwork2.util.location.Location 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 7 with Location

use of com.opensymphony.xwork2.util.location.Location in project struts by apache.

the class XmlConfigurationProvider method addResultTypes.

protected void addResultTypes(PackageConfig.Builder packageContext, Element element) {
    NodeList resultTypeList = element.getElementsByTagName("result-type");
    for (int i = 0; i < resultTypeList.getLength(); i++) {
        Element resultTypeElement = (Element) resultTypeList.item(i);
        String name = resultTypeElement.getAttribute("name");
        String className = resultTypeElement.getAttribute("class");
        String def = resultTypeElement.getAttribute("default");
        Location loc = DomHelper.getLocationObject(resultTypeElement);
        Class clazz = verifyResultType(className, loc);
        if (clazz != null) {
            String paramName = null;
            try {
                paramName = (String) clazz.getField("DEFAULT_PARAM").get(null);
            } catch (Throwable t) {
                LOG.debug("The result type [{}] doesn't have a default param [DEFAULT_PARAM] defined!", className, t);
            }
            ResultTypeConfig.Builder resultType = new ResultTypeConfig.Builder(name, className).defaultResultParam(paramName).location(DomHelper.getLocationObject(resultTypeElement));
            Map<String, String> params = XmlHelper.getParams(resultTypeElement);
            if (!params.isEmpty()) {
                resultType.addParams(params);
            }
            packageContext.addResultTypeConfig(resultType.build());
            // set the default result type
            if (BooleanUtils.toBoolean(def)) {
                packageContext.defaultResultType(name);
            }
        }
    }
}
Also used : ResultTypeConfig(com.opensymphony.xwork2.config.entities.ResultTypeConfig) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) ContainerBuilder(com.opensymphony.xwork2.inject.ContainerBuilder) Location(com.opensymphony.xwork2.util.location.Location)

Example 8 with Location

use of com.opensymphony.xwork2.util.location.Location in project struts by apache.

the class XmlConfigurationProvider method verifyAction.

protected boolean verifyAction(String className, String name, Location loc) {
    if (className.contains("{")) {
        LOG.debug("Action class [{}] contains a wildcard replacement value, so it can't be verified", className);
        return true;
    }
    try {
        if (objectFactory.isNoArgConstructorRequired()) {
            Class clazz = objectFactory.getClassInstance(className);
            if (!Modifier.isPublic(clazz.getModifiers())) {
                throw new ConfigurationException("Action class [" + className + "] is not public", loc);
            }
            clazz.getConstructor(new Class[] {});
        }
    } catch (ClassNotFoundException e) {
        LOG.debug("Class not found for action [{}]", className, e);
        throw new ConfigurationException("Action class [" + className + "] not found", loc);
    } catch (NoSuchMethodException e) {
        LOG.debug("No constructor found for action [{}]", className, e);
        throw new ConfigurationException("Action class [" + className + "] does not have a public no-arg constructor", e, loc);
    } catch (RuntimeException ex) {
        // Probably not a big deal, like request or session-scoped Spring beans that need a real request
        LOG.info("Unable to verify action class [{}] exists at initialization", className);
        LOG.debug("Action verification cause", ex);
    } catch (Exception ex) {
        // Default to failing fast
        LOG.debug("Unable to verify action class [{}]", className, ex);
        throw new ConfigurationException(ex, loc);
    }
    return true;
}
Also used : ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException) StrutsException(org.apache.struts2.StrutsException) IOException(java.io.IOException)

Example 9 with Location

use of com.opensymphony.xwork2.util.location.Location in project struts by apache.

the class XmlConfigurationProvider method loadInterceptors.

protected void loadInterceptors(PackageConfig.Builder context, Element element) throws ConfigurationException {
    NodeList interceptorList = element.getElementsByTagName("interceptor");
    for (int i = 0; i < interceptorList.getLength(); i++) {
        Element interceptorElement = (Element) interceptorList.item(i);
        String name = interceptorElement.getAttribute("name");
        String className = interceptorElement.getAttribute("class");
        Map<String, String> params = XmlHelper.getParams(interceptorElement);
        InterceptorConfig config = new InterceptorConfig.Builder(name, className).addParams(params).location(DomHelper.getLocationObject(interceptorElement)).build();
        context.addInterceptorConfig(config);
    }
    loadInterceptorStacks(element, context);
}
Also used : InterceptorConfig(com.opensymphony.xwork2.config.entities.InterceptorConfig) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element)

Example 10 with Location

use of com.opensymphony.xwork2.util.location.Location in project struts by apache.

the class DomHelper method parse.

/**
 * Creates a W3C Document that remembers the location of each element in
 * the source file. The location of element nodes can then be retrieved
 * using the {@link #getLocationObject(Element)} method.
 *
 * @param inputSource the inputSource to read the document from
 * @param dtdMappings a map of DTD names and public ids
 *
 * @return the W3C Document
 */
public static Document parse(InputSource inputSource, Map<String, String> dtdMappings) {
    SAXParserFactory factory = null;
    String parserProp = System.getProperty("xwork.saxParserFactory");
    if (parserProp != null) {
        try {
            ObjectFactory objectFactory = ActionContext.getContext().getContainer().getInstance(ObjectFactory.class);
            Class clazz = objectFactory.getClassInstance(parserProp);
            factory = (SAXParserFactory) clazz.newInstance();
        } catch (Exception e) {
            LOG.error("Unable to load saxParserFactory set by system property 'xwork.saxParserFactory': {}", parserProp, e);
        }
    }
    if (factory == null) {
        factory = SAXParserFactory.newInstance();
    }
    factory.setValidating((dtdMappings != null));
    factory.setNamespaceAware(true);
    SAXParser parser;
    try {
        parser = factory.newSAXParser();
    } catch (Exception ex) {
        throw new StrutsException("Unable to create SAX parser", ex);
    }
    DOMBuilder builder = new DOMBuilder();
    // Enhance the sax stream with location information
    ContentHandler locationHandler = new LocationAttributes.Pipe(builder);
    try {
        parser.parse(inputSource, new StartHandler(locationHandler, dtdMappings));
    } catch (Exception ex) {
        throw new StrutsException(ex);
    }
    return builder.getDocument();
}
Also used : StrutsException(org.apache.struts2.StrutsException) ObjectFactory(com.opensymphony.xwork2.ObjectFactory) SAXParser(javax.xml.parsers.SAXParser) StrutsException(org.apache.struts2.StrutsException) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

ResultConfig (com.opensymphony.xwork2.config.entities.ResultConfig)32 ServletContext (javax.servlet.ServletContext)22 PackageConfig (com.opensymphony.xwork2.config.entities.PackageConfig)21 HashSet (java.util.HashSet)15 ConfigurationException (com.opensymphony.xwork2.config.ConfigurationException)11 ActionContext (com.opensymphony.xwork2.ActionContext)10 ValueStack (com.opensymphony.xwork2.util.ValueStack)10 HashMap (java.util.HashMap)9 ActionInvocation (com.opensymphony.xwork2.ActionInvocation)8 ActionConfig (com.opensymphony.xwork2.config.entities.ActionConfig)8 ServletActionContext (org.apache.struts2.ServletActionContext)8 ResultTypeConfig (com.opensymphony.xwork2.config.entities.ResultTypeConfig)7 Location (com.opensymphony.xwork2.util.location.Location)7 ArrayList (java.util.ArrayList)7 NoAnnotationAction (org.apache.struts2.convention.actions.NoAnnotationAction)7 ClassLevelResultPathAction (org.apache.struts2.convention.actions.resultpath.ClassLevelResultPathAction)6 Action (org.apache.struts2.convention.annotation.Action)6 NodeList (org.w3c.dom.NodeList)6 ActionProxy (com.opensymphony.xwork2.ActionProxy)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5