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);
}
}
}
}
}
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();
}
}
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());
}
}
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);
}
}
}
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);
}
Aggregations