idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
18,600
public RatingValuesMap getAllRatings ( Reference reference ) { return getResourceFactory ( ) . getApiResource ( "/rating/" + reference . toURLFragment ( ) ) . get ( RatingValuesMap . class ) ; }
Returns all the ratings for the given object . It will only return the ratings that are enabled for the object .
49
22
18,601
public int getRating ( Reference reference , RatingType type , int userId ) { return getResourceFactory ( ) . getApiResource ( "/rating/" + reference . toURLFragment ( ) + type + "/" + userId ) . get ( SingleRatingValue . class ) . getValue ( ) ; }
Returns the rating value for the given rating type object and user .
66
13
18,602
private String getMenuType ( final WSubMenu submenu ) { WMenu menu = WebUtilities . getAncestorOfClass ( WMenu . class , submenu ) ; switch ( menu . getType ( ) ) { case BAR : return "bar" ; case FLYOUT : return "flyout" ; case TREE : return "tree" ; case COLUMN : return "column" ; default : throw new IllegalStateException ( "Invalid menu type: " + menu . getType ( ) ) ; } }
Get the string value of a WMenu . MenuType .
111
12
18,603
@ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WSubMenu menu = ( WSubMenu ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; xml . appendTagOpen ( "ui:submenu" ) ; xml . appendAttribute ( "id" , component . getId ( ) ) ; xml . appendOptionalAttribute ( "class" , component . getHtmlClass ( ) ) ; xml . appendOptionalAttribute ( "track" , component . isTracking ( ) , "true" ) ; if ( isTree ( menu ) ) { xml . appendAttribute ( "open" , String . valueOf ( isOpen ( menu ) ) ) ; } xml . appendOptionalAttribute ( "disabled" , menu . isDisabled ( ) , "true" ) ; xml . appendOptionalAttribute ( "hidden" , menu . isHidden ( ) , "true" ) ; if ( menu . isTopLevelMenu ( ) ) { xml . appendOptionalAttribute ( "accessKey" , menu . getAccessKeyAsString ( ) ) ; } else { xml . appendAttribute ( "nested" , "true" ) ; } xml . appendOptionalAttribute ( "type" , getMenuType ( menu ) ) ; switch ( menu . getMode ( ) ) { case CLIENT : xml . appendAttribute ( "mode" , "client" ) ; break ; case LAZY : xml . appendAttribute ( "mode" , "lazy" ) ; break ; case EAGER : xml . appendAttribute ( "mode" , "eager" ) ; break ; case DYNAMIC : case SERVER : // mode server mapped to mode dynamic as per https://github.com/BorderTech/wcomponents/issues/687 xml . appendAttribute ( "mode" , "dynamic" ) ; break ; default : throw new SystemException ( "Unknown menu mode: " + menu . getMode ( ) ) ; } xml . appendClose ( ) ; // Paint label menu . getDecoratedLabel ( ) . paint ( renderContext ) ; MenuMode mode = menu . getMode ( ) ; // Paint submenu items xml . appendTagOpen ( "ui:content" ) ; xml . appendAttribute ( "id" , component . getId ( ) + "-content" ) ; xml . appendClose ( ) ; // Render content if not EAGER Mode or is EAGER and is the current AJAX request if ( mode != MenuMode . EAGER || AjaxHelper . isCurrentAjaxTrigger ( menu ) ) { // Visibility of content set in prepare paint menu . paintMenuItems ( renderContext ) ; } xml . appendEndTag ( "ui:content" ) ; xml . appendEndTag ( "ui:submenu" ) ; }
Paints the given WSubMenu .
596
8
18,604
@ Override protected List getNewSelections ( final Request request ) { List selections = super . getNewSelections ( request ) ; if ( selections != null ) { // Ensure that there are no duplicates for ( int i = 0 ; i < selections . size ( ) ; i ++ ) { Object selection = selections . get ( i ) ; for ( int j = i + 1 ; j < selections . size ( ) ; j ++ ) { if ( Util . equals ( selection , selections . get ( j ) ) ) { selections . remove ( j -- ) ; } } } } return selections ; }
Override getNewSelections to ensure that the max number of inputs is honoured and that there are no duplicates . This should not normally occur as the client side js should prevent it .
127
37
18,605
public static String rowIndexListToString ( final List < Integer > row ) { if ( row == null || row . isEmpty ( ) ) { return null ; } StringBuffer index = new StringBuffer ( ) ; boolean addDelimiter = false ; for ( Integer lvl : row ) { if ( addDelimiter ) { index . append ( INDEX_DELIMITER ) ; } index . append ( lvl ) ; addDelimiter = true ; } return index . toString ( ) ; }
Convert the row index to its string representation .
108
10
18,606
public static List < Integer > rowIndexStringToList ( final String row ) { if ( row == null ) { return null ; } List < Integer > rowIndex = new ArrayList <> ( ) ; try { // Convert StringId to array String [ ] rowIdString = row . split ( INDEX_DELIMITER ) ; for ( int i = 0 ; i < rowIdString . length ; i ++ ) { rowIndex . add ( Integer . parseInt ( rowIdString [ i ] ) ) ; } } catch ( NumberFormatException e ) { LOG . warn ( "Invalid row id: " + row ) ; } return rowIndex ; }
Convert the string representation of a row index to a list .
140
13
18,607
public static void sortData ( final Object [ ] data , final Comparator < Object > comparator , final boolean ascending , final int lowIndex , final int highIndex , final int [ ] sortIndices ) { if ( lowIndex >= highIndex ) { return ; // 1 element, so sorted already! } Object midValue = data [ sortIndices [ ( lowIndex + highIndex ) >>> 1 ] ] ; int i = lowIndex - 1 ; int j = highIndex + 1 ; int sign = ascending ? 1 : - 1 ; for ( ; ; ) { do { i ++ ; } while ( comparator . compare ( data [ sortIndices [ i ] ] , midValue ) * sign < 0 ) ; do { j -- ; } while ( comparator . compare ( data [ sortIndices [ j ] ] , midValue ) * sign > 0 ) ; if ( i >= j ) { break ; // crossover, good! } // Out of order - swap! int temp = sortIndices [ i ] ; sortIndices [ i ] = sortIndices [ j ] ; sortIndices [ j ] = temp ; } // now determine the split point... if ( i > j ) { i = j ; } sortData ( data , comparator , ascending , lowIndex , i , sortIndices ) ; sortData ( data , comparator , ascending , i + 1 , highIndex , sortIndices ) ; }
Sorts the data using the given comparator using a quick - sort .
300
15
18,608
private static Date parse ( final String dateString ) { try { return new SimpleDateFormat ( "dd/mm/yyyy" ) . parse ( dateString ) ; } catch ( ParseException e ) { LOG . error ( "Error parsing date: " + dateString , e ) ; return null ; } }
Parses a date string .
66
7
18,609
private TableDataModel createTableModel ( ) { return new AbstractTableDataModel ( ) { /** * Column id for the first name column. */ private static final int FIRST_NAME = 0 ; /** * Column id for the last name column. */ private static final int LAST_NAME = 1 ; /** * Column id for the date of birth column. */ private static final int DOB = 2 ; /** * Column id for the action column. */ private static final int BUTTON = 3 ; private final List < Person > data = Arrays . asList ( new Person [ ] { new Person ( 123 , "Joe" , "Bloggs" , parse ( "01/02/1973" ) ) , new Person ( 456 , "Jane" , "Bloggs" , parse ( "04/05/1976" ) ) , new Person ( 789 , "Kid" , "Bloggs" , parse ( "31/12/1999" ) ) } ) ; /** * {@inheritDoc} */ @ Override public Object getValueAt ( final int row , final int col ) { Person person = data . get ( row ) ; switch ( col ) { case FIRST_NAME : return person . getFirstName ( ) ; case LAST_NAME : return person . getLastName ( ) ; case DOB : { if ( person . getDateOfBirth ( ) == null ) { return null ; } return person . getDateOfBirth ( ) ; } case BUTTON : { return person ; } default : return null ; } } /** * {@inheritDoc} */ @ Override public int getRowCount ( ) { return data . size ( ) ; } } ; }
Creates a table data model containing some dummy person data .
358
12
18,610
public static void addAllHeadlines ( final PrintWriter writer , final Headers headers ) { PageContentHelper . addHeadlines ( writer , headers . getHeadLines ( ) ) ; PageContentHelper . addJsHeadlines ( writer , headers . getHeadLines ( Headers . JAVASCRIPT_HEADLINE ) ) ; PageContentHelper . addCssHeadlines ( writer , headers . getHeadLines ( Headers . CSS_HEADLINE ) ) ; }
Shortcut method for adding all the headline entries stored in the WHeaders .
101
16
18,611
private void paintAjax ( final WButton button , final XmlStringBuilder xml ) { // Start tag xml . appendTagOpen ( "ui:ajaxtrigger" ) ; xml . appendAttribute ( "triggerId" , button . getId ( ) ) ; xml . appendClose ( ) ; // Target xml . appendTagOpen ( "ui:ajaxtargetid" ) ; xml . appendAttribute ( "targetId" , button . getAjaxTarget ( ) . getId ( ) ) ; xml . appendEnd ( ) ; // End tag xml . appendEndTag ( "ui:ajaxtrigger" ) ; }
Paints the AJAX information for the given WButton .
135
12
18,612
@ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WDialog dialog = ( WDialog ) component ; int state = dialog . getState ( ) ; if ( state == WDialog . ACTIVE_STATE || dialog . getTrigger ( ) != null ) { int width = dialog . getWidth ( ) ; int height = dialog . getHeight ( ) ; String title = dialog . getTitle ( ) ; XmlStringBuilder xml = renderContext . getWriter ( ) ; xml . appendTagOpen ( "ui:dialog" ) ; xml . appendAttribute ( "id" , component . getId ( ) ) ; xml . appendOptionalAttribute ( "class" , component . getHtmlClass ( ) ) ; xml . appendOptionalAttribute ( "track" , component . isTracking ( ) , "true" ) ; xml . appendOptionalAttribute ( "width" , width > 0 , width ) ; xml . appendOptionalAttribute ( "height" , height > 0 , height ) ; xml . appendOptionalAttribute ( "modal" , dialog . getMode ( ) == WDialog . MODAL , "true" ) ; xml . appendOptionalAttribute ( "open" , dialog . getState ( ) == WDialog . ACTIVE_STATE , "true" ) ; xml . appendOptionalAttribute ( "title" , title ) ; DialogOpenTrigger trigger = dialog . getTrigger ( ) ; if ( trigger != null ) { xml . appendOptionalAttribute ( "triggerid" , trigger . getId ( ) ) ; if ( dialog . hasLegacyTriggerButton ( ) ) { xml . appendClose ( ) ; trigger . paint ( renderContext ) ; xml . appendEndTag ( "ui:dialog" ) ; } else { xml . appendEnd ( ) ; } } else { xml . appendEnd ( ) ; } } }
Paints the given WDialog .
394
7
18,613
@ Override public void paint ( final RenderContext renderContext ) { if ( ! DebugUtil . isDebugFeaturesEnabled ( ) || ! ( renderContext instanceof WebXmlRenderContext ) ) { getBackingComponent ( ) . paint ( renderContext ) ; return ; } AjaxOperation operation = AjaxHelper . getCurrentOperation ( ) ; if ( operation == null ) { getBackingComponent ( ) . paint ( renderContext ) ; return ; } getBackingComponent ( ) . paint ( renderContext ) ; XmlStringBuilder xml = ( ( WebXmlRenderContext ) renderContext ) . getWriter ( ) ; xml . appendTag ( "ui:debug" ) ; for ( String targetId : operation . getTargets ( ) ) { ComponentWithContext target = WebUtilities . getComponentById ( targetId , true ) ; if ( target != null ) { writeDebugInfo ( target . getComponent ( ) , xml ) ; } } xml . appendEndTag ( "ui:debug" ) ; }
Override paint to only output the debugging info for the current targets .
214
13
18,614
public void setParameter ( final String key , final String value ) { parameters . put ( key , new String [ ] { value } ) ; }
Sets a parameter .
30
5
18,615
public void addParameterForButton ( final UIContext uic , final WButton button ) { UIContextHolder . pushContext ( uic ) ; try { setParameter ( button . getId ( ) , "x" ) ; } finally { UIContextHolder . popContext ( ) ; } }
Convenience method that adds a parameter emulating a button press .
69
14
18,616
public void setFileContents ( final String key , final byte [ ] contents ) { MockFileItem fileItem = new MockFileItem ( ) ; fileItem . set ( contents ) ; files . put ( key , new FileItem [ ] { fileItem } ) ; }
Sets mock file upload contents .
56
7
18,617
private void addMessage ( final WMessageBox box , final Message message , final boolean encode ) { String code = message . getMessage ( ) ; if ( ! Util . empty ( code ) ) { box . addMessage ( encode , code , message . getArgs ( ) ) ; } }
Convenience method to add a message to a message box .
61
13
18,618
protected static MessageContainer getMessageContainer ( final WComponent component ) { for ( WComponent c = component ; c != null ; c = c . getParent ( ) ) { if ( c instanceof MessageContainer ) { return ( MessageContainer ) c ; } } return null ; }
Searches the WComponent tree of the given component for an ancestor that implements the MessageContainer interface .
58
21
18,619
public int addItem ( int appId , ItemCreate create , boolean silent ) { return getResourceFactory ( ) . getApiResource ( "/item/app/" + appId + "/" ) . queryParam ( "silent" , silent ? "1" : "0" ) . entity ( create , MediaType . APPLICATION_JSON_TYPE ) . post ( ItemCreateResponse . class ) . getId ( ) ; }
Adds a new item to the given app .
91
9
18,620
public void updateItem ( int itemId , ItemUpdate update , boolean silent , boolean hook ) { getResourceFactory ( ) . getApiResource ( "/item/" + itemId ) . queryParam ( "silent" , silent ? "1" : "0" ) . queryParam ( "hook" , hook ? "1" : "0" ) . entity ( update , MediaType . APPLICATION_JSON_TYPE ) . put ( ) ; }
Updates the entire item . Only fields which have values specified will be updated . To delete the contents of a field pass an empty array for the value .
96
31
18,621
public void updateItemValues ( int itemId , List < FieldValuesUpdate > values , boolean silent , boolean hook ) { getResourceFactory ( ) . getApiResource ( "/item/" + itemId + "/value/" ) . queryParam ( "silent" , silent ? "1" : "0" ) . queryParam ( "hook" , hook ? "1" : "0" ) . entity ( values , MediaType . APPLICATION_JSON_TYPE ) . put ( ) ; }
Updates all the values for an item
105
8
18,622
public void updateItemFieldValues ( int itemId , int fieldId , List < Map < String , Object > > values , boolean silent , boolean hook ) { getResourceFactory ( ) . getApiResource ( "/item/" + itemId + "/value/" + fieldId ) . queryParam ( "silent" , silent ? "1" : "0" ) . queryParam ( "hook" , hook ? "1" : "0" ) . entity ( values , MediaType . APPLICATION_JSON_TYPE ) . put ( ) ; }
Update the item values for a specific field .
116
9
18,623
public List < Map < String , Object > > getItemFieldValues ( int itemId , int fieldId ) { return getResourceFactory ( ) . getApiResource ( "/item/" + itemId + "/value/" + fieldId ) . get ( new GenericType < List < Map < String , Object > > > ( ) { } ) ; }
Returns the values for a specified field on an item
74
10
18,624
public List < FieldValuesView > getItemValues ( int itemId ) { return getResourceFactory ( ) . getApiResource ( "/item/" + itemId + "/value/" ) . get ( new GenericType < List < FieldValuesView > > ( ) { } ) ; }
Returns all the values for an item with the additional data provided by the get item operation .
60
18
18,625
public List < ItemMini > getItemsByFieldAndTitle ( int fieldId , String text , List < Integer > notItemIds , Integer limit ) { WebResource resource = getResourceFactory ( ) . getApiResource ( "/item/field/" + fieldId + "/find" ) ; if ( limit != null ) { resource = resource . queryParam ( "limit" , limit . toString ( ) ) ; } if ( notItemIds != null && notItemIds . size ( ) > 0 ) { resource = resource . queryParam ( "not_item_id" , ToStringUtil . toString ( notItemIds , "," ) ) ; } resource = resource . queryParam ( "text" , text ) ; return resource . get ( new GenericType < List < ItemMini > > ( ) { } ) ; }
Used to find possible items for a given application field . It searches the relevant items for the title given .
180
21
18,626
public List < ItemReference > getItemReference ( int itemId ) { return getResourceFactory ( ) . getApiResource ( "/item/" + itemId + "/reference/" ) . get ( new GenericType < List < ItemReference > > ( ) { } ) ; }
Returns the items that have a reference to the given item . The references are grouped by app . Both the apps and the items are sorted by title .
58
30
18,627
public ItemRevision getItemRevision ( int itemId , int revisionId ) { return getResourceFactory ( ) . getApiResource ( "/item/" + itemId + "/revision/" + revisionId ) . get ( ItemRevision . class ) ; }
Returns the data about the specific revision on an item
56
10
18,628
public List < ItemFieldDifference > getItemRevisionDifference ( int itemId , int revisionFrom , int revisionTo ) { return getResourceFactory ( ) . getApiResource ( "/item/" + itemId + "/revision/" + revisionFrom + "/" + revisionTo ) . get ( new GenericType < List < ItemFieldDifference > > ( ) { } ) ; }
Returns the difference in fields values between the two revisions .
83
11
18,629
public List < ItemRevision > getItemRevisions ( int itemId ) { return getResourceFactory ( ) . getApiResource ( "/item/" + itemId + "/revision/" ) . get ( new GenericType < List < ItemRevision > > ( ) { } ) ; }
Returns all the revisions that have been made to an item
62
11
18,630
public ItemsResponse getItems ( int appId , Integer limit , Integer offset , SortBy sortBy , Boolean sortDesc , FilterByValue < ? > ... filters ) { WebResource resource = getResourceFactory ( ) . getApiResource ( "/item/app/" + appId + "/v2/" ) ; if ( limit != null ) { resource = resource . queryParam ( "limit" , limit . toString ( ) ) ; } if ( offset != null ) { resource = resource . queryParam ( "offset" , offset . toString ( ) ) ; } if ( sortBy != null ) { resource = resource . queryParam ( "sort_by" , sortBy . getKey ( ) ) ; } if ( sortDesc != null ) { resource = resource . queryParam ( "sort_desc" , sortDesc ? "1" : "0" ) ; } for ( FilterByValue < ? > filter : filters ) { resource = resource . queryParam ( filter . getBy ( ) . getKey ( ) , filter . getFormattedValue ( ) ) ; } return resource . get ( ItemsResponse . class ) ; }
Returns the items on app matching the given filters .
239
10
18,631
public ItemsResponse getItemsByExternalId ( int appId , String externalId ) { return getItems ( appId , null , null , null , null , new FilterByValue < String > ( new ExternalIdFilterBy ( ) , externalId ) ) ; }
Utility method to get items matching an external id
55
10
18,632
@ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WAjaxControl ajaxControl = ( WAjaxControl ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; WComponent trigger = ajaxControl . getTrigger ( ) == null ? ajaxControl : ajaxControl . getTrigger ( ) ; int delay = ajaxControl . getDelay ( ) ; if ( ajaxControl . getTargets ( ) == null || ajaxControl . getTargets ( ) . isEmpty ( ) ) { return ; } // Start tag xml . appendTagOpen ( "ui:ajaxtrigger" ) ; xml . appendAttribute ( "triggerId" , trigger . getId ( ) ) ; xml . appendOptionalAttribute ( "loadOnce" , ajaxControl . isLoadOnce ( ) , "true" ) ; xml . appendOptionalAttribute ( "delay" , delay > 0 , delay ) ; xml . appendClose ( ) ; // Targets for ( AjaxTarget target : ajaxControl . getTargets ( ) ) { xml . appendTagOpen ( "ui:ajaxtargetid" ) ; xml . appendAttribute ( "targetId" , target . getId ( ) ) ; xml . appendEnd ( ) ; } // End tag xml . appendEndTag ( "ui:ajaxtrigger" ) ; }
Paints the given AjaxControl .
308
7
18,633
public void setNameAction ( final Action action ) { LinkComponent linkComponent = new LinkComponent ( ) ; linkComponent . setNameAction ( action ) ; repeater . setRepeatedComponent ( linkComponent ) ; }
Sets the action to execute when the name link is invoked .
45
13
18,634
protected Object getNewSelection ( final Request request ) { String paramValue = request . getParameter ( getId ( ) ) ; if ( paramValue == null ) { return null ; } // Figure out which option has been selected. List < ? > options = getOptions ( ) ; if ( options == null || options . isEmpty ( ) ) { if ( ! isEditable ( ) ) { // User could not have made a selection. return null ; } options = Collections . EMPTY_LIST ; } int optionIndex = 0 ; for ( Object option : options ) { if ( option instanceof OptionGroup ) { List < ? > groupOptions = ( ( OptionGroup ) option ) . getOptions ( ) ; if ( groupOptions != null ) { for ( Object nestedOption : groupOptions ) { if ( paramValue . equals ( optionToCode ( nestedOption , optionIndex ++ ) ) ) { return nestedOption ; } } } } else if ( paramValue . equals ( optionToCode ( option , optionIndex ++ ) ) ) { return option ; } } // Option not found, but if editable, user entered text if ( isEditable ( ) ) { return paramValue ; } // Invalid option. Ignore and use the current selection LOG . warn ( "Option \"" + paramValue + "\" on the request is not a valid option. Will be ignored." ) ; Object currentOption = getValue ( ) ; return currentOption ; }
Determines which selection has been included in the given request .
302
13
18,635
public static Object pipe ( final Object in ) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; ObjectOutputStream os = new ObjectOutputStream ( bos ) ; os . writeObject ( in ) ; os . close ( ) ; byte [ ] bytes = bos . toByteArray ( ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( bytes ) ; ObjectInputStream is = new ObjectInputStream ( bis ) ; Object out = is . readObject ( ) ; return out ; } catch ( Exception ex ) { throw new SystemException ( "Failed to pipe " + in , ex ) ; } }
Takes a copy of an input object via serialization .
133
12
18,636
public void markAsViewed ( int notificationId ) { getResourceFactory ( ) . getApiResource ( "/notification/" + notificationId + "/viewed" ) . entity ( new Empty ( ) , MediaType . APPLICATION_JSON_TYPE ) . post ( ) ; }
Mark the notification as viewed . This will move the notification from the inbox to the viewed archive .
60
19
18,637
@ Override protected void afterPaint ( final RenderContext renderContext ) { if ( renderContext instanceof WebXmlRenderContext ) { PrintWriter writer = ( ( WebXmlRenderContext ) renderContext ) . getWriter ( ) ; writer . println ( WebUtilities . encode ( message ) ) ; if ( error != null ) { writer . println ( "\n<br/>\n<pre>\n" ) ; StringWriter buf = new StringWriter ( ) ; error . printStackTrace ( new PrintWriter ( buf ) ) ; writer . println ( WebUtilities . encode ( buf . toString ( ) ) ) ; writer . println ( "\n</pre>" ) ; } } }
Override in order to paint the component . Real applications should not emit HTML directly .
148
16
18,638
protected void serviceInt ( final HttpServletRequest request , final HttpServletResponse response ) throws ServletException , IOException { // Check for resource request boolean continueProcess = ServletUtil . checkResourceRequest ( request , response ) ; if ( ! continueProcess ) { return ; } // Create a support class to coordinate the web request. WServletHelper helper = createServletHelper ( request , response ) ; // Get the interceptors that will be used to plug in features. InterceptorComponent interceptorChain = createInterceptorChain ( request ) ; // Get the WComponent that represents the application we are serving. WComponent ui = getUI ( request ) ; ServletUtil . processRequest ( helper , ui , interceptorChain ) ; }
Service internal . This method does the real work in servicing the http request . It integrates wcomponents into a servlet environment via a servlet specific helper class .
161
33
18,639
protected WServletHelper createServletHelper ( final HttpServletRequest httpServletRequest , final HttpServletResponse httpServletResponse ) { LOG . debug ( "Creating a new WServletHelper instance" ) ; WServletHelper helper = new WServletHelper ( this , httpServletRequest , httpServletResponse ) ; return helper ; }
Create a support class to coordinate the web request .
78
10
18,640
@ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WPanel panel = ( WPanel ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; WButton submitButton = panel . getDefaultSubmitButton ( ) ; String submitId = submitButton == null ? null : submitButton . getId ( ) ; String titleText = panel . getTitleText ( ) ; boolean renderChildren = isRenderContent ( panel ) ; xml . appendTagOpen ( "ui:panel" ) ; xml . appendAttribute ( "id" , component . getId ( ) ) ; xml . appendOptionalAttribute ( "class" , component . getHtmlClass ( ) ) ; xml . appendOptionalAttribute ( "track" , component . isTracking ( ) , "true" ) ; if ( PanelMode . LAZY . equals ( panel . getMode ( ) ) ) { xml . appendOptionalAttribute ( "hidden" , ! renderChildren , "true" ) ; } else { xml . appendOptionalAttribute ( "hidden" , component . isHidden ( ) , "true" ) ; } xml . appendOptionalAttribute ( "buttonId" , submitId ) ; xml . appendOptionalAttribute ( "title" , titleText ) ; xml . appendOptionalAttribute ( "accessKey" , Util . upperCase ( panel . getAccessKeyAsString ( ) ) ) ; xml . appendOptionalAttribute ( "type" , getPanelType ( panel ) ) ; xml . appendOptionalAttribute ( "mode" , getPanelMode ( panel ) ) ; xml . appendClose ( ) ; // Render margin MarginRendererUtil . renderMargin ( panel , renderContext ) ; if ( renderChildren ) { renderChildren ( panel , renderContext ) ; } else { // Content will be loaded via AJAX xml . append ( "<ui:content/>" ) ; } xml . appendEndTag ( "ui:panel" ) ; }
Paints the given container .
416
6
18,641
@ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WSubordinateControl subordinate = ( WSubordinateControl ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; if ( ! subordinate . getRules ( ) . isEmpty ( ) ) { int seq = 0 ; for ( Rule rule : subordinate . getRules ( ) ) { xml . appendTagOpen ( "ui:subordinate" ) ; xml . appendAttribute ( "id" , subordinate . getId ( ) + "-c" + seq ++ ) ; xml . appendClose ( ) ; paintRule ( rule , xml ) ; xml . appendEndTag ( "ui:subordinate" ) ; } } }
Paints the given SubordinateControl .
155
8
18,642
private void paintRule ( final Rule rule , final XmlStringBuilder xml ) { if ( rule . getCondition ( ) == null ) { throw new SystemException ( "Rule cannot be painted as it has no condition" ) ; } paintCondition ( rule . getCondition ( ) , xml ) ; for ( Action action : rule . getOnTrue ( ) ) { paintAction ( action , "ui:onTrue" , xml ) ; } for ( Action action : rule . getOnFalse ( ) ) { paintAction ( action , "ui:onFalse" , xml ) ; } }
Paints a single rule .
122
6
18,643
private void paintCondition ( final Condition condition , final XmlStringBuilder xml ) { if ( condition instanceof And ) { xml . appendTag ( "ui:and" ) ; for ( Condition operand : ( ( And ) condition ) . getConditions ( ) ) { paintCondition ( operand , xml ) ; } xml . appendEndTag ( "ui:and" ) ; } else if ( condition instanceof Or ) { xml . appendTag ( "ui:or" ) ; for ( Condition operand : ( ( Or ) condition ) . getConditions ( ) ) { paintCondition ( operand , xml ) ; } xml . appendEndTag ( "ui:or" ) ; } else if ( condition instanceof Not ) { xml . appendTag ( "ui:not" ) ; paintCondition ( ( ( Not ) condition ) . getCondition ( ) , xml ) ; xml . appendEndTag ( "ui:not" ) ; } else if ( condition instanceof AbstractCompare ) { AbstractCompare compare = ( AbstractCompare ) condition ; xml . appendTagOpen ( "ui:condition" ) ; xml . appendAttribute ( "controller" , compare . getTrigger ( ) . getId ( ) ) ; xml . appendAttribute ( "value" , compare . getComparePaintValue ( ) ) ; xml . appendOptionalAttribute ( "operator" , getCompareTypeName ( compare . getCompareType ( ) ) ) ; xml . appendEnd ( ) ; } else { throw new SystemException ( "Unknown condition: " + condition ) ; } }
Paints a condition .
325
5
18,644
private void paintAction ( final Action action , final String elementName , final XmlStringBuilder xml ) { switch ( action . getActionType ( ) ) { case SHOW : case HIDE : case ENABLE : case DISABLE : case OPTIONAL : case MANDATORY : paintStandardAction ( action , elementName , xml ) ; break ; case SHOWIN : case HIDEIN : case ENABLEIN : case DISABLEIN : paintInGroupAction ( action , elementName , xml ) ; break ; default : break ; } }
Paints an action .
115
5
18,645
private void paintStandardAction ( final Action action , final String elementName , final XmlStringBuilder xml ) { xml . appendTagOpen ( elementName ) ; xml . appendAttribute ( "action" , getActionTypeName ( action . getActionType ( ) ) ) ; xml . appendClose ( ) ; xml . appendTagOpen ( "ui:target" ) ; SubordinateTarget target = action . getTarget ( ) ; if ( target instanceof WComponentGroup < ? > ) { xml . appendAttribute ( "groupId" , target . getId ( ) ) ; } else { xml . appendAttribute ( "id" , target . getId ( ) ) ; } xml . appendEnd ( ) ; xml . appendEndTag ( elementName ) ; }
Paint a standard action - where a single item or single group is targeted .
159
16
18,646
private void paintInGroupAction ( final Action action , final String elementName , final XmlStringBuilder xml ) { xml . appendTagOpen ( elementName ) ; xml . appendAttribute ( "action" , getActionTypeName ( action . getActionType ( ) ) ) ; xml . appendClose ( ) ; xml . appendTagOpen ( "ui:target" ) ; xml . appendAttribute ( "groupId" , action . getTarget ( ) . getId ( ) ) ; xml . appendAttribute ( "id" , ( ( AbstractAction ) action ) . getTargetInGroup ( ) . getId ( ) ) ; xml . appendEnd ( ) ; xml . appendEndTag ( elementName ) ; }
Paint an inGroup action - where a single item is being targeted out of a group of items .
149
21
18,647
private String getCompareTypeName ( final CompareType type ) { String compare = null ; switch ( type ) { case EQUAL : break ; case NOT_EQUAL : compare = "ne" ; break ; case LESS_THAN : compare = "lt" ; break ; case LESS_THAN_OR_EQUAL : compare = "le" ; break ; case GREATER_THAN : compare = "gt" ; break ; case GREATER_THAN_OR_EQUAL : compare = "ge" ; break ; case MATCH : compare = "rx" ; break ; default : throw new SystemException ( "Invalid compare type: " + type ) ; } return compare ; }
Helper method to determine the compare type name .
150
9
18,648
private String getActionTypeName ( final ActionType type ) { String action = null ; switch ( type ) { case SHOW : action = "show" ; break ; case SHOWIN : action = "showIn" ; break ; case HIDE : action = "hide" ; break ; case HIDEIN : action = "hideIn" ; break ; case ENABLE : action = "enable" ; break ; case ENABLEIN : action = "enableIn" ; break ; case DISABLE : action = "disable" ; break ; case DISABLEIN : action = "disableIn" ; break ; case OPTIONAL : action = "optional" ; break ; case MANDATORY : action = "mandatory" ; break ; default : break ; } return action ; }
Helper method to determine the action name .
164
8
18,649
private void buildUI ( ) { add ( messages ) ; add ( tabset ) ; // add(new AccessibilityWarningContainer()); container . add ( new WText ( "Select an example from the menu" ) ) ; // Set a static ID on container and it becomes a de-facto naming context. container . setIdName ( "eg" ) ; tabset . addTab ( container , "(no selection)" , WTabSet . TAB_MODE_CLIENT ) ; WImage srcImage = new WImage ( new ImageResource ( "/image/text-x-source.png" , "View Source" ) ) ; srcImage . setCacheKey ( "srcTabImage" ) ; tabset . addTab ( source , new WDecoratedLabel ( srcImage ) , WTabSet . TAB_MODE_LAZY ) . setToolTip ( "View Source" ) ; // The refresh current view button. WButton refreshButton = new WButton ( "\u200b" ) ; refreshButton . setToolTip ( "Refresh" ) ; refreshButton . setHtmlClass ( HtmlIconUtil . getIconClasses ( "fa-refresh" ) ) ; //refreshButton.setImage("/image/refresh-w.png"); refreshButton . setRenderAsLink ( true ) ; refreshButton . setAction ( new ValidatingAction ( messages . getValidationErrors ( ) , refreshButton ) { @ Override public void executeOnValid ( final ActionEvent event ) { // Do Nothing } } ) ; // The reset example button. final WButton resetButton = new WButton ( "\u200b" ) ; resetButton . setToolTip ( "Reset" ) ; resetButton . setHtmlClass ( HtmlIconUtil . getIconClasses ( "fa-times-circle" ) ) ; //resetButton.setImage("/image/cancel-w.png"); resetButton . setRenderAsLink ( true ) ; resetButton . setAction ( new ValidatingAction ( messages . getValidationErrors ( ) , resetButton ) { @ Override public void executeOnValid ( final ActionEvent event ) { resetExample ( ) ; } } ) ; addToTail ( refreshButton ) ; addToTail ( new WText ( "\u2002" ) ) ; addToTail ( resetButton ) ; }
Add the controls to the section in the right order .
507
11
18,650
private void addToTail ( final WComponent component ) { WContainer tail = ( WContainer ) getDecoratedLabel ( ) . getTail ( ) ; if ( null != tail ) { // bloody well better not be... tail . add ( component ) ; } }
Add a component to the WDecoratedLabel s tail container .
58
14
18,651
public void selectExample ( final WComponent example , final String exampleName ) { WComponent currentExample = container . getChildAt ( 0 ) . getParent ( ) ; if ( currentExample != null && currentExample . getClass ( ) . equals ( example . getClass ( ) ) ) { // Same example selected, do nothing return ; } resetExample ( ) ; container . removeAll ( ) ; this . getDecoratedLabel ( ) . setBody ( new WText ( exampleName ) ) ; WApplication app = WebUtilities . getAncestorOfClass ( WApplication . class , this ) ; if ( app != null ) { app . setTitle ( exampleName ) ; } if ( example instanceof ErrorComponent ) { tabset . getTab ( 0 ) . setText ( "Error" ) ; source . setSource ( null ) ; } else { String className = example . getClass ( ) . getName ( ) ; WDefinitionList list = new WDefinitionList ( WDefinitionList . Type . COLUMN ) ; container . add ( list ) ; list . addTerm ( "Example path" , new WText ( className . replaceAll ( "\\." , " / " ) ) ) ; list . addTerm ( "Example JavaDoc" , new JavaDocText ( getSource ( className ) ) ) ; container . add ( new WHorizontalRule ( ) ) ; tabset . getTab ( 0 ) . setText ( example . getClass ( ) . getSimpleName ( ) ) ; source . setSource ( getSource ( className ) ) ; } container . add ( example ) ; example . setLocked ( true ) ; }
Selects an example .
352
5
18,652
public void selectExample ( final ExampleData example ) { try { StringBuilder exampleName = new StringBuilder ( ) ; if ( example . getExampleGroupName ( ) != null && ! example . getExampleGroupName ( ) . equals ( "" ) ) { exampleName . append ( example . getExampleGroupName ( ) ) . append ( " - " ) ; } exampleName . append ( example . getExampleName ( ) ) ; selectExample ( example . getExampleClass ( ) . newInstance ( ) , exampleName . toString ( ) ) ; } catch ( Exception e ) { WMessages . getInstance ( this ) . error ( "Error selecting example \"" + example . getExampleName ( ) + ' ' ) ; selectExample ( new ErrorComponent ( e . getMessage ( ) , e ) , "Error" ) ; } }
Selects an example . If there is an error instantiating the component an error message will be displayed .
177
21
18,653
private static String getSource ( final String className ) { String sourceName = ' ' + className . replace ( ' ' , ' ' ) + ".java" ; InputStream stream = null ; try { stream = ExampleSection . class . getResourceAsStream ( sourceName ) ; if ( stream != null ) { byte [ ] sourceBytes = StreamUtil . getBytes ( stream ) ; // we need to do some basic formatting of the source now. return new String ( sourceBytes , "UTF-8" ) ; } } catch ( IOException e ) { LOG . warn ( "Unable to read source code for class " + className , e ) ; } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( IOException e ) { LOG . error ( "Error closing stream" , e ) ; } } } return null ; }
Tries to obtain the source file for the given class .
185
12
18,654
protected String optionToCode ( final Object option , final int index ) { if ( index < 0 ) { List < ? > options = getOptions ( ) ; if ( options == null || options . isEmpty ( ) ) { Integrity . issue ( this , "No options available, so cannot convert the option \"" + option + "\" to a code." ) ; } else { StringBuffer message = new StringBuffer ( ) ; message . append ( "The option \"" ) . append ( option ) . append ( "\" is not one of the available options." ) ; Object firstOption = SelectListUtil . getFirstOption ( options ) ; if ( firstOption != null && option != null && firstOption . getClass ( ) != option . getClass ( ) ) { message . append ( " The options in this list component are of type \"" ) ; message . append ( firstOption . getClass ( ) . getName ( ) ) . append ( "\", the selection you supplied is of type \"" ) ; message . append ( option . getClass ( ) . getName ( ) ) . append ( "\"." ) ; } Integrity . issue ( this , message . toString ( ) ) ; } return null ; } else if ( option instanceof Option ) { Option opt = ( Option ) option ; return opt . getCode ( ) == null ? "" : opt . getCode ( ) ; } else { String code = APPLICATION_LOOKUP_TABLE . getCode ( getLookupTable ( ) , option ) ; if ( code == null ) { return String . valueOf ( index + 1 ) ; } else { return code ; } } }
Retrieves the code for the given option . Will return null if there is no matching option .
348
20
18,655
protected int getOptionIndex ( final Object option ) { int optionCount = 0 ; List < ? > options = getOptions ( ) ; if ( options != null ) { for ( Object obj : getOptions ( ) ) { if ( obj instanceof OptionGroup ) { List < ? > groupOptions = ( ( OptionGroup ) obj ) . getOptions ( ) ; int groupIndex = groupOptions . indexOf ( option ) ; if ( groupIndex != - 1 ) { return optionCount + groupIndex ; } optionCount += groupOptions . size ( ) ; } else if ( Util . equals ( option , obj ) ) { return optionCount ; } else { optionCount ++ ; } } } return - 1 ; }
Retrieves the index of the given option . The index is not necessarily the index of the option in the options list as there may be options nested in OptionGroups .
149
35
18,656
public String getListCacheKey ( ) { Object table = getLookupTable ( ) ; if ( table != null && ConfigurationProperties . getDatalistCaching ( ) ) { String key = APPLICATION_LOOKUP_TABLE . getCacheKeyForTable ( table ) ; return key ; } return null ; }
Retrieves the data list cache key for this component .
68
12
18,657
public List < ? > getOptions ( ) { if ( getLookupTable ( ) == null ) { SelectionModel model = getComponentModel ( ) ; return model . getOptions ( ) ; } else { return APPLICATION_LOOKUP_TABLE . getTable ( getLookupTable ( ) ) ; } }
Returns the complete list of options available for selection for this user s session .
66
15
18,658
public void setOptions ( final Object [ ] aArray ) { setOptions ( aArray == null ? null : Arrays . asList ( aArray ) ) ; }
Set the complete list of options available for selection for this users session .
35
14
18,659
@ Override protected void preparePaintComponent ( final Request request ) { super . preparePaintComponent ( request ) ; if ( isAjax ( ) && UIContextHolder . getCurrent ( ) . getUI ( ) != null ) { AjaxTarget target = getAjaxTarget ( ) ; AjaxHelper . registerComponent ( target . getId ( ) , getId ( ) ) ; } String cacheKey = getListCacheKey ( ) ; if ( cacheKey != null ) { LookupTableHelper . registerList ( cacheKey , request ) ; } }
Override preparePaintComponent to register an AJAX operation if this list is AJAX enabled .
121
19
18,660
public String getDesc ( final Object option , final int index ) { String desc = "" ; if ( option instanceof Option ) { String optDesc = ( ( Option ) option ) . getDesc ( ) ; if ( optDesc != null ) { desc = optDesc ; } } else { String tableDesc = APPLICATION_LOOKUP_TABLE . getDescription ( getLookupTable ( ) , option ) ; if ( tableDesc != null ) { desc = tableDesc ; } else if ( option != null ) { desc = option . toString ( ) ; } } return I18nUtilities . format ( null , desc ) ; }
Retrieves the description for the given option . Intended for use by Renderers .
134
18
18,661
@ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WSingleSelect listBox = ( WSingleSelect ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; String dataKey = listBox . getListCacheKey ( ) ; boolean readOnly = listBox . isReadOnly ( ) ; int rows = listBox . getRows ( ) ; xml . appendTagOpen ( "ui:listbox" ) ; xml . appendAttribute ( "id" , component . getId ( ) ) ; xml . appendOptionalAttribute ( "class" , component . getHtmlClass ( ) ) ; xml . appendOptionalAttribute ( "track" , component . isTracking ( ) , "true" ) ; xml . appendOptionalAttribute ( "hidden" , listBox . isHidden ( ) , "true" ) ; if ( readOnly ) { xml . appendAttribute ( "readOnly" , "true" ) ; } else { xml . appendOptionalAttribute ( "data" , dataKey != null , dataKey ) ; xml . appendOptionalAttribute ( "disabled" , listBox . isDisabled ( ) , "true" ) ; xml . appendOptionalAttribute ( "required" , listBox . isMandatory ( ) , "true" ) ; xml . appendOptionalAttribute ( "submitOnChange" , listBox . isSubmitOnChange ( ) , "true" ) ; xml . appendOptionalAttribute ( "toolTip" , component . getToolTip ( ) ) ; xml . appendOptionalAttribute ( "accessibleText" , component . getAccessibleText ( ) ) ; xml . appendOptionalAttribute ( "rows" , rows >= 2 , rows ) ; String autocomplete = listBox . getAutocomplete ( ) ; xml . appendOptionalAttribute ( "autocomplete" , ! Util . empty ( autocomplete ) , autocomplete ) ; } xml . appendAttribute ( "single" , "true" ) ; xml . appendClose ( ) ; // Options List < ? > options = listBox . getOptions ( ) ; boolean renderSelectionsOnly = readOnly || dataKey != null ; if ( options != null ) { int optionIndex = 0 ; Object selectedOption = listBox . getSelected ( ) ; for ( Object option : options ) { if ( option instanceof OptionGroup ) { xml . appendTagOpen ( "ui:optgroup" ) ; xml . appendAttribute ( "label" , ( ( OptionGroup ) option ) . getDesc ( ) ) ; xml . appendClose ( ) ; for ( Object nestedOption : ( ( OptionGroup ) option ) . getOptions ( ) ) { renderOption ( listBox , nestedOption , optionIndex ++ , xml , selectedOption , renderSelectionsOnly ) ; } xml . appendEndTag ( "ui:optgroup" ) ; } else { renderOption ( listBox , option , optionIndex ++ , xml , selectedOption , renderSelectionsOnly ) ; } } } if ( ! readOnly ) { DiagnosticRenderUtil . renderDiagnostics ( listBox , renderContext ) ; } xml . appendEndTag ( "ui:listbox" ) ; }
Paints the given WSingleSelect .
673
8
18,662
private void initialiseInstanceVariables ( ) { backing = new HashMap <> ( ) ; booleanBacking = new HashSet <> ( ) ; locations = new HashMap <> ( ) ; // subContextCache is updated on the fly so ensure no concurrent modification. subcontextCache = Collections . synchronizedMap ( new HashMap ( ) ) ; runtimeProperties = new IncludeProperties ( "Runtime: added at runtime" ) ; }
This method initialises most of the instance variables .
92
10
18,663
@ SuppressWarnings ( "checkstyle:emptyblock" ) private void load ( ) { recordMessage ( "Loading parameters" ) ; File cwd = new File ( "." ) ; String workingDir ; try { workingDir = cwd . getCanonicalPath ( ) ; } catch ( IOException ex ) { workingDir = "UNKNOWN" ; } recordMessage ( "Working directory is " + workingDir ) ; for ( String resourceName : PARAMETER_LOAD_ORDER ) { loadTop ( resourceName ) ; } if ( getBoolean ( USE_SYSTEM_PROPERTIES ) ) { recordMessage ( "Loading from system properties" ) ; load ( System . getProperties ( ) , "System Properties" , true ) ; } // Now perform variable substitution. do { // Do nothing while loop } while ( substitute ( ) ) ; if ( getBoolean ( DUMP ) ) { // Can't use logging infrastructure here, so dump to console log ( getDebuggingInfo ( ) ) ; log ( getMessages ( ) ) ; } // We don't want the StringBuffer hanging around after 'DUMP'. clearMessages ( ) ; // Now move any parameters with the system parameters prefix into the real system parameters. Properties systemProperties = getSubProperties ( SYSTEM_PARAMETERS_PREFIX , true ) ; System . getProperties ( ) . putAll ( systemProperties ) ; }
Load the backing from the properties file visible to our classloader plus the filesystem .
306
16
18,664
@ SuppressWarnings ( "checkstyle:emptyblock" ) private void loadTop ( final String resourceName ) { try { resources . push ( resourceName ) ; load ( resourceName ) ; // Now check for INCLUDE_AFTER resources String includes = get ( INCLUDE_AFTER ) ; if ( includes != null ) { // First, do substitution on the INCLUDE_AFTER do { } while ( substitute ( INCLUDE_AFTER ) ) ; // Now split and process String [ ] includeAfter = getString ( INCLUDE_AFTER ) . split ( "," ) ; backing . remove ( INCLUDE_AFTER ) ; for ( String after : includeAfter ) { loadTop ( after ) ; } } } finally { resources . pop ( ) ; } }
Loading of top level resources is different to the general recursive case since it is only at the top level that we check for the includeAfter parameter .
176
29
18,665
private String filename ( final File aFile ) { try { return aFile . getCanonicalPath ( ) ; } catch ( IOException ex ) { recordException ( ex ) ; return "UNKNOWN FILE" ; } }
Retrieves the canonical path for a given file .
47
11
18,666
private void load ( final Properties properties , final String location , final boolean overwriteOnly ) { for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { String key = ( String ) entry . getKey ( ) ; String already = get ( key ) ; if ( overwriteOnly && already == null && ! INCLUDE . equals ( key ) ) { continue ; } String value = ( String ) entry . getValue ( ) ; load ( key , value , location ) ; } }
Load the properties from the given Properties object recording the origin on those properties as being from the given location .
107
21
18,667
private void load ( final String key , final String value , final String location ) { // Recursive bit if ( INCLUDE . equals ( key ) ) { load ( parseStringArray ( value ) ) ; } else { backing . put ( key , value ) ; if ( "yes" . equals ( value ) || "true" . equals ( value ) ) { booleanBacking . add ( key ) ; } else { booleanBacking . remove ( key ) ; } String history = locations . get ( key ) ; if ( history == null ) { history = location ; } else { history = location + "; " + history ; } locations . put ( key , history ) ; } }
Loads a single parameter into the configuration . This handles the special directives such as include .
145
18
18,668
private void load ( final String [ ] subFiles ) { for ( int i = 0 ; i < subFiles . length ; i ++ ) { load ( subFiles [ i ] ) ; } }
Loads the configuration from a set of files .
41
10
18,669
public Properties getSubProperties ( final String prefix , final boolean truncate ) { String cacheKey = truncate + prefix ; Properties sub = subcontextCache . get ( cacheKey ) ; if ( sub != null ) { // make a copy so users can't change. Properties copy = new Properties ( ) ; copy . putAll ( sub ) ; return copy ; } sub = new Properties ( ) ; int length = prefix . length ( ) ; for ( Map . Entry < String , Object > entry : backing . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( key . startsWith ( prefix ) ) { // If we are truncating, remove the prefix String newKey = key ; if ( truncate ) { newKey = key . substring ( length ) ; } sub . setProperty ( newKey , ( String ) entry . getValue ( ) ) ; } } subcontextCache . put ( cacheKey , sub ) ; // Make a copy so users can't change. Properties copy = new Properties ( ) ; copy . putAll ( sub ) ; return copy ; }
Returns a sub - set of the parameters contained in this configuration .
230
13
18,670
@ Override public void preparePaintComponent ( final Request request ) { if ( ! this . isInitialised ( ) ) { // Give the repeater the list of data to display. productRepeater . setData ( fetchProductData ( ) ) ; // Remember that we've done the initialisation. this . setInitialised ( true ) ; } }
Override to initialise some data .
74
7
18,671
public static String unescapeToXML ( final String input ) { if ( Util . empty ( input ) ) { return input ; } // Check if input has encoded brackets String encoded = WebUtilities . doubleEncodeBrackets ( input ) ; String unescaped = UNESCAPE_HTML_TO_XML . translate ( encoded ) ; String decoded = WebUtilities . doubleDecodeBrackets ( unescaped ) ; return decoded ; }
Unescape HTML entities to safe XML .
98
9
18,672
@ Override public Message toMessage ( final Throwable throwable ) { LOG . error ( "The system is currently unavailable" , throwable ) ; return new Message ( Message . ERROR_MESSAGE , InternalMessages . DEFAULT_SYSTEM_ERROR ) ; }
This method converts a java Throwable into a user friendly error message .
58
14
18,673
public void addTargets ( final List < ? extends AjaxTarget > targets ) { if ( targets != null ) { for ( AjaxTarget target : targets ) { this . addTarget ( target ) ; } } }
Add a list of target components that should be targets for this AJAX request .
45
16
18,674
public void addTarget ( final AjaxTarget target ) { AjaxControlModel model = getOrCreateComponentModel ( ) ; if ( model . targets == null ) { model . targets = new ArrayList <> ( ) ; } model . targets . add ( target ) ; MemoryUtil . checkSize ( model . targets . size ( ) , this . getClass ( ) . getSimpleName ( ) ) ; }
Add a single target WComponent to this AJAX control .
85
12
18,675
@ Override protected void preparePaintComponent ( final Request request ) { super . preparePaintComponent ( request ) ; List < AjaxTarget > targets = getTargets ( ) ; if ( targets != null && ! targets . isEmpty ( ) ) { WComponent triggerComponent = trigger == null ? this : trigger ; // The trigger maybe in a different context UIContext triggerContext = WebUtilities . getContextForComponent ( triggerComponent ) ; UIContextHolder . pushContext ( triggerContext ) ; // TODO The IDs of the targets are based on the Triggers Context. Not good for targets in repeaters try { List < String > targetIds = new ArrayList <> ( ) ; for ( AjaxTarget target : getTargets ( ) ) { targetIds . add ( target . getId ( ) ) ; } AjaxHelper . registerComponents ( targetIds , triggerComponent . getId ( ) ) ; } finally { UIContextHolder . popContext ( ) ; } } }
Override preparePaintComponent in order to register the components for the current request .
218
16
18,676
public void setCaseSensitiveMatch ( final Boolean caseInsensitive ) { FilterableBeanBoundDataModel model = getFilterableTableModel ( ) ; if ( model != null ) { model . setCaseSensitiveMatch ( caseInsensitive ) ; } }
Set the filter case sensitivity .
54
6
18,677
private WDecoratedLabel buildColumnHeader ( final String text , final WMenu menu ) { WDecoratedLabel label = new WDecoratedLabel ( null , new WText ( text ) , menu ) ; return label ; }
Helper to create the table column heading s WDecoratedLabel .
50
14
18,678
private void buildFilterMenus ( ) { buildFilterSubMenu ( firstNameFilterMenu , FIRST_NAME ) ; if ( firstNameFilterMenu . getChildCount ( ) == 0 ) { firstNameFilterMenu . setVisible ( false ) ; } buildFilterSubMenu ( lastNameFilterMenu , LAST_NAME ) ; if ( lastNameFilterMenu . getChildCount ( ) == 0 ) { lastNameFilterMenu . setVisible ( false ) ; } buildFilterSubMenu ( dobFilterMenu , DOB ) ; if ( dobFilterMenu . getChildCount ( ) == 0 ) { dobFilterMenu . setVisible ( false ) ; } }
Builds the menu content for each column heading s filter menu .
141
13
18,679
private void setUpClearAllAction ( ) { /* if one or fewer of the filter menus are visible then we don't need the clear all menus button */ int visibleMenus = 0 ; if ( firstNameFilterMenu . isVisible ( ) ) { visibleMenus ++ ; } if ( lastNameFilterMenu . isVisible ( ) ) { visibleMenus ++ ; } if ( dobFilterMenu . isVisible ( ) ) { visibleMenus ++ ; } clearAllFiltersButton . setVisible ( visibleMenus > 1 ) ; /* enable/disable the clear all filters action: * if we have not initialised the lists then we do not need the button (though in this case it will not be visible); * otherwise if the size of the full list is the same as the size of the filtered list then we have not filtered the * list so we do not need to clear the filters and the button can be disabled; * otherwise enable the button because we have applied at least one filter. */ if ( clearAllFiltersButton . isVisible ( ) ) { List < ? > fullList = getFilterableTableModel ( ) . getFullBeanList ( ) ; List < ? > filteredList = getFilterableTableModel ( ) . getBeanList ( ) ; clearAllFiltersButton . setDisabled ( fullList == null || filteredList == null || fullList . size ( ) == filteredList . size ( ) ) ; } }
Sets the state of the clearAllActions button based on the visibility of the filter menus and if the button is visible sets its disabled state if nothing is filtered .
308
34
18,680
private void buildFilterSubMenu ( final WMenu menu , final int column ) { List < ? > beanList = getFilterableTableModel ( ) . getFullBeanList ( ) ; int rows = ( beanList == null ) ? 0 : beanList . size ( ) ; if ( rows == 0 ) { return ; } final List < String > found = new ArrayList <> ( ) ; final WDecoratedLabel filterSubMenuLabel = new WDecoratedLabel ( new WText ( "\u200b" ) ) ; filterSubMenuLabel . setToolTip ( "Filter this column" ) ; filterSubMenuLabel . setHtmlClass ( HtmlIconUtil . getIconClasses ( "fa-filter" ) ) ; final WSubMenu submenu = new WSubMenu ( filterSubMenuLabel ) ; submenu . setSelectionMode ( SELECTION_MODE ) ; menu . add ( submenu ) ; WMenuItem item = new WMenuItem ( CLEAR_ALL , new ClearFilterAction ( ) ) ; submenu . add ( item ) ; item . setActionObject ( item ) ; item . setSelectability ( false ) ; add ( new WAjaxControl ( item , table ) ) ; Object cellObject ; String cellContent , cellContentMatch ; Object bean ; if ( beanList != null ) { for ( int i = 0 ; i < rows ; ++ i ) { bean = beanList . get ( i ) ; if ( bean != null ) { cellObject = getFilterableTableModel ( ) . getBeanPropertyValueFullList ( BEAN_PROPERTIES [ column ] , bean ) ; if ( cellObject != null ) { if ( cellObject instanceof Date ) { cellContent = new SimpleDateFormat ( DATE_FORMAT ) . format ( ( Date ) cellObject ) ; } else { cellContent = cellObject . toString ( ) ; } if ( "" . equals ( cellContent ) ) { cellContent = EMPTY ; } cellContentMatch = ( getFilterableTableModel ( ) . isCaseInsensitiveMatch ( ) ) ? cellContent . toLowerCase ( ) : cellContent ; if ( found . indexOf ( cellContentMatch ) == - 1 ) { item = new WMenuItem ( cellContent , new FilterAction ( ) ) ; submenu . add ( item ) ; add ( new WAjaxControl ( item , table ) ) ; found . add ( cellContentMatch ) ; } } } } } }
Creates and populates the sub - menu for each filter menu .
528
14
18,681
public void setUrl ( final String url ) { String currUrl = getUrl ( ) ; if ( ! Objects . equals ( url , currUrl ) ) { getOrCreateComponentModel ( ) . url = url ; } }
Sets the URL .
49
5
18,682
public void setTargetWindow ( final String targetWindow ) { String currTargWin = getTargetWindow ( ) ; if ( ! Objects . equals ( targetWindow , currTargWin ) ) { getOrCreateComponentModel ( ) . targetWindow = targetWindow ; } }
Sets the target window name .
59
7
18,683
private void dumpWEnvironment ( ) { StringBuffer text = new StringBuffer ( ) ; Environment env = getEnvironment ( ) ; text . append ( "\n\nWEnvironment" + "\n------------" ) ; text . append ( "\nAppId: " ) . append ( env . getAppId ( ) ) ; text . append ( "\nBaseUrl: " ) . append ( env . getBaseUrl ( ) ) ; text . append ( "\nHostFreeBaseUrl: " ) . append ( env . getHostFreeBaseUrl ( ) ) ; text . append ( "\nPostPath: " ) . append ( env . getPostPath ( ) ) ; text . append ( "\nTargetablePath: " ) . append ( env . getWServletPath ( ) ) ; text . append ( "\nAppHostPath: " ) . append ( env . getAppHostPath ( ) ) ; text . append ( "\nThemePath: " ) . append ( env . getThemePath ( ) ) ; text . append ( "\nStep: " ) . append ( env . getStep ( ) ) ; text . append ( "\nSession Token: " ) . append ( env . getSessionToken ( ) ) ; text . append ( "\nFormEncType: " ) . append ( env . getFormEncType ( ) ) ; text . append ( ' ' ) ; appendToConsole ( text . toString ( ) ) ; }
Appends the current environment to the console .
304
9
18,684
public static Configuration copyConfiguration ( final Configuration original ) { Configuration copy = new MapConfiguration ( new HashMap < String , Object > ( ) ) ; for ( Iterator < ? > i = original . getKeys ( ) ; i . hasNext ( ) ; ) { String key = ( String ) i . next ( ) ; Object value = original . getProperty ( key ) ; if ( value instanceof List ) { value = new ArrayList ( ( List ) value ) ; } copy . setProperty ( key , value ) ; } return copy ; }
Creates a deep - copy of the given configuration . This is useful for unit - testing .
114
19
18,685
public List < String > getFileTypes ( ) { List < String > fileTypes = getComponentModel ( ) . fileTypes ; if ( fileTypes == null ) { return Collections . emptyList ( ) ; } return Collections . unmodifiableList ( fileTypes ) ; }
Returns a list of strings that determine the allowable file mime types accepted by the file input . If no types have been added an empty list is returned . An empty list indicates that all file types are accepted .
57
42
18,686
public void setFileTypes ( final String [ ] types ) { if ( types == null ) { setFileTypes ( ( List < String > ) null ) ; } else { setFileTypes ( Arrays . asList ( types ) ) ; } }
Set each file type to be accepted by the WFileWidget .
52
13
18,687
private void resetValidationState ( ) { // if User Model exists it will be returned, othewise Shared Model is returned final FileWidgetModel componentModel = getComponentModel ( ) ; // If Shared Model is returned then both fileType and fileSize are always valid // If User Model is returned check if any if any is false if ( ! componentModel . validFileSize || ! componentModel . validFileType ) { final FileWidgetModel userModel = getOrCreateComponentModel ( ) ; userModel . validFileType = true ; userModel . validFileSize = true ; } }
Reset validation state .
122
5
18,688
public InputStream getInputStream ( ) throws IOException { FileItemWrap wrapper = getValue ( ) ; if ( wrapper != null ) { return wrapper . getInputStream ( ) ; } return null ; }
Retrieves an input stream of the uploaded file s contents .
44
13
18,689
@ Override public Object getData ( ) { Object data = super . getData ( ) ; if ( isRichTextArea ( ) && isSanitizeOnOutput ( ) && data != null ) { return sanitizeOutputText ( data . toString ( ) ) ; } return data ; }
The data for this WTextArea . If the text area is not rich text its output is XML escaped so we can ignore sanitization . If the text area is a rich text area then we check the sanitizeOnOutput flag as sanitization is rather resource intensive .
63
57
18,690
@ Override public void setData ( final Object data ) { if ( isRichTextArea ( ) && data instanceof String ) { super . setData ( sanitizeInputText ( ( String ) data ) ) ; } else { super . setData ( data ) ; } }
Set data in this component . If the WTextArea is a rich text input we need to sanitize the input .
59
25
18,691
public static List < Diagnostic > extractDiagnostics ( final List < Diagnostic > diagnostics , final int severity ) { ArrayList < Diagnostic > extract = new ArrayList <> ( ) ; for ( Diagnostic diagnostic : diagnostics ) { if ( diagnostic . getSeverity ( ) == severity ) { extract . add ( diagnostic ) ; } } return extract ; }
Extract diagnostics with a given severity from a list of Diagnostic objects . This is useful for picking errors out from a list of diagnostics for example .
79
32
18,692
@ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WCollapsible collapsible = ( WCollapsible ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; WComponent content = collapsible . getContent ( ) ; boolean collapsed = collapsible . isCollapsed ( ) ; xml . appendTagOpen ( "ui:collapsible" ) ; xml . appendAttribute ( "id" , component . getId ( ) ) ; xml . appendOptionalAttribute ( "class" , component . getHtmlClass ( ) ) ; xml . appendOptionalAttribute ( "track" , component . isTracking ( ) , "true" ) ; xml . appendAttribute ( "groupName" , collapsible . getGroupName ( ) ) ; xml . appendOptionalAttribute ( "collapsed" , collapsed , "true" ) ; xml . appendOptionalAttribute ( "hidden" , collapsible . isHidden ( ) , "true" ) ; switch ( collapsible . getMode ( ) ) { case CLIENT : xml . appendAttribute ( "mode" , "client" ) ; break ; case LAZY : xml . appendAttribute ( "mode" , "lazy" ) ; break ; case EAGER : xml . appendAttribute ( "mode" , "eager" ) ; break ; case DYNAMIC : xml . appendAttribute ( "mode" , "dynamic" ) ; break ; case SERVER : xml . appendAttribute ( "mode" , "server" ) ; break ; default : throw new SystemException ( "Unknown collapsible mode: " + collapsible . getMode ( ) ) ; } HeadingLevel level = collapsible . getHeadingLevel ( ) ; if ( level != null ) { xml . appendAttribute ( "level" , level . getLevel ( ) ) ; } xml . appendClose ( ) ; // Render margin MarginRendererUtil . renderMargin ( collapsible , renderContext ) ; // Label collapsible . getDecoratedLabel ( ) . paint ( renderContext ) ; // Content xml . appendTagOpen ( "ui:content" ) ; xml . appendAttribute ( "id" , component . getId ( ) + "-content" ) ; xml . appendClose ( ) ; // Render content if not EAGER Mode or is EAGER and is the current AJAX trigger if ( CollapsibleMode . EAGER != collapsible . getMode ( ) || AjaxHelper . isCurrentAjaxTrigger ( collapsible ) ) { // Visibility of content set in prepare paint content . paint ( renderContext ) ; } xml . appendEndTag ( "ui:content" ) ; xml . appendEndTag ( "ui:collapsible" ) ; }
Paints the given WCollapsible .
587
9
18,693
private void toggleReadOnly ( ) { allFiles . setReadOnly ( ! allFiles . isReadOnly ( ) ) ; imageFiles . setReadOnly ( ! imageFiles . isReadOnly ( ) ) ; textFiles . setReadOnly ( ! textFiles . isReadOnly ( ) ) ; pdfFiles . setReadOnly ( ! pdfFiles . isReadOnly ( ) ) ; }
Toggles the readonly state off all file widgets in the example .
81
14
18,694
private void processFiles ( ) { StringBuffer buf = new StringBuffer ( ) ; appendFileDetails ( buf , allFiles ) ; appendFileDetails ( buf , textFiles ) ; appendFileDetails ( buf , pdfFiles ) ; console . setText ( buf . toString ( ) ) ; }
Outputs information on the uploaded files to the text area .
61
12
18,695
private void appendFileDetails ( final StringBuffer buf , final WMultiFileWidget fileWidget ) { List < FileWidgetUpload > files = fileWidget . getFiles ( ) ; if ( files != null ) { for ( FileWidgetUpload file : files ) { String streamedSize ; try { InputStream in = file . getFile ( ) . getInputStream ( ) ; int size = 0 ; while ( in . read ( ) >= 0 ) { size ++ ; } streamedSize = String . valueOf ( size ) ; } catch ( IOException e ) { streamedSize = e . getMessage ( ) ; } buf . append ( "Name: " ) . append ( file . getFile ( ) . getName ( ) ) ; buf . append ( "\nSize: " ) . append ( streamedSize ) . append ( " bytes\n\n" ) ; } } }
Appends details of the uploaded files to the given string buffer .
182
13
18,696
public String getUrl ( ) { ContentAccess content = getContentAccess ( ) ; String mode = DisplayMode . PROMPT_TO_SAVE . equals ( getDisplayMode ( ) ) ? "attach" : "inline" ; // Check for a "static" resource if ( content instanceof InternalResource ) { String url = ( ( InternalResource ) content ) . getTargetUrl ( ) ; // This magic parameter is a work-around to the loading indicator becoming // "stuck" in certain browsers. // It is also used by the static resource handler to set the correct headers url = url + "&" + URL_CONTENT_MODE_PARAMETER_KEY + "=" + mode ; return url ; } Environment env = getEnvironment ( ) ; Map < String , String > parameters = env . getHiddenParameters ( ) ; parameters . put ( Environment . TARGET_ID , getTargetId ( ) ) ; if ( Util . empty ( getCacheKey ( ) ) ) { // Add some randomness to the URL to prevent caching String random = WebUtilities . generateRandom ( ) ; parameters . put ( Environment . UNIQUE_RANDOM_PARAM , random ) ; } else { // Remove step counter as not required for cached content parameters . remove ( Environment . STEP_VARIABLE ) ; parameters . remove ( Environment . SESSION_TOKEN_VARIABLE ) ; // Add the cache key parameters . put ( Environment . CONTENT_CACHE_KEY , getCacheKey ( ) ) ; } // This magic parameter is a work-around to the loading indicator becoming // "stuck" in certain browsers. It is only read by the theme. parameters . put ( URL_CONTENT_MODE_PARAMETER_KEY , mode ) ; // The targetable path needs to be configured for the portal environment. String url = env . getWServletPath ( ) ; // Note the last parameter. In javascript we don't want to encode "&". return WebUtilities . getPath ( url , parameters , true ) ; }
Retrieves a dynamic URL which this targetable component can be accessed from .
437
16
18,697
private void applySettings ( ) { container . reset ( ) ; WList list = new WList ( ( com . github . bordertech . wcomponents . WList . Type ) ddType . getSelected ( ) ) ; List < String > selected = ( List < String > ) cgBeanFields . getSelected ( ) ; SimpleListRenderer renderer = new SimpleListRenderer ( selected , cbRenderUsingFieldLayout . isSelected ( ) ) ; list . setRepeatedComponent ( renderer ) ; list . setSeparator ( ( Separator ) ddSeparator . getSelected ( ) ) ; list . setRenderBorder ( cbRenderBorder . isSelected ( ) ) ; container . add ( list ) ; List < SimpleTableBean > items = new ArrayList <> ( ) ; items . add ( new SimpleTableBean ( "A" , "none" , "thing" ) ) ; items . add ( new SimpleTableBean ( "B" , "some" , "thing2" ) ) ; items . add ( new SimpleTableBean ( "C" , "little" , "thing3" ) ) ; items . add ( new SimpleTableBean ( "D" , "lots" , "thing4" ) ) ; list . setData ( items ) ; list . setVisible ( cbVisible . isSelected ( ) ) ; }
Apply settings is responsible for building the list to be displayed and adding it to the container .
308
18
18,698
@ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WNumberField field = ( WNumberField ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; boolean readOnly = field . isReadOnly ( ) ; BigDecimal value = field . getValue ( ) ; String userText = field . getText ( ) ; xml . appendTagOpen ( "ui:numberfield" ) ; xml . appendAttribute ( "id" , component . getId ( ) ) ; xml . appendOptionalAttribute ( "class" , component . getHtmlClass ( ) ) ; xml . appendOptionalAttribute ( "track" , component . isTracking ( ) , "true" ) ; xml . appendOptionalAttribute ( "hidden" , component . isHidden ( ) , "true" ) ; if ( readOnly ) { xml . appendAttribute ( "readOnly" , "true" ) ; } else { WComponent submitControl = field . getDefaultSubmitButton ( ) ; String submitControlId = submitControl == null ? null : submitControl . getId ( ) ; BigDecimal min = field . getMinValue ( ) ; BigDecimal max = field . getMaxValue ( ) ; BigDecimal step = field . getStep ( ) ; int decimals = field . getDecimalPlaces ( ) ; xml . appendOptionalAttribute ( "disabled" , field . isDisabled ( ) , "true" ) ; xml . appendOptionalAttribute ( "required" , field . isMandatory ( ) , "true" ) ; xml . appendOptionalAttribute ( "toolTip" , field . getToolTip ( ) ) ; xml . appendOptionalAttribute ( "accessibleText" , field . getAccessibleText ( ) ) ; xml . appendOptionalAttribute ( "min" , min != null , String . valueOf ( min ) ) ; xml . appendOptionalAttribute ( "max" , max != null , String . valueOf ( max ) ) ; xml . appendOptionalAttribute ( "step" , step != null , String . valueOf ( step ) ) ; xml . appendOptionalAttribute ( "decimals" , decimals > 0 , decimals ) ; xml . appendOptionalAttribute ( "buttonId" , submitControlId ) ; String autocomplete = field . getAutocomplete ( ) ; xml . appendOptionalAttribute ( "autocomplete" , ! Util . empty ( autocomplete ) , autocomplete ) ; } xml . appendClose ( ) ; xml . appendEscaped ( value == null ? userText : value . toString ( ) ) ; if ( ! readOnly ) { DiagnosticRenderUtil . renderDiagnostics ( field , renderContext ) ; } xml . appendEndTag ( "ui:numberfield" ) ; }
Paints the given WNumberField .
597
8
18,699
@ Override public void write ( final int c ) { WhiteSpaceFilterStateMachine . StateChange change = stateMachine . nextState ( ( char ) c ) ; if ( change . getOutputBytes ( ) != null ) { for ( int i = 0 ; i < change . getOutputBytes ( ) . length ; i ++ ) { super . write ( change . getOutputBytes ( ) [ i ] ) ; } } if ( ! change . isSuppressCurrentChar ( ) ) { super . write ( c ) ; } }
Writes the given byte to the underlying output stream if it passes filtering .
111
15