FileDocCategorySizeDatePackage
Component.javaAPI DocExample16787Mon Jul 23 13:26:36 BST 2007org.apache.struts2.components

Component

public class Component extends Object
Base class to extend for UI components.

This class is a good extension point when building reuseable UI components.

Fields Summary
public static final String
COMPONENT_STACK
protected com.opensymphony.xwork2.util.ValueStack
stack
protected Map
parameters
protected String
id
protected org.apache.struts2.dispatcher.mapper.ActionMapper
actionMapper
Constructors Summary
public Component(com.opensymphony.xwork2.util.ValueStack stack)
Constructor.

param
stack OGNL value stack.


                
       
        this.stack = stack;
        this.parameters = new LinkedHashMap();
        getComponentStack().push(this);
    
Methods Summary
public voidaddAllParameters(java.util.Map params)
Add's all the given parameters to this componenets own parameters.

param
params the parameters to add.

        parameters.putAll(params);
    
public voidaddParameter(java.lang.String key, java.lang.Object value)
Add's the given key and value to this components own parameter.

If the provided key is null nothing happends. If the provided value is null any existing parameter with the given key name is removed.

param
key the key of the new parameter to add.
param
value the value assoicated with the key.

        if (key != null) {
            Map params = getParameters();

            if (value == null) {
                params.remove(key);
            } else {
                params.put(key, value);
            }
        }
    
public booleanaltSyntax()
Is the altSyntax enabled? [TRUE]

See struts.properties where the altSyntax flag is defined.

        return ContextUtil.isUseAltSyntax(stack.getContext());
    
public voidcopyParams(java.util.Map params)
Pushes this component's parameter Map as well as the component itself on to the stack and then copies the supplied parameters over. Because the component's parameter Map is pushed before the component itself, any key-value pair that can't be assigned to componet will be set in the parameters Map.

param
params the parameters to copy.

        stack.push(parameters);
        stack.push(this);
        try {
            for (Iterator iterator = params.entrySet().iterator(); iterator.hasNext();) {
                Map.Entry entry = (Map.Entry) iterator.next();
                String key = (String) entry.getKey();
                stack.setValue(key, entry.getValue());
            }
        } finally {
            stack.pop();
            stack.pop();
        }
    
protected java.lang.StringdetermineActionURL(java.lang.String action, java.lang.String namespace, java.lang.String method, javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res, java.util.Map parameters, java.lang.String scheme, boolean includeContext, boolean encodeResult)
Renders an action URL by consulting the {@link org.apache.struts2.dispatcher.mapper.ActionMapper}.

param
action the action
param
namespace the namespace
param
method the method
param
req HTTP request
param
res HTTP response
param
parameters parameters
param
scheme http or https
param
includeContext should the context path be included or not
param
encodeResult should the url be encoded
return
the action url.

        String finalAction = findString(action);
        String finalNamespace = determineNamespace(namespace, getStack(), req);
        ActionMapping mapping = new ActionMapping(finalAction, finalNamespace, method, parameters);
        String uri = actionMapper.getUriFromActionMapping(mapping);
        return UrlHelper.buildUrl(uri, req, res, parameters, scheme, includeContext, encodeResult);
    
protected java.lang.StringdetermineNamespace(java.lang.String namespace, com.opensymphony.xwork2.util.ValueStack stack, javax.servlet.http.HttpServletRequest req)
Determines the namespace of the current page being renderdd. Useful for Form, URL, and href generations.

param
namespace the namespace
param
stack OGNL value stack
param
req HTTP request
return
the namepsace of the current page being rendered, is never null.

        String result;

        if (namespace == null) {
            result = TagUtils.buildNamespace(actionMapper, stack, req);
        } else {
            result = findString(namespace);
        }

        if (result == null) {
            result = "";
        }

        return result;
    
public booleanend(java.io.Writer writer, java.lang.String body)
Callback for the end tag of this component. Should the body be evaluated again?

NOTE: will pop component stack.

param
writer the output writer.
param
body the rendered body.
return
true if the body should be evaluated again

        return end(writer, body, true);
    
protected booleanend(java.io.Writer writer, java.lang.String body, boolean popComponentStack)
Callback for the start tag of this component. Should the body be evaluated again?

NOTE: has a parameter to determine to pop the component stack.

param
writer the output writer.
param
body the rendered body.
param
popComponentStack should the component stack be popped?
return
true if the body should be evaluated again

        assert(body != null);

        try {
            writer.write(body);
        } catch (IOException e) {
            throw new StrutsException("IOError while writing the body: " + e.getMessage(), e);
        }
        if (popComponentStack) {
            popComponentStack();
        }
        return false;
    
protected org.apache.struts2.StrutsExceptionfieldError(java.lang.String field, java.lang.String errorMsg, java.lang.Exception e)
Constructs?a RuntimeException based on the given information.

A message is constructed and logged at ERROR level before being returned as a RuntimeException.

param
field field name used when throwing RuntimeException.
param
errorMsg error message used when throwing RuntimeException.
param
e the caused exception, can be null.
return
the constructed StrutsException.

        String msg = "tag '" + getComponentName() + "', field '" + field + ( id != null ?"', id '" + id:"") +
                ( parameters != null && parameters.containsKey("name")?"', name '" + parameters.get("name"):"") +
                "': " + errorMsg;
        throw new StrutsException(msg, e);
    
protected org.apache.struts2.components.ComponentfindAncestor(java.lang.Class clazz)
Finds the nearest ancestor of this component stack.

