idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
18,800
public static String doubleEncodeBrackets ( final String input ) { if ( input == null || input . length ( ) == 0 ) { // For performance reasons don't use Util.empty return input ; } return DOUBLE_ENCODE_BRACKETS . translate ( input ) ; }
Double encode open or closed brackets in the input String .
62
11
18,801
public static String doubleDecodeBrackets ( final String input ) { if ( input == null || input . length ( ) == 0 ) { // For performance reasons don't use Util.empty return input ; } return DOUBLE_DECODE_BRACKETS . translate ( input ) ; }
Decode double encoded open or closed brackets in the input String .
62
13
18,802
public static void appendGetParamForJavascript ( final String key , final String value , final StringBuffer vars , final boolean existingVars ) { vars . append ( existingVars ? ' ' : ' ' ) ; vars . append ( key ) . append ( ' ' ) . append ( WebUtilities . escapeForUrl ( value ) ) ; }
This is a slightly different version of appendGetParam that doesn t encode the ampersand seperator . It is intended to be used in urls that are generated for javascript functions .
76
38
18,803
public static String generateRandom ( ) { long next = ATOMIC_COUNT . incrementAndGet ( ) ; StringBuffer random = new StringBuffer ( ) ; random . append ( new Date ( ) . getTime ( ) ) . append ( ' ' ) . append ( next ) ; return random . toString ( ) ; }
Generates a random String . Can be useful for creating unique URLs by adding the String as a query parameter to the URL .
69
25
18,804
public static boolean isAncestor ( final WComponent component1 , final WComponent component2 ) { for ( WComponent parent = component2 . getParent ( ) ; parent != null ; parent = parent . getParent ( ) ) { if ( parent == component1 ) { return true ; } } return false ; }
Indicates whether a component is an ancestor of another .
66
11
18,805
public static UIContext getContextForComponent ( final WComponent component ) { // Start with the current Context UIContext result = UIContextHolder . getCurrent ( ) ; // Go through the contexts until we find the component while ( result instanceof SubUIContext && ! ( ( SubUIContext ) result ) . isInContext ( component ) ) { result = ( ( SubUIContext ) result ) . getBacking ( ) ; } return result ; }
Returns the context for this component . The component may not be in the current context .
106
17
18,806
public static ComponentWithContext getComponentById ( final String id , final boolean visibleOnly ) { UIContext uic = UIContextHolder . getCurrent ( ) ; WComponent root = uic . getUI ( ) ; ComponentWithContext comp = TreeUtil . getComponentWithContextForId ( root , id , visibleOnly ) ; return comp ; }
Finds a component by its id .
78
8
18,807
public static UIContext findClosestContext ( final String id ) { UIContext uic = UIContextHolder . getCurrent ( ) ; WComponent root = uic . getUI ( ) ; UIContext closest = TreeUtil . getClosestContextForId ( root , id ) ; return closest ; }
Finds the closest context for the given component id . This handles the case where the component no longer exists due to having been removed from the UI or having a SubUIContext removed .
75
39
18,808
public static void updateBeanValue ( final WComponent component , final boolean visibleOnly ) { // Do not process if component is invisble and ignore visible is true. Will ignore entire branch from this point. if ( ! component . isVisible ( ) && visibleOnly ) { return ; } if ( component instanceof WBeanComponent ) { ( ( WBeanComponent ) component ) . updateBeanValue ( ) ; } // These components recursively update bean values themselves, // as they have special requirements due to repeating data. if ( component instanceof WDataTable || component instanceof WTable || component instanceof WRepeater ) { return ; } if ( component instanceof Container ) { for ( int i = ( ( Container ) component ) . getChildCount ( ) - 1 ; i >= 0 ; i -- ) { updateBeanValue ( ( ( Container ) component ) . getChildAt ( i ) , visibleOnly ) ; } } }
Updates the bean value with the current value of the component and all its bean - bound children .
199
20
18,809
public static String render ( final Request request , final WComponent component ) { boolean needsContext = UIContextHolder . getCurrent ( ) == null ; if ( needsContext ) { UIContextHolder . pushContext ( new UIContextImpl ( ) ) ; } try { StringWriter buffer = new StringWriter ( ) ; component . preparePaint ( request ) ; try ( PrintWriter writer = new PrintWriter ( buffer ) ) { component . paint ( new WebXmlRenderContext ( writer ) ) ; } return buffer . toString ( ) ; } finally { if ( needsContext ) { UIContextHolder . popContext ( ) ; } } }
Renders the given WComponent to a String outside of the context of a Servlet . This is good for getting hold of the XML for debugging unit testing etc . Also it is good for using the WComponent framework as a more generic templating framework .
143
52
18,810
public static String renderWithTransformToHTML ( final Request request , final WComponent component , final boolean includePageShell ) { // Setup a context (if needed) boolean needsContext = UIContextHolder . getCurrent ( ) == null ; if ( needsContext ) { UIContextHolder . pushContext ( new UIContextImpl ( ) ) ; } try { // Link Interceptors InterceptorComponent templateRender = new TemplateRenderInterceptor ( ) ; InterceptorComponent transformXML = new TransformXMLInterceptor ( ) ; templateRender . setBackingComponent ( transformXML ) ; if ( includePageShell ) { transformXML . setBackingComponent ( new PageShellInterceptor ( ) ) ; } // Attach Component and Mock Response InterceptorComponent chain = templateRender ; chain . attachUI ( component ) ; chain . attachResponse ( new MockResponse ( ) ) ; // Render chain StringWriter buffer = new StringWriter ( ) ; chain . preparePaint ( request ) ; try ( PrintWriter writer = new PrintWriter ( buffer ) ) { chain . paint ( new WebXmlRenderContext ( writer ) ) ; } return buffer . toString ( ) ; } finally { if ( needsContext ) { UIContextHolder . popContext ( ) ; } } }
Renders and transforms the given WComponent to a HTML String outside of the context of a Servlet .
272
21
18,811
public static String getContentType ( final String fileName ) { if ( Util . empty ( fileName ) ) { return ConfigurationProperties . getDefaultMimeType ( ) ; } String mimeType = null ; if ( fileName . lastIndexOf ( ' ' ) > - 1 ) { String suffix = fileName . substring ( fileName . lastIndexOf ( ' ' ) + 1 ) . toLowerCase ( ) ; mimeType = ConfigurationProperties . getFileMimeTypeForExtension ( suffix ) ; } if ( mimeType == null ) { mimeType = URLConnection . guessContentTypeFromName ( fileName ) ; if ( mimeType == null ) { mimeType = ConfigurationProperties . getDefaultMimeType ( ) ; } } return mimeType ; }
Attempts to guess the content - type for the given file name .
172
13
18,812
public static NamingContextable getParentNamingContext ( final WComponent component ) { if ( component == null ) { return null ; } WComponent child = component ; NamingContextable parent = null ; while ( true ) { NamingContextable naming = WebUtilities . getAncestorOfClass ( NamingContextable . class , child ) ; if ( naming == null ) { break ; } if ( WebUtilities . isActiveNamingContext ( naming ) ) { parent = naming ; break ; } child = naming ; } return parent ; }
Get this component s parent naming context .
117
8
18,813
private void updateBeanValueForColumnInRow ( final WTableRowRenderer rowRenderer , final UIContext rowContext , final List < Integer > rowIndex , final int col , final TableModel model ) { // The actual component is wrapped in a renderer wrapper, so we have to fetch it from that WComponent renderer = ( ( Container ) rowRenderer . getRenderer ( col ) ) . getChildAt ( 0 ) ; UIContextHolder . pushContext ( rowContext ) ; try { // If the column is a Container then call updateBeanValue to let the column renderer and its children update // the "bean" returned by getValueAt(row, col) if ( renderer instanceof Container ) { WebUtilities . updateBeanValue ( renderer ) ; } else if ( renderer instanceof DataBound ) { // Update Databound renderer Object oldValue = model . getValueAt ( rowIndex , col ) ; Object newValue = ( ( DataBound ) renderer ) . getData ( ) ; if ( ! Util . equals ( oldValue , newValue ) ) { model . setValueAt ( newValue , rowIndex , col ) ; } } } finally { UIContextHolder . popContext ( ) ; } }
Update the column in the row .
278
7
18,814
private void updateBeanValueForRowRenderer ( final WTableRowRenderer rowRenderer , final UIContext rowContext , final Class < ? extends WComponent > expandRenderer ) { Container expandWrapper = ( Container ) rowRenderer . getExpandedTreeNodeRenderer ( expandRenderer ) ; if ( expandWrapper == null ) { return ; } // The actual component is wrapped in a renderer wrapper, so we have to fetch it from that WComponent expandInstance = expandWrapper . getChildAt ( 0 ) ; UIContextHolder . pushContext ( rowContext ) ; try { // Will apply updates to the "bean" returned by the model for this expanded renderer (ie // getValueAt(rowIndex, -1)) WebUtilities . updateBeanValue ( expandInstance ) ; } finally { UIContextHolder . popContext ( ) ; } }
Update the expandable row renderer .
199
8
18,815
public void setSeparatorType ( final SeparatorType separatorType ) { getOrCreateComponentModel ( ) . separatorType = separatorType == null ? SeparatorType . NONE : separatorType ; }
Sets the separator used to visually separate rows or columns .
49
13
18,816
public void setStripingType ( final StripingType stripingType ) { getOrCreateComponentModel ( ) . stripingType = stripingType == null ? StripingType . NONE : stripingType ; }
Sets the striping type used to highlight alternate rows or columns .
47
14
18,817
public void setPaginationMode ( final PaginationMode paginationMode ) { getOrCreateComponentModel ( ) . paginationMode = paginationMode == null ? PaginationMode . NONE : paginationMode ; }
Sets the pagination mode .
47
7
18,818
public void setPaginationLocation ( final PaginationLocation location ) { getOrCreateComponentModel ( ) . paginationLocation = location == null ? PaginationLocation . AUTO : location ; }
Sets the location in the table to show the pagination controls .
41
14
18,819
public void setType ( final Type type ) { getOrCreateComponentModel ( ) . type = type == null ? Type . TABLE : type ; }
Sets the table type that controls how the table is displayed .
31
13
18,820
public void setSelectAllMode ( final SelectAllType selectAllMode ) { getOrCreateComponentModel ( ) . selectAllMode = selectAllMode == null ? SelectAllType . TEXT : selectAllMode ; }
Sets how the table row select all function should be displayed .
45
13
18,821
public List < WButton > getActions ( ) { final int numActions = actions . getChildCount ( ) ; List < WButton > buttons = new ArrayList <> ( numActions ) ; for ( int i = 0 ; i < numActions ; i ++ ) { WButton button = ( WButton ) actions . getChildAt ( i ) ; buttons . add ( button ) ; } return Collections . unmodifiableList ( buttons ) ; }
Retrieves the actions for the table .
98
9
18,822
public void addActionConstraint ( final WButton button , final ActionConstraint constraint ) { if ( button . getParent ( ) != actions ) { throw new IllegalArgumentException ( "Can only add a constraint to a button which is in this table's actions" ) ; } getOrCreateComponentModel ( ) . addActionConstraint ( button , constraint ) ; }
Adds a constraint to when the given action can be used .
80
12
18,823
public List < ActionConstraint > getActionConstraints ( final WButton button ) { List < ActionConstraint > constraints = getComponentModel ( ) . actionConstraints . get ( button ) ; return constraints == null ? null : Collections . unmodifiableList ( constraints ) ; }
Retrieves the constraints for the given action .
63
10
18,824
private void handleSortRequest ( final Request request ) { String sortColStr = request . getParameter ( getId ( ) + ".sort" ) ; String sortDescStr = request . getParameter ( getId ( ) + ".sortDesc" ) ; if ( sortColStr != null ) { if ( "" . equals ( sortColStr ) ) { // Reset sort setSort ( - 1 , false ) ; getOrCreateComponentModel ( ) . rowIndexMapping = null ; } else { try { int sortCol = Integer . parseInt ( sortColStr ) ; // Allow for column order int [ ] cols = getColumnOrder ( ) ; if ( cols != null ) { sortCol = cols [ sortCol ] ; } boolean sortAsc = ! "true" . equalsIgnoreCase ( sortDescStr ) ; // Only process the sort request if it differs from the current sort order if ( sortCol != getSortColumnIndex ( ) || sortAsc != isSortAscending ( ) ) { sort ( sortCol , sortAsc ) ; setFocussed ( ) ; } } catch ( NumberFormatException e ) { LOG . warn ( "Invalid sort column: " + sortColStr ) ; } } } }
Handles a request containing sort instruction data .
261
9
18,825
public void sort ( final int sortCol , final boolean sortAsc ) { int [ ] rowIndexMappings = getTableModel ( ) . sort ( sortCol , sortAsc ) ; getOrCreateComponentModel ( ) . rowIndexMapping = rowIndexMappings ; setSort ( sortCol , sortAsc ) ; if ( rowIndexMappings == null ) { // There's no way to correlate the previously selected row indices // with the new order of rows, so we need to clear out the selection. setSelectedRows ( null ) ; setExpandedRows ( null ) ; } }
Sort the table data by the specified column .
128
9
18,826
@ SuppressWarnings ( "checkstyle:parameternumber" ) private void calcChildrenRowIds ( final List < RowIdWrapper > rows , final RowIdWrapper row , final TableModel model , final RowIdWrapper parent , final Set < ? > expanded , final ExpandMode mode , final boolean forUpdate , final boolean editable ) { // Add row rows . add ( row ) ; // Add to parent if ( parent != null ) { parent . addChild ( row ) ; } List < Integer > rowIndex = row . getRowIndex ( ) ; // If row has a renderer, then dont need to process its children (should not have any anyway as it is a "leaf") if ( model . getRendererClass ( rowIndex ) != null ) { return ; } // Check row is expandable if ( ! model . isExpandable ( rowIndex ) ) { return ; } // Check has children if ( ! model . hasChildren ( rowIndex ) ) { return ; } row . setHasChildren ( true ) ; // Always add children if CLIENT mode or row is expanded boolean addChildren = ( mode == ExpandMode . CLIENT ) || ( expanded != null && expanded . contains ( row . getRowKey ( ) ) ) ; if ( ! addChildren ) { return ; } // Get actual child count int children = model . getChildCount ( rowIndex ) ; if ( children == 0 ) { // Could be there are no children even though hasChildren returned true row . setHasChildren ( false ) ; return ; } // Render mode, Keep rows that have been expanded (only if table editable) if ( ! forUpdate && editable ) { addPrevExpandedRow ( row . getRowKey ( ) ) ; } // Add children by processing each child row for ( int i = 0 ; i < children ; i ++ ) { // Add next level List < Integer > nextRow = new ArrayList <> ( row . getRowIndex ( ) ) ; nextRow . add ( i ) ; // Create Wrapper Object key = model . getRowKey ( nextRow ) ; RowIdWrapper wrapper = new RowIdWrapper ( nextRow , key , row ) ; calcChildrenRowIds ( rows , wrapper , model , row , expanded , mode , forUpdate , editable ) ; } }
Calculate the row ids of a row s children .
490
13
18,827
@ Override public void paint ( final RenderContext renderContext ) { super . paint ( renderContext ) ; UIContext uic = UIContextHolder . getCurrent ( ) ; if ( LOG . isDebugEnabled ( ) ) { UIContextDebugWrapper debugWrapper = new UIContextDebugWrapper ( uic ) ; LOG . debug ( "Session usage after paint:\n" + debugWrapper ) ; } LOG . debug ( "Performing session tidy up of WComponents (any WComponents disconnected from the active top component will not be tidied up." ) ; getUI ( ) . tidyUpUIContextForTree ( ) ; LOG . debug ( "After paint - Clearing scratch maps." ) ; uic . clearScratchMap ( ) ; uic . clearRequestScratchMap ( ) ; }
Override paint to clear out the scratch map and component models which are no longer necessary .
182
17
18,828
public void setButtonColumns ( final int numColumns ) { if ( numColumns < 1 ) { throw new IllegalArgumentException ( "Must have one or more columns" ) ; } CheckBoxSelectModel model = getOrCreateComponentModel ( ) ; model . numColumns = numColumns ; model . layout = numColumns == 1 ? LAYOUT_STACKED : LAYOUT_COLUMNS ; }
Sets the layout to be a certain number of columns .
92
12
18,829
protected void doHandleAjaxRefresh ( ) { final Action action = getRefreshAction ( ) ; if ( action == null ) { return ; } final ActionEvent event = new ActionEvent ( this , AJAX_REFRESH_ACTION_COMMAND , getAjaxFilter ( ) ) ; Runnable later = new Runnable ( ) { @ Override public void run ( ) { action . execute ( event ) ; } } ; invokeLater ( later ) ; }
Handle the AJAX refresh request .
104
7
18,830
public List < String > getSuggestions ( ) { // Lookup table Object table = getLookupTable ( ) ; if ( table == null ) { SuggestionsModel model = getComponentModel ( ) ; List < String > suggestions = model . getSuggestions ( ) ; return suggestions == null ? Collections . EMPTY_LIST : suggestions ; } else { List < ? > lookupSuggestions = APPLICATION_LOOKUP_TABLE . getTable ( table ) ; if ( lookupSuggestions == null || lookupSuggestions . isEmpty ( ) ) { return Collections . EMPTY_LIST ; } // Build list of String suggestions List < String > suggestions = new ArrayList <> ( lookupSuggestions . size ( ) ) ; for ( Object suggestion : lookupSuggestions ) { String sugg = APPLICATION_LOOKUP_TABLE . getDescription ( table , suggestion ) ; if ( sugg != null ) { suggestions . add ( sugg ) ; } } return Collections . unmodifiableList ( suggestions ) ; } }
Returns the complete list of suggestions available for selection for this user s session .
210
15
18,831
public void setSuggestions ( final List < String > suggestions ) { SuggestionsModel model = getOrCreateComponentModel ( ) ; model . setSuggestions ( suggestions ) ; }
Set the complete list of suggestions available for selection for this user s session .
37
15
18,832
public static String validateXMLAgainstSchema ( final String xml ) { // Validate XML against schema if ( xml != null && ! xml . equals ( "" ) ) { // Wrap XML with a root element (if required) String testXML = wrapXMLInRootElement ( xml ) ; try { // Create SAX Parser Factory SAXParserFactory spf = SAXParserFactory . newInstance ( ) ; spf . setNamespaceAware ( true ) ; spf . setValidating ( true ) ; // Create SAX Parser SAXParser parser = spf . newSAXParser ( ) ; parser . setProperty ( "http://java.sun.com/xml/jaxp/properties/schemaLanguage" , XMLConstants . W3C_XML_SCHEMA_NS_URI ) ; // Set schema location Object schema = DebugValidateXML . class . getResource ( getSchemaPath ( ) ) . toString ( ) ; parser . setProperty ( "http://java.sun.com/xml/jaxp/properties/schemaSource" , schema ) ; // Setup the handler to throw an exception when an error occurs DefaultHandler handler = new DefaultHandler ( ) { @ Override public void warning ( final SAXParseException e ) throws SAXException { LOG . warn ( "XML Schema warning: " + e . getMessage ( ) , e ) ; super . warning ( e ) ; } @ Override public void fatalError ( final SAXParseException e ) throws SAXException { throw e ; } @ Override public void error ( final SAXParseException e ) throws SAXException { throw e ; } } ; // Validate the XML InputSource xmlSource = new InputSource ( new StringReader ( testXML ) ) ; parser . parse ( xmlSource , handler ) ; } catch ( SAXParseException e ) { return "At line " + e . getLineNumber ( ) + ", column: " + e . getColumnNumber ( ) + " ==> " + e . getMessage ( ) ; } catch ( Exception e ) { return e . getMessage ( ) ; } } return null ; }
Validate the component to make sure the generated XML is schema compliant .
468
14
18,833
public static String wrapXMLInRootElement ( final String xml ) { // The XML may not need to be wrapped. if ( xml . startsWith ( "<?xml" ) || xml . startsWith ( "<!DOCTYPE" ) ) { return xml ; } else { // ENTITY definition required for NBSP. // ui namepsace required for xml theme. return XMLUtil . XML_DECLARATION + "<ui:root" + XMLUtil . STANDARD_NAMESPACES + ">" + xml + "</ui:root>" ; } }
Wrap the XML in a root element before validating .
123
12
18,834
public static void registerResource ( final InternalResource resource ) { String resourceName = resource . getResourceName ( ) ; if ( ! RESOURCES . containsKey ( resourceName ) ) { RESOURCES . put ( resourceName , resource ) ; RESOURCE_CACHE_KEYS . put ( resourceName , computeHash ( resource ) ) ; } }
Adds a resource to the resource map .
77
8
18,835
public static String computeHash ( final InternalResource resource ) { final int bufferSize = 1024 ; try ( InputStream stream = resource . getStream ( ) ) { if ( stream == null ) { return null ; } // Compute CRC-32 checksum // TODO: Is a 1 in 2^32 chance of a cache bust fail good enough? // Checksum checksumEngine = new Adler32(); Checksum checksumEngine = new CRC32 ( ) ; byte [ ] buf = new byte [ bufferSize ] ; for ( int read = stream . read ( buf ) ; read != - 1 ; read = stream . read ( buf ) ) { checksumEngine . update ( buf , 0 , read ) ; } return Long . toHexString ( checksumEngine . getValue ( ) ) ; } catch ( Exception e ) { throw new SystemException ( "Error calculating resource hash" , e ) ; } }
Computes a simple hash of the resource contents .
191
10
18,836
@ Override protected void doReplace ( final String search , final Writer backing ) { WComponent component = componentsByKey . get ( search ) ; UIContextHolder . pushContext ( uic ) ; try { component . paint ( new WebXmlRenderContext ( ( PrintWriter ) backing ) ) ; } finally { UIContextHolder . popContext ( ) ; } }
Replaces the search string by rendering the corresponding component .
83
11
18,837
protected Object getTopRowBean ( final List < Integer > row ) { // Get root level List < ? > lvl = getBeanList ( ) ; if ( lvl == null || lvl . isEmpty ( ) ) { return null ; } // Get root row bean (ie top level) int rowIdx = row . get ( 0 ) ; Object rowData = lvl . get ( rowIdx ) ; return rowData ; }
Return the top level bean for this row index .
91
10
18,838
protected Object getBeanPropertyValue ( final String property , final Object bean ) { if ( bean == null ) { return null ; } if ( "." . equals ( property ) ) { return bean ; } try { Object data = PropertyUtils . getProperty ( bean , property ) ; return data ; } catch ( Exception e ) { LOG . error ( "Failed to get bean property " + property + " on " + bean , e ) ; return null ; } }
Get the bean property value .
99
6
18,839
protected void setBeanPropertyValue ( final String property , final Object bean , final Serializable value ) { if ( bean == null ) { return ; } if ( "." . equals ( property ) ) { LOG . error ( "Set of entire bean is not supported by this model" ) ; return ; } try { PropertyUtils . setProperty ( bean , property , value ) ; } catch ( Exception e ) { LOG . error ( "Failed to set bean property " + property + " on " + bean , e ) ; } }
Set the bean property value .
113
6
18,840
@ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WDataTable table = ( WDataTable ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; xml . appendTagOpen ( "ui:table" ) ; xml . appendAttribute ( "id" , component . getId ( ) ) ; xml . appendOptionalAttribute ( "track" , component . isTracking ( ) , "true" ) ; xml . appendOptionalAttribute ( "hidden" , table . isHidden ( ) , "true" ) ; xml . appendOptionalAttribute ( "caption" , table . getCaption ( ) ) ; switch ( table . getType ( ) ) { case TABLE : xml . appendAttribute ( "type" , "table" ) ; break ; case HIERARCHIC : xml . appendAttribute ( "type" , "hierarchic" ) ; break ; default : throw new SystemException ( "Unknown table type: " + table . getType ( ) ) ; } switch ( table . getStripingType ( ) ) { case ROWS : xml . appendAttribute ( "striping" , "rows" ) ; break ; case COLUMNS : xml . appendAttribute ( "striping" , "cols" ) ; break ; case NONE : break ; default : throw new SystemException ( "Unknown striping type: " + table . getStripingType ( ) ) ; } switch ( table . getSeparatorType ( ) ) { case HORIZONTAL : xml . appendAttribute ( "separators" , "horizontal" ) ; break ; case VERTICAL : xml . appendAttribute ( "separators" , "vertical" ) ; break ; case BOTH : xml . appendAttribute ( "separators" , "both" ) ; break ; case NONE : break ; default : throw new SystemException ( "Unknown separator type: " + table . getSeparatorType ( ) ) ; } xml . appendClose ( ) ; if ( table . getPaginationMode ( ) != PaginationMode . NONE ) { paintPaginationElement ( table , xml ) ; } if ( table . getSelectMode ( ) != SelectMode . NONE ) { paintRowSelectionElement ( table , xml ) ; } if ( table . getExpandMode ( ) != ExpandMode . NONE ) { paintRowExpansionElement ( table , xml ) ; } if ( table . isSortable ( ) ) { paintSortElement ( table , xml ) ; } paintColumnHeadings ( table , renderContext ) ; paintRows ( table , renderContext ) ; paintTableActions ( table , renderContext ) ; xml . appendEndTag ( "ui:table" ) ; }
Paints the given WDataTable .
590
8
18,841
private void paintPaginationElement ( final WDataTable table , final XmlStringBuilder xml ) { TableDataModel model = table . getDataModel ( ) ; xml . appendTagOpen ( "ui:pagination" ) ; if ( model instanceof TreeTableDataModel ) { // For tree tables, we only include top-level nodes for pagination. TreeNode firstNode = ( ( TreeTableDataModel ) model ) . getNodeAtLine ( 0 ) ; xml . appendAttribute ( "rows" , firstNode == null ? 0 : firstNode . getParent ( ) . getChildCount ( ) ) ; } else { xml . appendAttribute ( "rows" , model . getRowCount ( ) ) ; } xml . appendAttribute ( "rowsPerPage" , table . getRowsPerPage ( ) ) ; xml . appendAttribute ( "currentPage" , table . getCurrentPage ( ) ) ; switch ( table . getPaginationMode ( ) ) { case CLIENT : xml . appendAttribute ( "mode" , "client" ) ; break ; case DYNAMIC : case SERVER : xml . appendAttribute ( "mode" , "dynamic" ) ; break ; case NONE : break ; default : throw new SystemException ( "Unknown pagination mode: " + table . getPaginationMode ( ) ) ; } xml . appendEnd ( ) ; }
Paint the pagination aspects of the WDataTable .
294
12
18,842
public void setAction ( final Action action ) { MenuItemModel model = getOrCreateComponentModel ( ) ; model . action = action ; model . url = null ; }
Sets the action to execute when the menu item is invoked .
36
13
18,843
public void setUrl ( final String url ) { MenuItemModel model = getOrCreateComponentModel ( ) ; model . url = url ; model . action = null ; }
Sets the URL to navigate to when the menu item is invoked .
36
14
18,844
public void setMessage ( final String message , final Serializable ... args ) { getOrCreateComponentModel ( ) . message = I18nUtilities . asMessage ( message , args ) ; }
Sets the confirmation message that is to be displayed to the user for this menu item .
41
18
18,845
@ Override public void handleRequest ( final Request request ) { if ( isDisabled ( ) ) { // Protect against client-side tampering of disabled/read-only fields. return ; } if ( isMenuPresent ( request ) ) { String requestValue = request . getParameter ( getId ( ) ) ; if ( requestValue != null ) { // Only process on a POST if ( ! "POST" . equals ( request . getMethod ( ) ) ) { LOG . warn ( "Menu item on a request that is not a POST. Will be ignored." ) ; return ; } // Execute associated action, if set final Action action = getAction ( ) ; if ( action != null ) { final ActionEvent event = new ActionEvent ( this , this . getActionCommand ( ) , this . getActionObject ( ) ) ; Runnable later = new Runnable ( ) { @ Override public void run ( ) { action . execute ( event ) ; } } ; invokeLater ( later ) ; } } } }
Override handleRequest in order to perform processing for this component . This implementation checks for selection of the menu item and executes the associated action if it has been set .
215
32
18,846
protected boolean isMenuPresent ( final Request request ) { WMenu menu = WebUtilities . getAncestorOfClass ( WMenu . class , this ) ; if ( menu != null ) { return menu . isPresent ( request ) ; } return false ; }
Determine if this WMenuItem s parent WMenu is on the Request .
55
17
18,847
@ Deprecated @ Override public void setEditable ( final boolean editable ) { setType ( editable ? DropdownType . COMBO : DropdownType . NATIVE ) ; }
Sets whether the users are able to enter in an arbitrary value rather than having to pick one from the drop - down list .
40
26
18,848
private void buildUI ( ) { add ( new WSkipLinks ( ) ) ; // the application header add ( headerPanel ) ; headerPanel . add ( new UtilityBar ( ) ) ; headerPanel . add ( new WHeading ( HeadingLevel . H1 , "WComponents" ) ) ; // mainPanel holds the menu and the actual example. add ( mainPanel ) ; mainPanel . add ( menuPanel ) ; mainPanel . add ( exampleSection ) ; // An application footer? WPanel footer = new WPanel ( WPanel . Type . FOOTER ) ; footer . add ( lastLoaded ) ; add ( footer ) ; add ( new WAjaxControl ( menuPanel . getTree ( ) , new AjaxTarget [ ] { menuPanel . getMenu ( ) , exampleSection } ) ) ; }
Add all the bits in the right order .
177
9
18,849
@ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WPopup popup = ( WPopup ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; int width = popup . getWidth ( ) ; int height = popup . getHeight ( ) ; String targetWindow = popup . getTargetWindow ( ) ; xml . appendTagOpen ( "ui:popup" ) ; xml . appendUrlAttribute ( "url" , popup . getUrl ( ) ) ; xml . appendOptionalAttribute ( "width" , width > 0 , width ) ; xml . appendOptionalAttribute ( "height" , height > 0 , height ) ; xml . appendOptionalAttribute ( "resizable" , popup . isResizable ( ) , "true" ) ; xml . appendOptionalAttribute ( "showScrollbars" , popup . isScrollable ( ) , "true" ) ; xml . appendOptionalAttribute ( "targetWindow" , ! Util . empty ( targetWindow ) , targetWindow ) ; xml . appendClose ( ) ; xml . appendEndTag ( "ui:popup" ) ; }
Paints the given WPopup .
243
8
18,850
public static ObjectGraphNode dump ( final Object obj ) { ObjectGraphDump dump = new ObjectGraphDump ( false , true ) ; ObjectGraphNode root = new ObjectGraphNode ( ++ dump . nodeCount , null , obj . getClass ( ) . getName ( ) , obj ) ; dump . visit ( root ) ; return root ; }
Dumps the contents of the session attributes .
73
9
18,851
private void visit ( final ObjectGraphNode currentNode ) { Object currentValue = currentNode . getValue ( ) ; if ( currentValue == null || ( currentValue instanceof java . lang . ref . SoftReference ) || currentNode . isPrimitive ( ) || currentNode . isSimpleType ( ) ) { return ; } if ( isObjectVisited ( currentNode ) ) { ObjectGraphNode ref = visitedNodes . get ( currentValue ) ; currentNode . setRefNode ( ref ) ; return ; } markObjectVisited ( currentNode ) ; if ( currentValue instanceof List ) { // ArrayList's elementData is marked transient, and others may be as well, so we have to do this ourselves. visitList ( currentNode ) ; } else if ( currentValue instanceof Map ) { // HashMap's table is marked transient, and others may be as well, so we have to do this ourselves. visitMap ( currentNode ) ; } else if ( currentValue instanceof ComponentModel ) { // Special case for ComponentModel, so we can figure out if any fields are overridden visitComponentModel ( currentNode ) ; } else if ( currentValue instanceof Field ) { visitComplexType ( currentNode ) ; summariseNode ( currentNode ) ; } else if ( currentValue . getClass ( ) . isArray ( ) ) { visitArray ( currentNode ) ; } else { visitComplexType ( currentNode ) ; } }
Implementation of the tree walk .
305
7
18,852
private void visitComplexType ( final ObjectGraphNode node ) { Field [ ] fields = getAllInstanceFields ( node . getValue ( ) ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { Object fieldValue = readField ( fields [ i ] , node . getValue ( ) ) ; String fieldType = fields [ i ] . getType ( ) . getName ( ) ; ObjectGraphNode childNode = new ObjectGraphNode ( ++ nodeCount , fields [ i ] . getName ( ) , fieldType , fieldValue ) ; node . add ( childNode ) ; visit ( childNode ) ; } }
Visits all the fields in the given complex object .
137
11
18,853
private void visitComplexTypeWithDiff ( final ObjectGraphNode node , final Object otherInstance ) { if ( otherInstance == null ) { // Nothing to compare against, just use the default visit visitComplexType ( node ) ; } else { Field [ ] fields = getAllInstanceFields ( node . getValue ( ) ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { Object fieldValue = readField ( fields [ i ] , node . getValue ( ) ) ; Object otherValue = readField ( fields [ i ] , otherInstance ) ; String fieldType = fields [ i ] . getType ( ) . getName ( ) ; String nodeFieldName = fields [ i ] . getName ( ) + ( Util . equals ( fieldValue , otherValue ) ? "" : "*" ) ; ObjectGraphNode childNode = new ObjectGraphNode ( ++ nodeCount , nodeFieldName , fieldType , fieldValue ) ; node . add ( childNode ) ; visit ( childNode ) ; } } }
Visits all the fields in the given complex object noting differences .
220
13
18,854
private void visitComponentModel ( final ObjectGraphNode node ) { ComponentModel model = ( ComponentModel ) node . getValue ( ) ; ComponentModel sharedModel = null ; List < Field > fieldList = ReflectionUtil . getAllFields ( node . getValue ( ) , true , false ) ; Field [ ] fields = fieldList . toArray ( new Field [ fieldList . size ( ) ] ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { if ( ComponentModel . class . equals ( fields [ i ] . getDeclaringClass ( ) ) && "sharedModel" . equals ( fields [ i ] . getName ( ) ) ) { sharedModel = ( ComponentModel ) readField ( fields [ i ] , model ) ; } } visitComplexTypeWithDiff ( node , sharedModel ) ; }
Visits all the fields in the given ComponentModel .
179
11
18,855
private Object readField ( final Field field , final Object obj ) { try { return field . get ( obj ) ; } catch ( IllegalAccessException e ) { // Should not happen as we've called Field.setAccessible(true). LOG . error ( "Failed to read " + field . getName ( ) + " of " + obj . getClass ( ) . getName ( ) , e ) ; } return null ; }
Reads the contents of a field .
91
8
18,856
private void visitArray ( final ObjectGraphNode node ) { if ( node . getValue ( ) instanceof Object [ ] ) { Object [ ] array = ( Object [ ] ) node . getValue ( ) ; for ( int i = 0 ; i < array . length ; i ++ ) { String entryType = array [ i ] == null ? Object . class . getName ( ) : array [ i ] . getClass ( ) . getName ( ) ; ObjectGraphNode childNode = new ObjectGraphNode ( ++ nodeCount , "[" + i + "]" , entryType , array [ i ] ) ; node . add ( childNode ) ; visit ( childNode ) ; } } else { ObjectGraphNode childNode = new ObjectGraphNode ( ++ nodeCount , "[primitive array]" , node . getValue ( ) . getClass ( ) . getName ( ) , node . getValue ( ) ) ; node . add ( childNode ) ; } }
Visits all the elements of the given array .
202
10
18,857
private void visitList ( final ObjectGraphNode node ) { int index = 0 ; for ( Iterator i = ( ( List ) node . getValue ( ) ) . iterator ( ) ; i . hasNext ( ) ; ) { Object entry = i . next ( ) ; String entryType = entry == null ? Object . class . getName ( ) : entry . getClass ( ) . getName ( ) ; ObjectGraphNode childNode = new ObjectGraphNode ( ++ nodeCount , "[" + index ++ + "]" , entryType , entry ) ; node . add ( childNode ) ; visit ( childNode ) ; } adjustOverhead ( node ) ; }
Visits all the elements of the given list .
139
10
18,858
private void summariseNode ( final ObjectGraphNode node ) { int size = node . getSize ( ) ; node . removeAll ( ) ; node . setSize ( size ) ; }
For some types we don t care about their internals so just summarise the size .
39
18
18,859
private void visitMap ( final ObjectGraphNode node ) { Map map = ( Map ) node . getValue ( ) ; for ( Iterator i = map . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) i . next ( ) ; Object key = entry . getKey ( ) ; if ( key != null ) { ObjectGraphNode keyNode = new ObjectGraphNode ( ++ nodeCount , "key" , key . getClass ( ) . getName ( ) , key ) ; node . add ( keyNode ) ; visit ( keyNode ) ; } else { ObjectGraphNode keyNode = new ObjectGraphNode ( ++ nodeCount , "key" , Object . class . getName ( ) , null ) ; node . add ( keyNode ) ; } Object value = entry . getValue ( ) ; if ( value != null ) { ObjectGraphNode valueNode = new ObjectGraphNode ( ++ nodeCount , "value" , value . getClass ( ) . getName ( ) , value ) ; node . add ( valueNode ) ; visit ( valueNode ) ; } else { ObjectGraphNode valueNode = new ObjectGraphNode ( ++ nodeCount , "value" , Object . class . getName ( ) , null ) ; node . add ( valueNode ) ; } } adjustOverhead ( node ) ; }
Visits all the keys and entries of the given map .
292
12
18,860
private Field [ ] getAllInstanceFields ( final Object obj ) { Field [ ] fields = instanceFieldsByClass . get ( obj . getClass ( ) ) ; if ( fields == null ) { List < Field > fieldList = ReflectionUtil . getAllFields ( obj , excludeStatic , excludeTransient ) ; fields = fieldList . toArray ( new Field [ fieldList . size ( ) ] ) ; instanceFieldsByClass . put ( obj . getClass ( ) , fields ) ; } return fields ; }
Retrieves all the instance fields for the given object .
113
12
18,861
private static void renderHelper ( final WebXmlRenderContext renderContext , final Diagnosable component , final List < Diagnostic > diags , final int severity ) { if ( diags . isEmpty ( ) ) { return ; } XmlStringBuilder xml = renderContext . getWriter ( ) ; xml . appendTagOpen ( TAG_NAME ) ; xml . appendAttribute ( "id" , "_wc_" . concat ( UUID . randomUUID ( ) . toString ( ) ) ) ; xml . appendAttribute ( "type" , getLevel ( severity ) ) ; xml . appendAttribute ( "for" , component . getId ( ) ) ; xml . appendClose ( ) ; for ( Diagnostic diagnostic : diags ) { xml . appendTag ( MESSAGE_TAG_NAME ) ; xml . appendEscaped ( diagnostic . getDescription ( ) ) ; xml . appendEndTag ( MESSAGE_TAG_NAME ) ; } xml . appendEndTag ( TAG_NAME ) ; }
Render the diagnostics .
216
5
18,862
public static void renderDiagnostics ( final Diagnosable component , final WebXmlRenderContext renderContext ) { List < Diagnostic > diags = component . getDiagnostics ( Diagnostic . ERROR ) ; if ( diags != null ) { renderHelper ( renderContext , component , diags , Diagnostic . ERROR ) ; } diags = component . getDiagnostics ( Diagnostic . WARNING ) ; if ( diags != null ) { renderHelper ( renderContext , component , diags , Diagnostic . WARNING ) ; } diags = component . getDiagnostics ( Diagnostic . INFO ) ; if ( diags != null ) { renderHelper ( renderContext , component , diags , Diagnostic . INFO ) ; } diags = component . getDiagnostics ( Diagnostic . SUCCESS ) ; if ( diags != null ) { renderHelper ( renderContext , component , diags , Diagnostic . SUCCESS ) ; } }
Render diagnostics for the component .
202
7
18,863
private void handleWarpToTheFuture ( final UIContext uic ) { // Increment the step counter StepCountUtil . incrementSessionStep ( uic ) ; // Get component at end of chain WComponent application = getUI ( ) ; // Call handle step error on WApplication if ( application instanceof WApplication ) { LOG . warn ( "The handleStepError method will be called on WApplication." ) ; ( ( WApplication ) application ) . handleStepError ( ) ; } }
Warp the user to the future by replacing the entire page .
105
13
18,864
private void handleRenderRedirect ( final PrintWriter writer ) { UIContext uic = UIContextHolder . getCurrent ( ) ; // Redirect user to error page LOG . warn ( "User will be redirected to " + redirectUrl ) ; // Setup response with redirect getResponse ( ) . setContentType ( WebUtilities . CONTENT_TYPE_XML ) ; writer . write ( XMLUtil . getXMLDeclarationWithThemeXslt ( uic ) ) ; writer . print ( "<ui:ajaxresponse " ) ; writer . print ( XMLUtil . UI_NAMESPACE ) ; writer . print ( ">" ) ; writer . print ( "<ui:ajaxtarget id=\"" + triggerId + "\" action=\"replace\">" ) ; // Redirect URL writer . print ( "<ui:redirect url=\"" + redirectUrl + "\" />" ) ; writer . print ( "</ui:ajaxtarget>" ) ; writer . print ( "</ui:ajaxresponse>" ) ; }
Redirect the user via the AJAX response .
224
10
18,865
private String buildApplicationUrl ( final UIContext uic ) { Environment env = uic . getEnvironment ( ) ; return env . getPostPath ( ) ; }
Build the url to refresh the application .
36
8
18,866
public static Serializable asMessage ( final String text , final Serializable ... args ) { if ( text == null ) { return null ; } else if ( args == null || args . length == 0 ) { return text ; } else { return new Message ( text , args ) ; } }
Converts a message String and optional message arguments to a an appropriate format for internationalisation .
60
18
18,867
public static String format ( final Locale locale , final String text , final Object ... args ) { if ( text == null ) { return null ; } String localisedText = getLocalisedText ( locale , text ) ; String message = localisedText == null ? text : localisedText ; if ( args != null ) { try { return MessageFormat . format ( message , args ) ; } catch ( IllegalArgumentException e ) { LOG . error ( "Invalid message format for message " + message , e ) ; } } return message ; }
Formats the given text optionally using locale - specific text .
114
12
18,868
public static Locale getEffectiveLocale ( ) { Locale effectiveLocale = null ; UIContext uic = UIContextHolder . getCurrent ( ) ; if ( uic != null ) { effectiveLocale = uic . getLocale ( ) ; } if ( effectiveLocale == null ) { String defaultLocale = ConfigurationProperties . getDefaultLocale ( ) ; effectiveLocale = new Locale ( defaultLocale ) ; } // Don't use Locale.getDefault() because it is too nebulous (depends on host environment) return effectiveLocale ; }
Get the locale currently in use .
128
7
18,869
public static String getLocalisedText ( final Locale locale , final String text ) { String message = null ; String resourceBundleBaseName = getResourceBundleBaseName ( ) ; if ( ! Util . empty ( resourceBundleBaseName ) ) { Locale effectiveLocale = locale ; if ( effectiveLocale == null ) { effectiveLocale = getEffectiveLocale ( ) ; } try { // TODO: This is slow ResourceBundle bundle = ResourceBundle . getBundle ( resourceBundleBaseName , effectiveLocale ) ; message = bundle . getString ( text ) ; } catch ( MissingResourceException e ) { // Fall back to the Configuration mechanism for the default internal messages if ( text != null && text . startsWith ( ConfigurationProperties . INTERNAL_MESSAGE_PREFIX ) ) { message = ConfigurationProperties . getInternalMessage ( text ) ; } if ( message == null && ! MISSING_RESOURCES . contains ( locale ) ) { LOG . error ( "Missing resource mapping for locale: " + locale + ", text: " + text ) ; MISSING_RESOURCES . add ( locale ) ; } } } else if ( text != null && text . startsWith ( ConfigurationProperties . INTERNAL_MESSAGE_PREFIX ) ) { // Fall back to the Configuration mechanism for the default internal messages message = ConfigurationProperties . getInternalMessage ( text ) ; } return message ; }
Attempts to retrieve the localized message for the given text .
313
11
18,870
public static boolean validateFileType ( final FileItemWrap newFile , final List < String > fileTypes ) { // The newFile is null, then return false if ( newFile == null ) { return false ; } // If fileTypes to validate is null or empty, then assume newFile is valid if ( fileTypes == null || fileTypes . isEmpty ( ) ) { return true ; } final List < String > fileExts = fileTypes . stream ( ) . filter ( fileType -> fileType . startsWith ( "." ) ) . collect ( Collectors . toList ( ) ) ; // filter mime types from fileTypes. final List < String > fileMimes = fileTypes . stream ( ) . filter ( fileType -> ! fileExts . contains ( fileType ) ) . collect ( Collectors . toList ( ) ) ; // First validate newFile against fileExts list // If extensions are supplied, then check if newFile has a name if ( fileExts . size ( ) > 0 && newFile . getName ( ) != null ) { // Then see if newFile has an extension String [ ] split = newFile . getName ( ) . split ( ( "\\.(?=[^\\.]+$)" ) ) ; // If it exists, then check if it matches supplied extension(s) if ( split . length == 2 && fileExts . stream ( ) . anyMatch ( fileExt -> fileExt . equals ( "." + split [ 1 ] ) ) ) { return true ; } } // If extension match is unsucessful, then move to fileMimes list if ( fileMimes . size ( ) > 0 ) { final String mimeType = getFileMimeType ( newFile ) ; LOG . debug ( "File mime-type is: " + mimeType ) ; for ( String fileMime : fileMimes ) { if ( StringUtils . equals ( mimeType , fileMime ) ) { return true ; } if ( fileMime . indexOf ( "*" ) == fileMime . length ( ) - 1 ) { fileMime = fileMime . substring ( 0 , fileMime . length ( ) - 1 ) ; if ( mimeType . indexOf ( fileMime ) == 0 ) { return true ; } } } } return false ; }
Checks if the file item is one among the supplied file types . This first checks against file extensions then against file mime types
498
26
18,871
public static String getFileMimeType ( final File file ) { if ( file != null ) { try { final Tika tika = new Tika ( ) ; return tika . detect ( file . getInputStream ( ) ) ; } catch ( IOException ex ) { LOG . error ( "Invalid file, name " + file . getName ( ) , ex ) ; } } return null ; }
Identify the mime type of a file .
85
10
18,872
public static boolean validateFileSize ( final FileItemWrap newFile , final long maxFileSize ) { // If newFile to validate is null, then return false if ( newFile == null ) { return false ; } // If maxFileSize to validate is zero or negative, then assume newFile is valid if ( maxFileSize < 1 ) { return true ; } return ( newFile . getSize ( ) <= maxFileSize ) ; }
Checks if the file item size is within the supplied max file size .
93
15
18,873
public static String getInvalidFileTypeMessage ( final List < String > fileTypes ) { if ( fileTypes == null ) { return null ; } return String . format ( I18nUtilities . format ( null , InternalMessages . DEFAULT_VALIDATION_ERROR_FILE_WRONG_TYPE ) , StringUtils . join ( fileTypes . toArray ( new Object [ fileTypes . size ( ) ] ) , "," ) ) ; }
Returns invalid fileTypes error message .
96
7
18,874
public static String getInvalidFileSizeMessage ( final long maxFileSize ) { return String . format ( I18nUtilities . format ( null , InternalMessages . DEFAULT_VALIDATION_ERROR_FILE_WRONG_SIZE ) , FileUtil . readableFileSize ( maxFileSize ) ) ; }
Returns invalid fileSize error message .
67
7
18,875
public List < Diagnostic > getDiagnostics ( ) { FieldIndicatorModel model = getComponentModel ( ) ; return Collections . unmodifiableList ( model . diagnostics ) ; }
Return the diagnostics for this indicator .
40
8
18,876
public void setWidth ( final int width ) { if ( width > 100 ) { throw new IllegalArgumentException ( "Width (" + width + ") cannot be greater than 100 percent" ) ; } getOrCreateComponentModel ( ) . width = Math . max ( 0 , width ) ; }
Sets the column width .
62
6
18,877
@ Override public void paint ( final RenderContext renderContext ) { // Set headers getResponse ( ) . setHeader ( "Cache-Control" , type . getSettings ( ) ) ; // Add extra no cache headers if ( ! type . isCache ( ) ) { getResponse ( ) . setHeader ( "Pragma" , "no-cache" ) ; getResponse ( ) . setHeader ( "Expires" , "-1" ) ; } super . paint ( renderContext ) ; }
Set the appropriate response headers for caching or not caching the response .
105
13
18,878
public void addMessage ( final boolean encode , final String msg , final Serializable ... args ) { MessageModel model = getOrCreateComponentModel ( ) ; model . messages . add ( new Duplet <> ( I18nUtilities . asMessage ( msg , args ) , encode ) ) ; // Potential for leaking memory here MemoryUtil . checkSize ( model . messages . size ( ) , this . getClass ( ) . getSimpleName ( ) ) ; }
Adds a message to the message box .
98
8
18,879
public void removeMessages ( final int index ) { MessageModel model = getOrCreateComponentModel ( ) ; if ( model . messages != null ) { model . messages . remove ( index ) ; } }
Removes a message from the message box .
43
9
18,880
public void clearMessages ( ) { MessageModel model = getOrCreateComponentModel ( ) ; if ( model . messages != null ) { model . messages . clear ( ) ; } }
Removes all messages from the message box .
39
9
18,881
public List < String > getMessages ( ) { MessageModel model = getComponentModel ( ) ; List < String > messages = new ArrayList <> ( model . messages . size ( ) ) ; for ( Duplet < Serializable , Boolean > message : model . messages ) { String text = I18nUtilities . format ( null , message . getFirst ( ) ) ; // If we are outputting unencoded content it must be XML valid. boolean encode = message . getSecond ( ) ; messages . add ( encode ? WebUtilities . encode ( text ) : HtmlToXMLUtil . unescapeToXML ( text ) ) ; } return Collections . unmodifiableList ( messages ) ; }
Retrieves the list of messages .
152
8
18,882
public void setVideo ( final Video [ ] video ) { List < Video > list = video == null ? null : Arrays . asList ( video ) ; getOrCreateComponentModel ( ) . video = list ; }
Sets the video clip in multiple formats . The client will try to load the first video clip and if it fails or isn t supported it will move on to the next video clip . Only the first clip which can be played on the client will be used .
46
52
18,883
public Video [ ] getVideo ( ) { List < Video > list = getComponentModel ( ) . video ; return list == null ? null : list . toArray ( new Video [ ] { } ) ; }
Retrieves the video clips associated with this WVideo .
44
12
18,884
public void setMediaGroup ( final String mediaGroup ) { String currMediaGroup = getMediaGroup ( ) ; if ( ! Objects . equals ( mediaGroup , currMediaGroup ) ) { getOrCreateComponentModel ( ) . mediaGroup = mediaGroup ; } }
Sets the media group .
57
6
18,885
public void setAltText ( final String altText ) { String currAltText = getAltText ( ) ; if ( ! Objects . equals ( altText , currAltText ) ) { getOrCreateComponentModel ( ) . altText = altText ; } }
Sets the alternative text to display when the video clip can not be played .
57
16
18,886
public void setTracks ( final Track [ ] tracks ) { List < Track > list = tracks == null ? null : Arrays . asList ( tracks ) ; getOrCreateComponentModel ( ) . tracks = list ; }
Sets the tracks for the video . The tracks are used to provide additional information relating to the video for example subtitles .
47
24
18,887
public Track [ ] getTracks ( ) { List < Track > list = getComponentModel ( ) . tracks ; return list == null ? null : list . toArray ( new Track [ ] { } ) ; }
Retrieves additional tracks associated with the video . The tracks provide additional information relating to the video for example subtitles .
45
23
18,888
@ Override public boolean isVisible ( ) { if ( ! super . isVisible ( ) ) { return false ; } Video [ ] video = getVideo ( ) ; return video != null && video . length > 0 ; }
Override isVisible to also return false if there are no video clips to play .
49
17
18,889
@ Override public void handleRequest ( final Request request ) { super . handleRequest ( request ) ; String targ = request . getParameter ( Environment . TARGET_ID ) ; boolean contentReqested = ( targ != null && targ . equals ( getTargetId ( ) ) ) ; if ( contentReqested && request . getParameter ( POSTER_REQUEST_PARAM_KEY ) != null ) { handlePosterRequest ( ) ; } if ( isDisabled ( ) ) { return ; } if ( contentReqested ) { if ( request . getParameter ( VIDEO_INDEX_REQUEST_PARAM_KEY ) != null ) { handleVideoRequest ( request ) ; } else if ( request . getParameter ( TRACK_INDEX_REQUEST_PARAM_KEY ) != null ) { handleTrackRequest ( request ) ; } } }
When an video element is rendered to the client the browser will make a second request to get the video content . The handleRequest method has been overridden to detect whether the request is the content fetch request by looking for the parameter that we encode in the content url .
183
53
18,890
private void handlePosterRequest ( ) { Image poster = getComponentModel ( ) . poster ; if ( poster != null ) { ContentEscape escape = new ContentEscape ( poster ) ; escape . setCacheable ( ! Util . empty ( getCacheKey ( ) ) ) ; throw escape ; } else { LOG . warn ( "Client requested non-existant poster" ) ; } }
Handles a request for the poster .
83
8
18,891
private void handleVideoRequest ( final Request request ) { String videoRequested = request . getParameter ( VIDEO_INDEX_REQUEST_PARAM_KEY ) ; int videoFileIndex = 0 ; try { videoFileIndex = Integer . parseInt ( videoRequested ) ; } catch ( NumberFormatException e ) { LOG . error ( "Failed to parse video index: " + videoFileIndex ) ; } Video [ ] video = getVideo ( ) ; if ( video != null && videoFileIndex >= 0 && videoFileIndex < video . length ) { ContentEscape escape = new ContentEscape ( video [ videoFileIndex ] ) ; escape . setCacheable ( ! Util . empty ( getCacheKey ( ) ) ) ; throw escape ; } else { LOG . warn ( "Client requested invalid video clip: " + videoFileIndex ) ; } }
Handles a request for a video .
182
8
18,892
private void handleTrackRequest ( final Request request ) { String trackRequested = request . getParameter ( TRACK_INDEX_REQUEST_PARAM_KEY ) ; int trackIndex = 0 ; try { trackIndex = Integer . parseInt ( trackRequested ) ; } catch ( NumberFormatException e ) { LOG . error ( "Failed to parse track index: " + trackIndex ) ; } Track [ ] tracks = getTracks ( ) ; if ( tracks != null && trackIndex >= 0 && trackIndex < tracks . length ) { ContentEscape escape = new ContentEscape ( tracks [ trackIndex ] ) ; escape . setCacheable ( ! Util . empty ( getCacheKey ( ) ) ) ; throw escape ; } else { LOG . warn ( "Client requested invalid track: " + trackIndex ) ; } }
Handles a request for an auxillary track .
176
10
18,893
public void setAudio ( final Audio [ ] audio ) { List < Audio > list = audio == null ? null : Arrays . asList ( audio ) ; getOrCreateComponentModel ( ) . audio = list ; }
Sets the audio clip in multiple formats for all users . The client will try to load the first audio clip and if it fails or isn t supported it will move on to the next audio clip . Only the first clip which can be played on the client will be used .
46
55
18,894
public Audio [ ] getAudio ( ) { List < Audio > list = getComponentModel ( ) . audio ; return list == null ? null : list . toArray ( new Audio [ ] { } ) ; }
Retrieves the audio clips associated with this WAudio .
44
12
18,895
@ Override public boolean isVisible ( ) { if ( ! super . isVisible ( ) ) { return false ; } Audio [ ] audio = getAudio ( ) ; return audio != null && audio . length > 0 ; }
Override isVisible to also return false if there are no audio clips to play .
49
17
18,896
@ Override public void handleRequest ( final Request request ) { super . handleRequest ( request ) ; if ( isDisabled ( ) ) { return ; } String targ = request . getParameter ( Environment . TARGET_ID ) ; String audioFileRequested = request . getParameter ( AUDIO_INDEX_REQUEST_PARAM_KEY ) ; boolean contentReqested = targ != null && targ . equals ( getTargetId ( ) ) ; if ( contentReqested ) { int audioFileIndex = 0 ; try { audioFileIndex = Integer . parseInt ( audioFileRequested ) ; } catch ( NumberFormatException e ) { LOG . error ( "Failed to parse audio index: " + audioFileIndex ) ; } Audio [ ] audio = getAudio ( ) ; if ( audio != null && audioFileIndex >= 0 && audioFileIndex < audio . length ) { ContentEscape escape = new ContentEscape ( audio [ audioFileIndex ] ) ; escape . setCacheable ( ! Util . empty ( getCacheKey ( ) ) ) ; throw escape ; } else { LOG . error ( "Requested invalid audio clip: " + audioFileIndex ) ; } } }
When an audio element is rendered to the client the browser will make a second request to get the audio content . The handleRequest method has been overridden to detect whether the request is the content fetch request by looking for the parameter that we encode in the content url .
253
53
18,897
private WFieldLayout recursiveFieldLayout ( final int curr , final int startAt ) { WFieldLayout innerLayout = new WFieldLayout ( ) ; innerLayout . setLabelWidth ( 20 ) ; if ( curr == 0 && startAt == 0 ) { innerLayout . setMargin ( new Margin ( Size . LARGE , null , null , null ) ) ; } innerLayout . setOrdered ( true ) ; if ( startAt > 1 ) { innerLayout . setOrderedOffset ( startAt ) ; } innerLayout . addField ( "Test " + String . valueOf ( startAt > 1 ? startAt : 1 ) , new WTextField ( ) ) ; innerLayout . addField ( "Test " + String . valueOf ( startAt > 1 ? startAt + 1 : 2 ) , new WTextField ( ) ) ; innerLayout . addField ( "Test " + String . valueOf ( startAt > 1 ? startAt + 2 : 2 ) , new WTextField ( ) ) ; if ( curr < 4 ) { int next = curr + 1 ; innerLayout . addField ( "indent level " + String . valueOf ( next ) , recursiveFieldLayout ( next , 0 ) ) ; } innerLayout . addField ( "Test after nest" , new WTextField ( ) ) ; return innerLayout ; }
Create a recursive field layout .
289
6
18,898
protected void handleFileUploadRequest ( final WMultiFileWidget widget , final XmlStringBuilder xml , final String uploadId ) { FileWidgetUpload file = widget . getFile ( uploadId ) ; if ( file == null ) { throw new SystemException ( "Invalid file id [" + uploadId + "] to render uploaded response." ) ; } int idx = widget . getFiles ( ) . indexOf ( file ) ; FileWidgetRendererUtil . renderFileElement ( widget , xml , file , idx ) ; }
Paint the response for the file uploaded in this request .
112
12
18,899
private String typesToString ( final List < String > types ) { if ( types == null || types . isEmpty ( ) ) { return null ; } StringBuffer typesString = new StringBuffer ( ) ; for ( Iterator < String > iter = types . iterator ( ) ; iter . hasNext ( ) ; ) { typesString . append ( iter . next ( ) ) ; if ( iter . hasNext ( ) ) { typesString . append ( ' ' ) ; } } return typesString . toString ( ) ; }
Flattens the list of accepted mime types into a format suitable for rendering .
110
17