Class AbstractWComponent

  • All Implemented Interfaces:
    WComponent, WebComponent, Serializable
    Direct Known Subclasses:
    AbstractContainer, AbstractWComponent.WComponentRef, AbstractWFieldIndicator, DefaultWComponent, FatalErrorPage, WAjaxControl, WAudio, WBeanComponent, WCollapsibleToggle, WComponentGroup, WContent, WDialog, WHorizontalRule, WImageEditor, WInternalLink, WMessageBox, WPopup, WSelectToggle, WSeparator, WSkipLinks, WSubordinateControl, WSuggestions, WTimeoutWarning, WValidationErrors, WVideo, WWindow

    public abstract class AbstractWComponent
    extends Object
    implements WComponent

    AbstractWComponent is the parent class of all standard WComponents.

    WComponent trees (UIs) are intended to be shared between sessions in order to reduce their memory footprint. To archive this a class called UIContext has been introduced to store WComponent information specific to an individual session. Each session has its own UIContext instance which is passed to the component tree whenever it needs to handle events and paint.

    The attributes of a WComponent have an initial shared value that can be overridden on a per session basis. We call this a private attribute value. The methods that manipulate a components attributes will normally have two method signatures. One will manipulate the shared value and does not require a UIContext to be passed. The other will manipulate the private session based value and will include a UIContext as the first parameter. The methods that access a components attributes only require one method signature. Accessor methods will include a UIContext as their first parameter. They will return the private attribute value if one exists else the shared value.

    The shared/private concept makes WComponents very flexible but has the dangerous ramification that it is easy to accidentally dynamically share attribute values and even whole chunks of UI with everyone. To reduce this risk, it is possible to lock a component and all its children. When the lock is set, it becomes impossible to update a shared value. Trying to update a shared value will result in a runtime exception. The intention is that shared component trees will be held in a registry. Adding a component tree to a registry would be a sensible time to lock it.

    Since:
    1.0.0
    Author:
    James Gifford, Martin Shevchenko
    See Also:
    Serialized Form
    • Constructor Detail

      • AbstractWComponent

        public AbstractWComponent()
    • Method Detail

      • getInternalId

        public String getInternalId()
        Specified by:
        getInternalId in interface WComponent
        Returns:
        the internal identifier of this Component based on its position in the component tree.
      • getIdName

        public String getIdName()
        Specified by:
        getIdName in interface WComponent
        Returns:
        the component identifier of this Component (if any).
      • setIdName

        public void setIdName​(String idName)
        Set the component identifier of this Component (if any). Component identifiers must obey the following syntax restrictions:
        • Must not be a zero-length String.
        • First character must be a letter.
        • Underscore ('_') as the first character is reserved by the framework.
        • Subsequent characters must be a letter, a digit or an underscore ('_').

        The specified identifier must be unique among all the components that are descendents of the nearest ancestor Component that is an active NamingContextable.

        Specified by:
        setIdName in interface WComponent
        Parameters:
        idName - the id name
      • getId

        public String getId()
        Return an identifier for this component, generating one if necessary.

        The implementation must follow these steps in determining the Id:

        If has id name set: If no id name set:
        • If the component's parent is null, then let the ID be WComponent.DEFAULT_NO_ID.
        • If has a parent, then let the ID prefix be parent.getId() or parent.getNamingContextID() + WComponent.ID_CONTEXT_SEPERATOR if the parent is an active NamingContext. Then let the ID be prefix + generate unique id.
        Specified by:
        getId in interface WComponent
        Specified by:
        getId in interface WebComponent
        Returns:
        the id for this WComponent in the current context.
      • getScratchMap

        protected Map getScratchMap()

        Retrieves a short-lived map which can be used to cache data during request processing. This map will be guaranteed to be cleared at the end of processing a request, but may also be cleared during request processing. Do not rely on the contents of this map to exist at any time.

        This method will return null if called outside of request processing.

        Returns:
        a map which can be used to temporarily cache data, or null
      • serviceRequest

        public final void serviceRequest​(Request request)

        This is the main entry point during request handling. Only the "top-level" component will have this method called - other components will have WComponent.handleRequest(Request) called. For efficiency, only visible components are asked to handle the request.

        The basic workflow is:
        1. Collate the list of visible components, in depth-first order. Depth-first traversal is used to ensure that when a parent component's handleRequest method is called, all of its children have already handled the request and are in a stable state.
        2. Call handle request for each visible component found, in order.
        3. At this point, all the components should be in a stable state, and any runnables added using WComponent.invokeLater(Runnable) will be invoked. These runnables can include e.g. Actions on buttons.

        Applications should not call this method directly.

        Specified by:
        serviceRequest in interface WComponent
        Specified by:
        serviceRequest in interface WebComponent
        Parameters:
        request - the request being responded to.
      • invokeLaters

        protected void invokeLaters()
        The framework calls this method at the end of the serviceRequest method. The default implementation is that only a root wcomponent actually runs them.
      • invokeLater

        public void invokeLater​(Runnable runnable)

        Adds a runnable that will be processed after the completion of the current serviceRequest method. This method is intended to be called from subcomponents' handleRequest methods, to permit processing to continue once the entire WComponent tree has been updated from the incoming HTTP request.

        If this method is invoked more than once, each Runnable will be invoked in turn.

        Specified by:
        invokeLater in interface WComponent
        Parameters:
        runnable - the Runnable to execute after the serviceRequest method has otherwise completed.
      • handleRequest

        public void handleRequest​(Request request)
        Subclasses should override this method in order to provide specific request handling logic. For example, a text field may set its value to the value of a request parameter.
        Specified by:
        handleRequest in interface WComponent
        Parameters:
        request - the request being responded to.
      • forward

        public void forward​(String url)
        Applications can call this method during event handling to indicate that we should forward to a given url. The event handling will complete and the forwarding will take place before painting.
        Specified by:
        forward in interface WComponent
        Parameters:
        url - the URL to forward to
      • getTemplateMarkUp

        @Deprecated
        public String getTemplateMarkUp()
        Deprecated.
        Use WTemplate instead
        Retrieves Velocity mark-up which has been explicitly associated with this component.
        Returns:
        the Velocity mark-up, or null if no mark-up has been set explicitly.
      • getTemplate

        @Deprecated
        public String getTemplate()
        Deprecated.
        Use WTemplate instead
        Retrieves the resource url of the Velocity template associated with this component.
        Returns:
        the location of the Velocity template resource, or null if there is no template.
      • preparePaintComponent

        protected void preparePaintComponent​(Request request)
        Subclasses may override this method to place the component in the correct state before it is painted. When overriding this method, it is good practice to also call the superclass implementation.
        Parameters:
        request - the request being responded to.
      • isDebugStructure

        protected boolean isDebugStructure()
        Indicates whether structural debugging info should be output for this component.
        Returns:
        false debug structure is never enabled for this component.
      • beforePaint

        protected void beforePaint​(RenderContext renderContext)
        Subclasses may override this method to output content before the component has been painted. When overriding this method, it is good practice to call the superclass implementation after emitting any additional content.
        Parameters:
        renderContext - the context to render to.
      • afterPaint

        protected void afterPaint​(RenderContext renderContext)
        Subclasses may override this method to output content after the component has been painted. When overriding this method, it is good practice to call the superclass implementation before emitting any additional content.
        Parameters:
        renderContext - the context to render to.
      • paintComponent

        protected void paintComponent​(RenderContext renderContext)
        This is where most of the painting work is normally done. If a layout has been supplied either directly or by supplying a velocity template, then painting is delegated to the layout manager. If there is no layout, the default behaviour is to paint the child components in sequence.
        Parameters:
        renderContext - the context to render to.
      • validate

        public void validate​(List<Diagnostic> diags)

        The validate method should be called by an Action, or ValidatingAction at points in the application lifecycle where it makes sense to perform validation.

        No side effect of displaying error markers implied by this. This is a pure "function" except that it stores the results in the diags list.

        It is the responsibility of the validatable component to call any of its children that may also require validation.

        Specified by:
        validate in interface WComponent
        Parameters:
        diags - the list into which any validation diagnostics are added.
      • validateComponent

        protected void validateComponent​(List<Diagnostic> diags)
        Subclasses may override to provide validation.
        Parameters:
        diags - the list into which any validation diagnostics are added.
      • createErrorDiagnostic

        protected Diagnostic createErrorDiagnostic​(String message,
                                                   Serializable... args)
        Create and return an error diagnostic associated to this WComponent.
        Parameters:
        message - the error message, using MessageFormat syntax.
        args - optional arguments for the message.
        Returns:
        an error diagnostic for this component.
      • createErrorDiagnostic

        protected Diagnostic createErrorDiagnostic​(WComponent source,
                                                   String message,
                                                   Serializable... args)
        Create and return an error diagnostic associated to the given error source.
        Parameters:
        source - the source of the error.
        message - the error message, using MessageFormat syntax.
        args - optional arguments for the message.
        Returns:
        an error diagnostic for this component.
      • showErrorIndicators

        public void showErrorIndicators​(List<Diagnostic> diags)

        This does not affect the diag list at all. The ValidatableComponent should visually mark any fields or blocks that have errors in the given diag list.

        It is the responsibility of the validatable component to call any of its children that may also be validatable.

        Specified by:
        showErrorIndicators in interface WComponent
        Parameters:
        diags - the list of current validation diagnostics.
      • showErrorIndicatorsForComponent

        protected void showErrorIndicatorsForComponent​(List<Diagnostic> diags)

        This does not affect the diag list at all. The ValidatableComponent should visually mark any fields or blocks that have errors in the given diag list.

        Parameters:
        diags - the list of diagnostics for this component.
      • showWarningIndicators

        public void showWarningIndicators​(List<Diagnostic> diags)

        This does not affect the diag list at all. The ValidatableComponent should visually mark any fields or blocks that have warnings in the given diag list.

        It is the responsibility of the validatable component to call any of its children that may also be validatable. The default implemntation does nothing.

        Specified by:
        showWarningIndicators in interface WComponent
        Parameters:
        diags - the list of diagnostics for this component.
      • showWarningIndicatorsForComponent

        protected void showWarningIndicatorsForComponent​(List<Diagnostic> diags)

        This does not affect the diag list at all. The ValidatableComponent should visually mark any fields or blocks that have warnings in the given diag list.

        Parameters:
        diags - the list of diagnostics for this component.
      • setLocked

        public void setLocked​(boolean lock)

        The shared attributes of a component (and all its children) can be locked, preventing users/developers from making further updates. However, attribute values can still be updated on a per session basis.

        This method should normally never be called from application code.

        Specified by:
        setLocked in interface WComponent
        Parameters:
        lock - true to lock the component, false to unlock
      • isLocked

        public boolean isLocked()
        Indicates whether this component is locked. If the component is locked, shared attribute values can not be updated.
        Specified by:
        isLocked in interface WComponent
        Returns:
        true if the component is locked, false if not.
      • isInitialised

        public boolean isInitialised()
        Optionally use this flag to test if some arbitrary initialisation has been performed by this component.
        Specified by:
        isInitialised in interface WComponent
        Returns:
        true if the component has been marked as initialised, false otherwise.
        See Also:
        WComponent.setInitialised(boolean)
      • setInitialised

        public void setInitialised​(boolean flag)
        Optionally use this flag to store whether some arbitrary initialisation has been performed by this component on the given session. This should normally only be used after the UI has been constructed.
        Specified by:
        setInitialised in interface WComponent
        Parameters:
        flag - the initialised flag.
      • isValidate

        public boolean isValidate()
        Indicates whether this component should take part in validation processing.
        Specified by:
        isValidate in interface WComponent
        Returns:
        true if this component is validateable, false if not.
      • setValidate

        public void setValidate​(boolean flag)
        Sets whether this component should take part in validation processing.
        Specified by:
        setValidate in interface WComponent
        Parameters:
        flag - true if this component should be validated, false if not.
      • isVisible

        public boolean isVisible()
        Indicates whether this component is visible. Invisible components are normally excluded from all event handling and painting.
        Specified by:
        isVisible in interface WComponent
        Returns:
        true if this component is visible, false if invisible.
      • setVisible

        public void setVisible​(boolean visible)
        Sets the visibility of this component. Invisible components are normally excluded from all event handling and painting.
        Specified by:
        setVisible in interface WComponent
        Parameters:
        visible - true to set this component visible, false for invisible.
      • isHidden

        public boolean isHidden()
        Indicates whether this component is hidden. Hidden components take part in event handling and painting, but are not visible on the client.
        Specified by:
        isHidden in interface WComponent
        Returns:
        true if this component is hidden, false if displayed.
      • setHidden

        public void setHidden​(boolean hidden)

        Sets the client visibility of this component. Hidden components take part in event handling and painting, but are not palpable on the client.

        Parameters:
        hidden - true for hidden, false for displayed.
      • setTrackingEnabled

        public void setTrackingEnabled​(boolean track)
        Sets the flag if tracking is enabled for this component. This flag is used by WComponent.isTracking().
        Specified by:
        setTrackingEnabled in interface WComponent
        Parameters:
        track - set true if tracking is enabled for this component.
      • isTrackingEnabled

        public boolean isTrackingEnabled()
        Returns true if tracking is enabled for this component.This flag is used by WComponent.isTracking().
        Specified by:
        isTrackingEnabled in interface WComponent
        Returns:
        true if tracking is enabled for this component.
      • isTracking

        public boolean isTracking()
        Returns true if this component should be tracked.

        A component will only be tracked if WComponent.setTrackingEnabled(boolean) is set true and the component has an id set via WComponent.setIdName(String). If the id has not been set, then the id used for tracking will be dynamic and constantly changing which makes it useless for analysing.

        Specified by:
        isTracking in interface WComponent
        Returns:
        true if this component should be tracked.
      • setFlag

        protected void setFlag​(int mask,
                               boolean flag)
        Sets or clears one or more component flags in the component model for the given context..
        Parameters:
        mask - the bit mask for the flags to set/clear.
        flag - true to set the flag(s), false to clear.
      • isFlagSet

        protected boolean isFlagSet​(int mask)
        Indicates whether any of the given flags are set. This is normally used to only check a single flag at a time.
        Parameters:
        mask - the bit mask for the flags to check.
        Returns:
        true if any flags are set, false otherwise.
      • hasTabIndex

        @Deprecated
        public boolean hasTabIndex()
        Deprecated.
        1.4 causes a11y issues, no replacement.
        Indicates whether this component has a tab index.
        Specified by:
        hasTabIndex in interface WComponent
        Returns:
        false - For the moment, turn off the tab index feature and see what happens.
      • getTabIndex

        @Deprecated
        public int getTabIndex()
        Deprecated.
        1.4 causes a11y issues, no replacement.
        Specified by:
        getTabIndex in interface WComponent
        Returns:
        the tab index for this component.
      • getLabel

        public WLabel getLabel()
        Specified by:
        getLabel in interface WComponent
        Returns:
        the label associated with this component, or null if there is no label.
      • setFocussed

        public void setFocussed()
        Requests that this component be given keyboard focus when rendered.
        Specified by:
        setFocussed in interface WComponent
      • newComponentModel

        protected ComponentModel newComponentModel()
        Creates a new model appropriate for the type of component. Subclasses can override, and should narrow the return type.
        Returns:
        a new ComponentModel.
      • initialiseComponentModel

        protected void initialiseComponentModel()

        Performs initialisation that is required on this components model, and potentially its children. Subclasses can override.

        Note that the user's component model will automatically be populated from the shared model.

      • hasNoComponentModel

        protected boolean hasNoComponentModel​(UIContext uic)
        Check if this component has a model on this user's context.
        Parameters:
        uic - the user context
        Returns:
        true if has no component model
      • getComponentModel

        protected ComponentModel getComponentModel()
        Returns the effective component model for this component. Subclass may override this method to narrow the return type to their specific model type.
        Returns:
        the effective component model
      • getDefaultModel

        protected ComponentModel getDefaultModel()
        Returns the shared component model for this component. Subclass may override this method to narrow the return type to their specific model type.
        Returns:
        the shared component model
      • getOrCreateComponentModel

        protected ComponentModel getOrCreateComponentModel()
        Retrieves the model for this component so that it can be modified. If this method is called during request processing, and a session specific model does not yet exist, then a new model is created. Subclasses may override this method to narrow the return type to their specific model type.
        Returns:
        the model for this component
      • reset

        public void reset()

        Resets this component and its children to their initial state for the given user context / session.

        NOTE: The exception to this rule is if this component has been dynamically added to the UI, then the parent component will differ from the initial state.

        Specified by:
        reset in interface WComponent
      • removeComponentModel

        protected void removeComponentModel()
        Reset this component to its initial state.
      • tidyUpUIContextForTree

        public void tidyUpUIContextForTree()
        This method removes unnecessary component models from the user session for this component and all its descendants. A component model is deemed unnecessary when it has the same state as the component's default component model.
        Specified by:
        tidyUpUIContextForTree in interface WComponent
      • tidyUpUIContext

        protected void tidyUpUIContext()
        Removes the user-specific component model if this component is in its default state.
      • isDefaultState

        public boolean isDefaultState()

        WComponents must implement this method in order to protect any session based information they store from being incorrectly removed by the WComponent.tidyUpUIContextForTree() method.

        It is possible you can write a more exact check for the default state here than the method on the component model itself can provide.

        Specified by:
        isDefaultState in interface WComponent
        Returns:
        true if the component is in it's default state, otherwise false.
      • assertAddSupported

        protected void assertAddSupported​(WComponent componentToAdd)
        Some components may wish to throw an Exception if certain types of components can not be added. This implementation does nothing, and is here so that e.g. sub-classes do not have to override multiple add methods.
        Parameters:
        componentToAdd - the component being added.
      • addNotify

        protected void addNotify()
        Notifies this component that it now has a parent component. Subclasses can override this to perform any additional processing required. The default implementation does nothing.
      • removeNotify

        protected void removeNotify()
        Notifies this component that it no longer has a parent component. Subclasses can override this to perform any additional processing required. The default implementation does nothing.
      • getTag

        @Deprecated
        public String getTag()
        Deprecated.
        Use WTemplate instead
        Retrieves the tag used to identify this component in a Velocity template.
        Specified by:
        getTag in interface WComponent
        Returns:
        the component's tag.
      • setTag

        @Deprecated
        public void setTag​(String tag)
        Deprecated.
        Use WTemplate instead
        Sets the tag used to identify this component in a Velocity template.
        Specified by:
        setTag in interface WComponent
        Parameters:
        tag - the component's tag to set.
      • getEnvironment

        public Environment getEnvironment()
        Retrieves the environment for the current session. If there is no environment for the session, a dummy environment is returned.
        Specified by:
        getEnvironment in interface WComponent
        Returns:
        the environment for the user session.
      • setEnvironment

        public void setEnvironment​(Environment environment)
        Sets the environment.
        Specified by:
        setEnvironment in interface WComponent
        Parameters:
        environment - the environment to set.
      • getHeaders

        public Headers getHeaders()
        Retrieves the headers.
        Specified by:
        getHeaders in interface WComponent
        Returns:
        the headers.
      • getBaseUrl

        public String getBaseUrl()
        Exposes the base URL for this environment. Renderers can call this method to construct URIs to sub-resources. The baseurl is ultimately derived from com.github.bordertech.wcomponents.Environment
        Specified by:
        getBaseUrl in interface WComponent
        Returns:
        the base URL
      • setAttribute

        public void setAttribute​(String key,
                                 Serializable value)
        Associates an arbitrary attribute with this component.
        Specified by:
        setAttribute in interface WComponent
        Parameters:
        key - the attribute key.
        value - the attribute value.
      • getAttribute

        public Serializable getAttribute​(String key)
        Retrieves an arbitrary attribute which has been previously associated with this component.
        Specified by:
        getAttribute in interface WComponent
        Parameters:
        key - the attribute key.
        Returns:
        value the attribute value if set, otherwise null.
      • removeAttribute

        public Serializable removeAttribute​(String key)
        Removes an arbitrary attribute.
        Specified by:
        removeAttribute in interface WComponent
        Parameters:
        key - the attribute key.
        Returns:
        the value for the attribute which was removed, or null if no attribute was found with the given key.
      • setToolTip

        public void setToolTip​(String text,
                               Serializable... args)
        Sets the component's tool tip. Note that not all components support displaying tool tips.
        Specified by:
        setToolTip in interface WComponent
        Parameters:
        text - the tool tip text, using MessageFormat syntax.
        args - optional arguments for the message format string.
      • getToolTip

        public String getToolTip()
        Retrieves the component's tool tip.
        Specified by:
        getToolTip in interface WComponent
        Returns:
        the component's tool tip.
      • setAccessibleText

        public void setAccessibleText​(String text,
                                      Serializable... args)
        Sets the text used by screen readers to describe the component.
        Specified by:
        setAccessibleText in interface WComponent
        Parameters:
        text - the screen reader text, using MessageFormat syntax.
        args - optional arguments for the message format string.
      • getAccessibleText

        public String getAccessibleText()
        Retrieves the text used by screen readers to describe the component.
        Specified by:
        getAccessibleText in interface WComponent
        Returns:
        the screen reader text.
      • setHtmlClass

        public void setHtmlClass​(String text)
        Sets additional HTML class name string for this component. Multiple HTML class names may be added to an instance of a component using a space separated string. Some values in the HTML class name attribute are determined in the theme and are used for core functionality and styling.
        Specified by:
        setHtmlClass in interface WComponent
        Parameters:
        text - the HTML class attribute's value to add to the component
      • setHtmlClass

        public void setHtmlClass​(HtmlClassProperties className)
        Sets additional HTML class name for this component from a set of preset values.
        Specified by:
        setHtmlClass in interface WComponent
        Parameters:
        className - the HTML class attribute's value to add to the component derived from the utility enum
      • addHtmlClass

        public void addHtmlClass​(String className)
        Append value to the HTML class name for this component.
        Specified by:
        addHtmlClass in interface WComponent
        Parameters:
        className - the HTML class attribute's value to add to the component
      • addHtmlClass

        public void addHtmlClass​(HtmlClassProperties className)
        Append a value to the HTML class name for this component from a set of preset values.
        Specified by:
        addHtmlClass in interface WComponent
        Parameters:
        className - the HTML class attribute's value to add to the component derived from the utility enum
      • getHtmlClass

        public String getHtmlClass()
        Returns the HTML class name string to apply to a component. Some values in the HTML class name attribute are determined in the theme and are used for core functionality and styling. This method will only return class name values which are added in the application, it has no knowledge of theme's class names.
        Specified by:
        getHtmlClass in interface WComponent
        Returns:
        the value to add to the HTML class attribute of the output component
      • getHtmlClasses

        public Set getHtmlClasses()
        Specified by:
        getHtmlClasses in interface WComponent
        Returns:
        the HTML class list HashSet for this component
      • removeHtmlClass

        public void removeHtmlClass​(String className)
        Remove a value from the set of HTML class name values added to the current component.
        Specified by:
        removeHtmlClass in interface WComponent
        Parameters:
        className - the value to remove
      • removeHtmlClass

        public void removeHtmlClass​(HtmlClassProperties className)
        Remove a value from the set of HTML class name values added to the current component.
        Specified by:
        removeHtmlClass in interface WComponent
        Parameters:
        className - the property representing the value to remove
      • toString

        public String toString()
        Creates a String representation of this component; usually for debugging purposes.
        Overrides:
        toString in class Object
        Returns:
        a String representation of this component.
      • writeReplace

        protected Object writeReplace()
                               throws ObjectStreamException
        Implement writeReplace so that on serialization, WComponents that are registered in the UIRegistry write a reference to the registered component rather than the component itself. This ensures that, on deserialization, only one copy of the registered component will be present in the VM.
        Returns:
        the WComponent instance that is registered with the registry.
        Throws:
        ObjectStreamException - never, but Serializable requires this method signature to declare it.
        See Also:
        Serializable
      • replaceWComponent

        public static Object replaceWComponent​(AbstractWComponent component)
        A Utility method which returns the (replaced) serialized form of a WComponent. This method is only exposed for internal instrumentation (by UicStats).
        Parameters:
        component - the component to serialize.
        Returns:
        the serialized form of the component.