param
clazz the class to look for, or if assignable from.
return
the component if found, null if not.

        Stack componentStack = getComponentStack();
        int currPosition = componentStack.search(this);
        if (currPosition >= 0) {
            int start = componentStack.size() - currPosition - 1;

            //for (int i = componentStack.size() - 2; i >= 0; i--) {
            for (int i = start; i >=0; i--) {
                Component component = (Component) componentStack.get(i);
                if (clazz.isAssignableFrom(component.getClass()) && component != this) {
                    return component;
                }
            }
        }

        return null;
    
protected java.lang.StringfindString(java.lang.String expr)
Evaluates the OGNL stack to find a String value.

param
expr OGNL expression.
return
the String value found.

        return (String) findValue(expr, String.class);
    
protected java.lang.StringfindString(java.lang.String expr, java.lang.String field, java.lang.String errorMsg)
Evaluates the OGNL stack to find a String value.

If the given expression is null a error is logged and a RuntimeException is thrown constructed with a messaged based on the given field and errorMsg paramter.

param
expr OGNL expression.
param
field field name used when throwing RuntimeException.
param
errorMsg error message used when throwing RuntimeException.
return
the String value found.
throws
StrutsException is thrown in case of expression is null.

        if (expr == null) {
            throw fieldError(field, errorMsg, null);
        } else {
            return findString(expr);
        }
    
protected java.lang.ObjectfindValue(java.lang.String expr)
Finds a value from the OGNL stack based on the given expression. Will always evaluate expr against stack except when expr is null. If altsyntax (%{...}) is applied, simply strip it off.

param
expr the expression. Returns null if expr is null.
return
the value, null if not found.

        if (expr == null) {
            return null;
        }

        if (altSyntax()) {
            // does the expression start with %{ and end with }? if so, just cut it off!
            if (expr.startsWith("%{") && expr.endsWith("}")) {
                expr = expr.substring(2, expr.length() - 1);
            }
        }

        return getStack().findValue(expr);
    
protected java.lang.ObjectfindValue(java.lang.String expr, java.lang.String field, java.lang.String errorMsg)
Evaluates the OGNL stack to find an Object value.

Function just like findValue(String) except that if the given expression is null a error is logged and a RuntimeException is thrown constructed with a messaged based on the given field and errorMsg paramter.

param
expr OGNL expression.
param
field field name used when throwing RuntimeException.
param
errorMsg error message used when throwing RuntimeException.
return
the Object found, is never null.
throws
StrutsException is thrown in case of not found in the OGNL stack, or expression is null.

        if (expr == null) {
            throw fieldError(field, errorMsg, null);
        } else {
            Object value = null;
            Exception problem = null;
            try {
                value = findValue(expr);
            } catch (Exception e) {
                problem = e;
            }

            if (value == null) {
                throw fieldError(field, errorMsg, problem);
            }

            return value;
        }
    
protected java.lang.ObjectfindValue(java.lang.String expr, java.lang.Class toType)
Evaluates the OGNL stack to find an Object of the given type. Will evaluate expr the portion wrapped with altSyntax (%{...}) against stack when altSyntax is on, else the whole expr is evaluated against the stack.

This method only supports the altSyntax. So this should be set to true.

param
expr OGNL expression.
param
toType the type expected to find.
return
the Object found, or null if not found.

        if (altSyntax() && toType == String.class) {
            return TextParseUtil.translateVariables('%", expr, stack);
        } else {
            if (altSyntax()) {
                // does the expression start with %{ and end with }? if so, just cut it off!
                if (expr.startsWith("%{") && expr.endsWith("}")) {
                    expr = expr.substring(2, expr.length() - 1);
                }
            }

            return getStack().findValue(expr, toType);
        }
    
private java.lang.StringgetComponentName()
Get's the name of this component.

return
the name of this component.

        Class c = getClass();
        String name = c.getName();
        int dot = name.lastIndexOf('.");

        return name.substring(dot + 1).toLowerCase();
    
public java.util.StackgetComponentStack()
Get's the component stack of this component.

return
the component stack of this component, never null.

        Stack componentStack = (Stack) stack.getContext().get(COMPONENT_STACK);
        if (componentStack == null) {
            componentStack = new Stack();
            stack.getContext().put(COMPONENT_STACK, componentStack);
        }
        return componentStack;
    
public java.lang.StringgetId()
Get's the id for referencing element.

return
the id for referencing element.

        return id;
    
public java.util.MapgetParameters()
Get's the parameters.

return
the parameters. Is never null.

        return parameters;
    
public com.opensymphony.xwork2.util.ValueStackgetStack()
Get's the OGNL value stack assoicated with this component.

return
the OGNL value stack assoicated with this component.

        return stack;
    
protected voidpopComponentStack()
Pops the component stack.

        getComponentStack().pop();
    
public voidsetActionMapper(org.apache.struts2.dispatcher.mapper.ActionMapper mapper)

        this.actionMapper = mapper;
    
public voidsetId(java.lang.String id)

        if (id != null) {
            this.id = findString(id);
        }
    
public booleanstart(java.io.Writer writer)
Callback for the start tag of this component. Should the body be evaluated?

param
writer the output writer.
return
true if the body should be evaluated

        return true;
    
protected java.lang.StringtoString(java.lang.Throwable t)
Constructs a string representation of the given exception.

param
t the exception
return
the exception as a string.

        FastByteArrayOutputStream bout = new FastByteArrayOutputStream();
        PrintWriter wrt = new PrintWriter(bout);
        t.printStackTrace(wrt);
        wrt.close();

        return bout.toString();
    
public booleanusesBody()
Overwrite to set if body shold be used.

return
always false for this component.

        return false;