idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
19,200 | public void setImage ( final Image image ) { LinkModel model = getOrCreateComponentModel ( ) ; model . image = image ; model . imageUrl = null ; } | Sets the image to display on the link . | 36 | 10 |
19,201 | public void setImageUrl ( final String imageUrl ) { LinkModel model = getOrCreateComponentModel ( ) ; model . imageUrl = imageUrl ; model . image = null ; } | Sets the URL of the image to display on the link . | 39 | 13 |
19,202 | public void addFile ( final FileWidgetUpload file ) { List < FileWidgetUpload > files = ( List < FileWidgetUpload > ) getData ( ) ; if ( files == null ) { files = new ArrayList <> ( ) ; setData ( files ) ; } files . add ( file ) ; MemoryUtil . checkSize ( files . size ( ) , this . getClass ( ) . getSimpleName ( ) ) ; } | Add a file item to this widget . | 92 | 8 |
19,203 | public void removeFile ( final FileWidgetUpload file ) { List < FileWidgetUpload > files = ( List < FileWidgetUpload > ) getData ( ) ; if ( files != null ) { files . remove ( file ) ; if ( files . isEmpty ( ) ) { setData ( null ) ; } } } | Remove the file . | 66 | 4 |
19,204 | private boolean isValid ( final String fileType ) { boolean result = false ; if ( fileType != null && fileType . length ( ) > 1 ) { // the shortest I can think of would be something like ".h" if ( fileType . startsWith ( "." ) ) { // assume it's a file extension result = true ; } else if ( fileType . length ( ) > 2 && fileType . indexOf ( ' ' ) > 0 ) { // some imaginary mimetype like "a/*" would be at least 3 characters result = true ; } } return result ; } | Check that the file type SEEMS to be legit . | 124 | 11 |
19,205 | public List < String > getFileTypes ( ) { Set < String > fileTypes = getComponentModel ( ) . fileTypes ; List < String > result ; if ( fileTypes == null || fileTypes . isEmpty ( ) ) { return Collections . emptyList ( ) ; } result = new ArrayList <> ( fileTypes ) ; return result ; } | Returns a list of file types accepted by the file input . | 74 | 12 |
19,206 | public void setColumns ( final Integer cols ) { if ( cols != null && cols < 0 ) { throw new IllegalArgumentException ( "Must have zero or more columns" ) ; } Integer currColumns = getColumns ( ) ; if ( ! Objects . equals ( cols , currColumns ) ) { getOrCreateComponentModel ( ) . cols = cols ; } } | Sets the layout of uploaded files to be a certain number of columns . Null uses the theme default . | 88 | 21 |
19,207 | protected void doHandleFileAjaxActionRequest ( final Request request ) { // Protect against client-side tampering of disabled components if ( isDisabled ( ) ) { throw new SystemException ( "File widget is disabled." ) ; } // Check for file id String fileId = request . getParameter ( FILE_UPLOAD_ID_KEY ) ; if ( fileId == null ) { throw new SystemException ( "No file id provided for ajax action." ) ; } // Check valid file id FileWidgetUpload file = getFile ( fileId ) ; if ( file == null ) { throw new SystemException ( "Invalid file id [" + fileId + "]." ) ; } // Run the action final Action action = getFileAjaxAction ( ) ; if ( action == null ) { throw new SystemException ( "No action set for file ajax action request." ) ; } // Set the selected file id as the action object final ActionEvent event = new ActionEvent ( this , "fileajax" , fileId ) ; Runnable later = new Runnable ( ) { @ Override public void run ( ) { action . execute ( event ) ; } } ; invokeLater ( later ) ; } | Handle a file action AJAX request . | 257 | 8 |
19,208 | protected void doHandleTargetedRequest ( final Request request ) { // Check for file id String fileId = request . getParameter ( FILE_UPLOAD_ID_KEY ) ; if ( fileId == null ) { throw new SystemException ( "No file id provided for content request." ) ; } // Check valid file id FileWidgetUpload file = getFile ( fileId ) ; if ( file == null ) { throw new SystemException ( "Invalid file id [" + fileId + "]." ) ; } // Check if thumb nail requested boolean thumbNail = request . getParameter ( FILE_UPLOAD_THUMB_NAIL_KEY ) != null ; if ( thumbNail ) { doHandleThumbnailRequest ( file ) ; } else { doHandleFileContentRequest ( file ) ; } } | Handle a targeted request . Can be a file upload thumbnail request or file content request . | 169 | 17 |
19,209 | protected void doHandleUploadRequest ( final Request request ) { // Protect against client-side tampering of disabled/read-only fields. if ( isDisabled ( ) || isReadOnly ( ) ) { throw new SystemException ( "File widget cannot be updated." ) ; } // Only process on a POST if ( ! "POST" . equals ( request . getMethod ( ) ) ) { throw new SystemException ( "File widget cannot be updated by " + request . getMethod ( ) + "." ) ; } // Check only one file item in the request FileItem [ ] items = request . getFileItems ( getId ( ) ) ; if ( items . length > 1 ) { throw new SystemException ( "More than one file item received on the request." ) ; } // Check the client provided a fileID String fileId = request . getParameter ( FILE_UPLOAD_MULTI_PART_ID_KEY ) ; if ( fileId == null ) { throw new SystemException ( "No file id provided for file upload." ) ; } // Wrap the file item FileItemWrap wrap = new FileItemWrap ( items [ 0 ] ) ; // if fileType is supplied then validate it if ( hasFileTypes ( ) && ! FileUtil . validateFileType ( wrap , getFileTypes ( ) ) ) { String invalidMessage = FileUtil . getInvalidFileTypeMessage ( getFileTypes ( ) ) ; throw new SystemException ( invalidMessage ) ; } // if fileSize is supplied then validate it if ( hasMaxFileSize ( ) && ! FileUtil . validateFileSize ( wrap , getMaxFileSize ( ) ) ) { String invalidMessage = FileUtil . getInvalidFileSizeMessage ( getMaxFileSize ( ) ) ; throw new SystemException ( invalidMessage ) ; } FileWidgetUpload file = new FileWidgetUpload ( fileId , wrap ) ; addFile ( file ) ; // Set the file id to be used ion the renderer setFileUploadRequestId ( fileId ) ; setNewUpload ( true ) ; } | The request is a targeted file upload request . Upload the file and respond with the file information . | 433 | 19 |
19,210 | protected void doHandleThumbnailRequest ( final FileWidgetUpload file ) { // Create thumb nail (if required) if ( file . getThumbnail ( ) == null ) { Image thumbnail = createThumbNail ( file . getFile ( ) ) ; file . setThumbnail ( thumbnail ) ; } ContentEscape escape = new ContentEscape ( file . getThumbnail ( ) ) ; throw escape ; } | Handle the thumb nail request . | 82 | 6 |
19,211 | public String getFileUrl ( final String fileId ) { FileWidgetUpload file = getFile ( fileId ) ; if ( file == null ) { return null ; } Environment env = getEnvironment ( ) ; Map < String , String > parameters = env . getHiddenParameters ( ) ; parameters . put ( Environment . TARGET_ID , getTargetId ( ) ) ; if ( Util . empty ( file . getFileCacheKey ( ) ) ) { // 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 , file . getFileCacheKey ( ) ) ; } // File id parameters . put ( FILE_UPLOAD_ID_KEY , fileId ) ; // 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 URL for the uploaded file content . | 295 | 11 |
19,212 | public String getFileThumbnailUrl ( final String fileId ) { FileWidgetUpload file = getFile ( fileId ) ; if ( file == null ) { return null ; } // Check static resource Image thumbnail = file . getThumbnail ( ) ; if ( thumbnail instanceof InternalResource ) { return ( ( InternalResource ) thumbnail ) . getTargetUrl ( ) ; } Environment env = getEnvironment ( ) ; Map < String , String > parameters = env . getHiddenParameters ( ) ; parameters . put ( Environment . TARGET_ID , getTargetId ( ) ) ; if ( Util . empty ( file . getThumbnailCacheKey ( ) ) ) { // 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 , file . getThumbnailCacheKey ( ) ) ; } // File id parameters . put ( FILE_UPLOAD_ID_KEY , fileId ) ; // Thumbnail flag parameters . put ( FILE_UPLOAD_THUMB_NAIL_KEY , "Y" ) ; // 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 URL for the thumbnail of an uploaded file . | 363 | 13 |
19,213 | @ Override public void serviceRequest ( final Request request ) { // Reset the focus for this new request. UIContext uic = UIContextHolder . getCurrent ( ) ; uic . setFocussed ( null , null ) ; // We've hit the action phase, so we do want focus on this app. uic . setFocusRequired ( true ) ; super . serviceRequest ( request ) ; } | Override serviceRequest in order to perform processing specific to this interceptor . | 90 | 14 |
19,214 | @ Override public void paint ( final RenderContext renderContext ) { getBackingComponent ( ) . paint ( renderContext ) ; // We don't want to remember the focus for the next render because on // a multi portlet page, we'd end up with multiple portlets trying to // set the focus. UIContext uic = UIContextHolder . getCurrent ( ) ; if ( uic . isFocusRequired ( ) ) { boolean sticky = ConfigurationProperties . getStickyFocus ( ) ; if ( ! sticky ) { uic . setFocussed ( null , null ) ; uic . setFocusRequired ( false ) ; } } } | Override paint in order to perform processing specific to this interceptor . | 141 | 13 |
19,215 | private void applyEnableAction ( final WComponent target , final boolean enabled ) { // Found Disableable component if ( target instanceof Disableable ) { target . setValidate ( enabled ) ; ( ( Disableable ) target ) . setDisabled ( ! enabled ) ; } else if ( target instanceof Container ) { // Apply to any Disableable children Container cont = ( Container ) target ; final int size = cont . getChildCount ( ) ; for ( int i = 0 ; i < size ; i ++ ) { WComponent child = cont . getChildAt ( i ) ; applyEnableAction ( child , enabled ) ; } } } | Apply the enable action against the target and its children . | 132 | 11 |
19,216 | private void startLoad ( ) { tableLayout . setVisible ( true ) ; List < PersonBean > beans = ExampleDataUtil . createExampleData ( numRows . getNumber ( ) . intValue ( ) , numDocs . getNumber ( ) . intValue ( ) ) ; if ( isLoadWTable ( ) ) { table . setBean ( beans ) ; } if ( isLoadWDataTable ( ) ) { TableTreeNode tree = createTree ( beans ) ; datatable . setDataModel ( new SimpleBeanTreeTableDataModel ( new String [ ] { "firstName" , "lastName" , "dateOfBirth" } , tree ) ) ; } if ( isLoadWTable ( ) ) { ajax2 . setVisible ( true ) ; tableShim . setVisible ( isLoadWTable ( ) ) ; } else { ajax4 . setVisible ( true ) ; dataShim . setVisible ( isLoadWDataTable ( ) ) ; } } | Start load . | 220 | 3 |
19,217 | private void applyMandatoryAction ( final WComponent target , final boolean mandatory ) { if ( target instanceof Mandatable ) { ( ( Mandatable ) target ) . setMandatory ( mandatory ) ; } else if ( target instanceof Container ) { // Apply to the Mandatable children Container cont = ( Container ) target ; final int size = cont . getChildCount ( ) ; for ( int i = 0 ; i < size ; i ++ ) { WComponent child = cont . getChildAt ( i ) ; applyMandatoryAction ( child , mandatory ) ; } } } | Apply the mandatory action against the target and its children . | 119 | 11 |
19,218 | @ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WShuffler shuffler = ( WShuffler ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; boolean readOnly = shuffler . isReadOnly ( ) ; // Start tag xml . appendTagOpen ( "ui:shuffler" ) ; xml . appendAttribute ( "id" , component . getId ( ) ) ; xml . appendOptionalAttribute ( "class" , component . getHtmlClass ( ) ) ; xml . appendOptionalAttribute ( "track" , component . isTracking ( ) , "true" ) ; xml . appendOptionalAttribute ( "hidden" , shuffler . isHidden ( ) , "true" ) ; if ( readOnly ) { xml . appendAttribute ( "readOnly" , "true" ) ; } else { xml . appendOptionalAttribute ( "disabled" , shuffler . isDisabled ( ) , "true" ) ; xml . appendOptionalAttribute ( "toolTip" , shuffler . getToolTip ( ) ) ; xml . appendOptionalAttribute ( "accessibleText" , shuffler . getAccessibleText ( ) ) ; int rows = shuffler . getRows ( ) ; xml . appendOptionalAttribute ( "rows" , rows > 0 , rows ) ; } xml . appendClose ( ) ; // Options List < ? > options = shuffler . getOptions ( ) ; if ( options != null && ! options . isEmpty ( ) ) { for ( int i = 0 ; i < options . size ( ) ; i ++ ) { String stringOption = String . valueOf ( options . get ( i ) ) ; xml . appendTagOpen ( "ui:option" ) ; xml . appendAttribute ( "value" , stringOption ) ; xml . appendClose ( ) ; xml . appendEscaped ( stringOption ) ; xml . appendEndTag ( "ui:option" ) ; } } if ( ! readOnly ) { DiagnosticRenderUtil . renderDiagnostics ( shuffler , renderContext ) ; } // End tag xml . appendEndTag ( "ui:shuffler" ) ; } | Paints the given WShuffler . | 464 | 9 |
19,219 | private String deriveId ( final String idName ) { // Find parent naming context NamingContextable parent = WebUtilities . getParentNamingContext ( this ) ; // No Parent if ( parent == null ) { return idName ; } // Get ID prefix String prefix = parent . getNamingContextId ( ) ; // No Prefix, just use id name if ( prefix . length ( ) == 0 ) { return idName ; } // Add Prefix StringBuffer nameBuf = new StringBuffer ( prefix . length ( ) + idName . length ( ) + 1 ) ; nameBuf . append ( prefix ) ; nameBuf . append ( ID_CONTEXT_SEPERATOR ) ; nameBuf . append ( idName ) ; return nameBuf . toString ( ) ; } | Derive the full id from its naming context . | 168 | 10 |
19,220 | void registerInContext ( ) { if ( ! ConfigurationProperties . getCheckDuplicateIds ( ) ) { return ; } // Register Component if it has an ID name set if ( getIdName ( ) != null ) { // Find parent context NamingContextable context = WebUtilities . getParentNamingContext ( this ) ; if ( context == null ) { // If this is the top context, then register itself if ( WebUtilities . isActiveNamingContext ( this ) ) { this . registerId ( this ) ; } else { LOG . warn ( "Component with id name [" + getIdName ( ) + "] is not in a naming context and cannot be verified for duplicate id." ) ; } return ; } // Assume context is AbstractWComponent ( ( AbstractWComponent ) context ) . registerId ( this ) ; } } | Register this component s ID in its naming context . | 181 | 10 |
19,221 | protected void invokeLaters ( ) { if ( getParent ( ) == null ) { UIContext uic = UIContextHolder . getCurrent ( ) ; if ( uic != null ) { uic . doInvokeLaters ( ) ; } } } | The framework calls this method at the end of the serviceRequest method . The default implementation is that only a root wcomponent actually runs them . | 59 | 28 |
19,222 | protected void paintComponent ( final RenderContext renderContext ) { Renderer renderer = UIManager . getRenderer ( this , renderContext ) ; if ( getTemplate ( ) != null || getTemplateMarkUp ( ) != null ) { Renderer templateRenderer = UIManager . getTemplateRenderer ( renderContext ) ; templateRenderer . render ( this , renderContext ) ; } else if ( renderer == null ) { // Default is juxtaposition List < WComponent > children = getComponentModel ( ) . getChildren ( ) ; if ( children != null ) { final int size = children . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { children . get ( i ) . paint ( renderContext ) ; } } } else { renderer . render ( this , renderContext ) ; } } | This is where most of the painting work is normally done . If a layout has been supplied either directly or by supplying a velocity template then painting is delegated to the layout manager . If there is no layout the default behaviour is to paint the child components in sequence . | 183 | 52 |
19,223 | protected Diagnostic createErrorDiagnostic ( final WComponent source , final String message , final Serializable ... args ) { return new DiagnosticImpl ( Diagnostic . ERROR , source , message , args ) ; } | Create and return an error diagnostic associated to the given error source . | 44 | 13 |
19,224 | protected void setFlag ( final int mask , final boolean flag ) { // Only store the flag value if it is not the default. if ( flag != isFlagSet ( mask ) ) { ComponentModel model = getOrCreateComponentModel ( ) ; model . setFlags ( switchFlag ( model . getFlags ( ) , mask , flag ) ) ; } } | Sets or clears one or more component flags in the component model for the given context .. | 74 | 18 |
19,225 | private static int switchFlag ( final int flags , final int mask , final boolean value ) { int newFlags = value ? flags | mask : flags & ~ mask ; return newFlags ; } | A utility method to set or clear one or more bits in the given set of flags . | 39 | 18 |
19,226 | protected ComponentModel getComponentModel ( ) { UIContext effectiveContext = UIContextHolder . getCurrent ( ) ; if ( effectiveContext == null ) { return sharedModel ; } else { ComponentModel model = ( ComponentModel ) effectiveContext . getModel ( this ) ; if ( model == null ) { return sharedModel ; } else if ( model . getSharedModel ( ) == null ) { // The reference to the sharedModel has disappeared, // probably due to session serialization model . setSharedModel ( sharedModel ) ; } return model ; } } | Returns the effective component model for this component . Subclass may override this method to narrow the return type to their specific model type . | 121 | 26 |
19,227 | protected ComponentModel getOrCreateComponentModel ( ) { ComponentModel model = getComponentModel ( ) ; if ( locked && model == sharedModel ) { UIContext effectiveContext = UIContextHolder . getCurrent ( ) ; if ( effectiveContext != null ) { model = newComponentModel ( ) ; model . setSharedModel ( sharedModel ) ; effectiveContext . setModel ( this , model ) ; initialiseComponentModel ( ) ; } } return model ; } | Retrieves the model for this component so that it can be modified . If this method is called during request processing and a session specific model does not yet exist then a new model is created . Subclasses may override this method to narrow the return type to their specific model type . | 101 | 56 |
19,228 | WComponent getChildAt ( final int index ) { ComponentModel model = getComponentModel ( ) ; return model . getChildren ( ) . get ( index ) ; } | Retrieves a child component by its index . | 35 | 10 |
19,229 | int getIndexOfChild ( final WComponent childComponent ) { ComponentModel model = getComponentModel ( ) ; List < WComponent > children = model . getChildren ( ) ; return children == null ? - 1 : children . indexOf ( childComponent ) ; } | Retrieves the index of the given child . | 55 | 10 |
19,230 | List < WComponent > getChildren ( ) { List < WComponent > children = getComponentModel ( ) . getChildren ( ) ; return children != null && ! children . isEmpty ( ) ? Collections . unmodifiableList ( children ) : Collections . < WComponent > emptyList ( ) ; } | Retrieves the children of this component . | 63 | 9 |
19,231 | void add ( final WComponent component ) { assertAddSupported ( component ) ; assertNotReparenting ( component ) ; if ( ! ( this instanceof Container ) ) { throw new UnsupportedOperationException ( "Components can only be added to a container" ) ; } ComponentModel model = getOrCreateComponentModel ( ) ; if ( model . getChildren ( ) == null ) { model . setChildren ( new ArrayList < WComponent > ( 1 ) ) ; } model . getChildren ( ) . add ( component ) ; if ( isLocked ( ) ) { component . setLocked ( true ) ; } if ( component instanceof AbstractWComponent ) { ( ( AbstractWComponent ) component ) . getOrCreateComponentModel ( ) . setParent ( ( Container ) this ) ; ( ( AbstractWComponent ) component ) . addNotify ( ) ; } } | Adds the given component as a child of this component . | 183 | 11 |
19,232 | void remove ( final WComponent aChild ) { ComponentModel model = getOrCreateComponentModel ( ) ; if ( model . getChildren ( ) == null ) { model . setChildren ( copyChildren ( getComponentModel ( ) . getChildren ( ) ) ) ; } if ( model . getChildren ( ) . remove ( aChild ) ) { // Deallocate children list if possible, to reduce session size. if ( model . getChildren ( ) . isEmpty ( ) ) { model . setChildren ( null ) ; } // The child component has been successfully removed so clean up the context. aChild . reset ( ) ; // If the parent has been set in the shared model, we must override // it in the session model for the component to be considered removed. // This unfortunately means that the model will remain in the user's session. if ( aChild . getParent ( ) != null && aChild instanceof AbstractWComponent ) { ( ( AbstractWComponent ) aChild ) . getOrCreateComponentModel ( ) . setParent ( null ) ; ( ( AbstractWComponent ) aChild ) . removeNotify ( ) ; } } } | Removes the given component from this component s list of children . | 239 | 13 |
19,233 | private static List < WComponent > copyChildren ( final List < WComponent > children ) { ArrayList < WComponent > copy ; if ( children == null ) { copy = new ArrayList <> ( 1 ) ; } else { copy = new ArrayList <> ( children ) ; } return copy ; } | Creates a copy of the given list of components . | 64 | 11 |
19,234 | protected Object writeReplace ( ) throws ObjectStreamException { WComponent top = WebUtilities . getTop ( this ) ; String repositoryKey ; if ( top instanceof WApplication ) { repositoryKey = ( ( WApplication ) top ) . getUiVersionKey ( ) ; } else { repositoryKey = top . getClass ( ) . getName ( ) ; } if ( UIRegistry . getInstance ( ) . isRegistered ( repositoryKey ) && top == UIRegistry . getInstance ( ) . getUI ( repositoryKey ) ) { // Calculate the node location. // The node location is a list of "shared" child indexes of each // ancestor going right back to the top node. ArrayList < Integer > reversedIndexList = new ArrayList <> ( ) ; WComponent node = this ; Container parent = node . getParent ( ) ; try { while ( parent != null ) { int index = getIndexOfChild ( parent , node ) ; reversedIndexList . add ( index ) ; node = parent ; parent = node . getParent ( ) ; } } catch ( Exception ex ) { LOG . error ( "Unable to determine component index relative to top." , ex ) ; } final int depth = reversedIndexList . size ( ) ; int [ ] nodeLocation = new int [ depth ] ; for ( int i = 0 ; i < depth ; i ++ ) { Integer index = reversedIndexList . get ( depth - i - 1 ) ; nodeLocation [ i ] = index . intValue ( ) ; } WComponentRef ref = new WComponentRef ( repositoryKey , nodeLocation ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "WComponent converted to reference. Ref = " + ref + ". Component = " + getClass ( ) . getName ( ) ) ; } return ref ; } else { LOG . debug ( "WComponent not accessible via the repository, so it will be serialised. Component = " + getClass ( ) . getName ( ) ) ; return this ; } } | Implement writeReplace so that on serialization WComponents that are registered in the UIRegistry write a reference to the registered component rather than the component itself . This ensures that on deserialization only one copy of the registered component will be present in the VM . | 430 | 56 |
19,235 | private void addLink ( final WSubMenu subMenu , final WLink link ) { subMenu . add ( new WMenuItem ( new WDecoratedLabel ( link ) ) ) ; } | Adds a WLink to a sub - menu . | 41 | 10 |
19,236 | public void setLabelWidth ( final int labelWidth ) { if ( labelWidth > 100 ) { throw new IllegalArgumentException ( "labelWidth (" + labelWidth + ") cannot be greater than 100 percent." ) ; } getOrCreateComponentModel ( ) . labelWidth = Math . max ( 0 , labelWidth ) ; } | Sets the label width . | 69 | 6 |
19,237 | public WField addField ( final WButton button ) { WField field = new WField ( ( WLabel ) null , button ) ; add ( field ) ; return field ; } | Add a field consisting of a WButton with a null label . | 38 | 13 |
19,238 | @ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WPartialDateField dateField = ( WPartialDateField ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; boolean readOnly = dateField . isReadOnly ( ) ; String date = formatDate ( dateField ) ; xml . appendTagOpen ( "ui:datefield" ) ; xml . appendAttribute ( "id" , component . getId ( ) ) ; xml . appendOptionalAttribute ( "class" , component . getHtmlClass ( ) ) ; xml . appendOptionalAttribute ( "track" , component . isTracking ( ) , "true" ) ; xml . appendOptionalAttribute ( "hidden" , dateField . isHidden ( ) , "true" ) ; xml . appendOptionalAttribute ( "date" , date ) ; if ( readOnly ) { xml . appendAttribute ( "readOnly" , "true" ) ; } else { xml . appendAttribute ( "allowPartial" , "true" ) ; xml . appendOptionalAttribute ( "disabled" , dateField . isDisabled ( ) , "true" ) ; xml . appendOptionalAttribute ( "required" , dateField . isMandatory ( ) , "true" ) ; xml . appendOptionalAttribute ( "toolTip" , dateField . getToolTip ( ) ) ; xml . appendOptionalAttribute ( "accessibleText" , dateField . getAccessibleText ( ) ) ; WComponent submitControl = dateField . getDefaultSubmitButton ( ) ; String submitControlId = submitControl == null ? null : submitControl . getId ( ) ; xml . appendOptionalAttribute ( "buttonId" , submitControlId ) ; } xml . appendClose ( ) ; if ( date == null ) { xml . appendEscaped ( dateField . getText ( ) ) ; } if ( ! readOnly ) { DiagnosticRenderUtil . renderDiagnostics ( dateField , renderContext ) ; } xml . appendEndTag ( "ui:datefield" ) ; } | Paints the given WPartialDateField . | 441 | 10 |
19,239 | private String formatDate ( final WPartialDateField dateField ) { Integer day = dateField . getDay ( ) ; Integer month = dateField . getMonth ( ) ; Integer year = dateField . getYear ( ) ; if ( day != null || month != null || year != null ) { StringBuffer buf = new StringBuffer ( 10 ) ; append ( buf , year , 4 ) ; buf . append ( ' ' ) ; append ( buf , month , 2 ) ; buf . append ( ' ' ) ; append ( buf , day , 2 ) ; return buf . toString ( ) ; } return null ; } | Formats a partial date to the format required by the schema . | 130 | 13 |
19,240 | private void append ( final StringBuffer buf , final Integer num , final int digits ) { if ( num == null ) { for ( int i = 0 ; i < digits ; i ++ ) { buf . append ( ' ' ) ; } } else { for ( int digit = 1 , test = 10 ; digit < digits ; digit ++ , test *= 10 ) { if ( num < test ) { buf . append ( ' ' ) ; } } buf . append ( num ) ; } } | Appends a single date component to the given StringBuffer . Nulls are replaced with question marks and numbers are padded with zeros . | 102 | 27 |
19,241 | @ Override protected void validateComponent ( final List < Diagnostic > diags ) { String text1 = field1 . getText ( ) ; String text2 = field2 . getText ( ) ; String text3 = field3 . getText ( ) ; if ( text1 != null && text1 . length ( ) > 0 && text1 . equals ( text2 ) ) { // Note that this error will hyperlink to Field 2. diags . add ( createErrorDiagnostic ( field2 , "Fields 1 and 2 cannot be the same." ) ) ; } int len = 0 ; if ( text1 != null ) { len += text1 . length ( ) ; } if ( text2 != null ) { len += text2 . length ( ) ; } if ( len > 20 ) { // Note that this error does not link to a specific field. diags . add ( createErrorDiagnostic ( "The total length of Field 1 plus Field 2 can exceed 20 characters." ) ) ; } // Sample Warning Message if ( Util . empty ( text3 ) ) { diags . add ( new DiagnosticImpl ( Diagnostic . WARNING , UIContextHolder . getCurrent ( ) , field3 , "Warning that this should not be blank" ) ) ; } } | An example of cross field validation . | 272 | 7 |
19,242 | public StateChange nextState ( final char c ) { StateChange change = currentState . getChange ( c ) ; currentState = change . getNewState ( ) ; return change ; } | Moves the machine to the next state based on the input character . | 39 | 14 |
19,243 | @ Override protected boolean doHandleRequest ( final Request request ) { // Check if the group has a value on the Request if ( request . getParameter ( getId ( ) ) != null ) { // Allow the handle request to be processed by the radio buttons return false ; } // If no value, then clear the current value (if required) if ( getValue ( ) != null ) { setData ( null ) ; return true ; } return false ; } | This method will only processes a request where the group is on the request and has no value . If the group has no value then none of the group s radio buttons will be triggered to process the request . | 95 | 41 |
19,244 | private void addDateRangeExample ( ) { add ( new WHeading ( HeadingLevel . H2 , "Example of a date range component" ) ) ; WFieldSet dateRange = new WFieldSet ( "Enter the expected arrival and departure dates." ) ; add ( dateRange ) ; WPanel dateRangePanel = new WPanel ( ) ; dateRangePanel . setLayout ( new FlowLayout ( FlowLayout . LEFT , Size . MEDIUM ) ) ; dateRange . add ( dateRangePanel ) ; final WDateField arrivalDate = new WDateField ( ) ; final WDateField departureDate = new WDateField ( ) ; //One could add some validation rules around this so that "arrival" was always earlier than or equal to "departure" WLabel arrivalLabel = new WLabel ( "Arrival" , arrivalDate ) ; arrivalLabel . setHint ( "dd MMM yyyy" ) ; WLabel departureLabel = new WLabel ( "Departure" , departureDate ) ; departureLabel . setHint ( "dd MMM yyyy" ) ; dateRangePanel . add ( arrivalLabel ) ; dateRangePanel . add ( arrivalDate ) ; dateRangePanel . add ( departureLabel ) ; dateRangePanel . add ( departureDate ) ; //subordinate control to ensure that the departure date is only enabled if the arrival date is populated WSubordinateControl control = new WSubordinateControl ( ) ; add ( control ) ; Rule rule = new Rule ( new Equal ( arrivalDate , null ) ) ; control . addRule ( rule ) ; rule . addActionOnTrue ( new Disable ( departureDate ) ) ; rule . addActionOnFalse ( new Enable ( departureDate ) ) ; control . addRule ( rule ) ; } | Add date range example . | 375 | 5 |
19,245 | private void addContraintExamples ( ) { add ( new WHeading ( HeadingLevel . H2 , "Date fields with input constraints" ) ) ; WFieldLayout layout = new WFieldLayout ( ) ; layout . setLabelWidth ( 33 ) ; add ( layout ) ; /* mandatory */ WDateField constrainedDateField = new WDateField ( ) ; constrainedDateField . setMandatory ( true ) ; layout . addField ( "Mandatory date field" , constrainedDateField ) ; /* min date */ constrainedDateField = new WDateField ( ) ; constrainedDateField . setMinDate ( new Date ( ) ) ; layout . addField ( "Minimum date today" , constrainedDateField ) ; /* max date */ constrainedDateField = new WDateField ( ) ; constrainedDateField . setMaxDate ( new Date ( ) ) ; layout . addField ( "Maximum date today" , constrainedDateField ) ; /* auto complete */ constrainedDateField = new WDateField ( ) ; constrainedDateField . setBirthdayAutocomplete ( ) ; layout . addField ( "With autocomplete hint" , constrainedDateField ) ; constrainedDateField = new WDateField ( ) ; constrainedDateField . setAutocompleteOff ( ) ; layout . addField ( "With autocomplete off" , constrainedDateField ) ; } | Add constraint example . | 282 | 4 |
19,246 | @ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WSelectToggle toggle = ( WSelectToggle ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; xml . appendTagOpen ( "ui:selecttoggle" ) ; xml . appendAttribute ( "id" , component . getId ( ) ) ; xml . appendOptionalAttribute ( "class" , component . getHtmlClass ( ) ) ; xml . appendOptionalAttribute ( "track" , component . isTracking ( ) , "true" ) ; State state = toggle . getState ( ) ; if ( State . ALL . equals ( state ) ) { xml . appendAttribute ( "selected" , "all" ) ; } else if ( State . NONE . equals ( state ) ) { xml . appendAttribute ( "selected" , "none" ) ; } else { xml . appendAttribute ( "selected" , "some" ) ; } xml . appendOptionalAttribute ( "disabled" , toggle . isDisabled ( ) , "true" ) ; xml . appendAttribute ( "target" , toggle . getTarget ( ) . getId ( ) ) ; xml . appendAttribute ( "renderAs" , toggle . isRenderAsText ( ) ? "text" : "control" ) ; xml . appendOptionalAttribute ( "roundTrip" , ! toggle . isClientSide ( ) , "true" ) ; xml . appendEnd ( ) ; } | Paints the given WSelectToggle . | 315 | 9 |
19,247 | private void buildUI ( ) { // build the configuration options UI. WFieldLayout layout = new WFieldLayout ( WFieldLayout . LAYOUT_STACKED ) ; layout . setMargin ( new Margin ( null , null , Size . LARGE , null ) ) ; add ( layout ) ; layout . addField ( "Autoplay" , cbAutoPlay ) ; layout . addField ( "Loop" , cbLoop ) ; layout . addField ( "Disable" , cbDisable ) ; layout . addField ( "Show only play/pause" , cbControls ) ; layout . addField ( ( WLabel ) null , btnApply ) ; // enable disable option only when control PLAY_PAUSE is used. WSubordinateControl control = new WSubordinateControl ( ) ; add ( control ) ; Rule rule = new Rule ( ) ; rule . setCondition ( new Equal ( cbControls , Boolean . TRUE . toString ( ) ) ) ; rule . addActionOnTrue ( new Enable ( cbDisable ) ) ; rule . addActionOnFalse ( new Disable ( cbDisable ) ) ; control . addRule ( rule ) ; // allow config to change without reloading the whole page. add ( new WAjaxControl ( btnApply , audio ) ) ; // add the audio to the UI add ( audio ) ; } | Build the UI for this example . | 291 | 7 |
19,248 | @ Override protected void preparePaintComponent ( final Request request ) { super . preparePaintComponent ( request ) ; //To change body of generated methods, choose Tools | Templates. if ( ! isInitialised ( ) ) { setInitialised ( true ) ; setupAudio ( ) ; } } | Set up the initial state of the audio component . | 63 | 10 |
19,249 | private void setupAudio ( ) { audio . setAutoplay ( cbAutoPlay . isSelected ( ) ) ; audio . setLoop ( ! cbLoop . isDisabled ( ) && cbLoop . isSelected ( ) ) ; audio . setControls ( cbControls . isSelected ( ) ? WAudio . Controls . PLAY_PAUSE : WAudio . Controls . NATIVE ) ; audio . setDisabled ( cbControls . isSelected ( ) && cbDisable . isSelected ( ) ) ; } | Set the audio configuration options . | 118 | 6 |
19,250 | @ Override protected void afterPaint ( final RenderContext renderContext ) { super . afterPaint ( renderContext ) ; final int size = getChildCount ( ) ; for ( int i = 0 ; i < size ; i ++ ) { WComponent child = getChildAt ( i ) ; child . reset ( ) ; } } | After the component has been painted the UIContexts for this component and all its children are cleared . | 70 | 22 |
19,251 | public String getGroupName ( ) { if ( collapsibleToggle != null ) { return collapsibleToggle . getId ( ) ; } else if ( ! collapsibleList . isEmpty ( ) ) { // This is only to retain compatibility with the // previous implementation, and should be removed post-Sfp11, // as it doesn't make much sense to create a group without // something to toggle it. return collapsibleList . get ( 0 ) . getId ( ) ; } return "" ; } | Retrieves the common name used by all collapsible components in the group . | 106 | 16 |
19,252 | private void addComponent ( final WComponent component ) { collapsibleList . add ( component ) ; MemoryUtil . checkSize ( collapsibleList . size ( ) , this . getClass ( ) . getSimpleName ( ) ) ; } | Responsible for updating the underlying group store . | 50 | 10 |
19,253 | private List < ? > getNewOptions ( final String [ ] paramValues ) { // Take a copy of the old options List < ? > copyOldOptions = new ArrayList ( getOptions ( ) ) ; // Create a new list to hold the shuffled options List < Object > newOptions = new ArrayList <> ( paramValues . length ) ; // Process the option parameters for ( String param : paramValues ) { for ( Object oldOption : copyOldOptions ) { // Match the string value of the option String stringOldOption = String . valueOf ( oldOption ) ; if ( Util . equals ( stringOldOption , param ) ) { newOptions . add ( oldOption ) ; copyOldOptions . remove ( oldOption ) ; break ; } } } return newOptions ; } | Shuffle the options . | 164 | 5 |
19,254 | private void addListItems ( final WDefinitionList list ) { // Example of adding multiple data items at once. list . addTerm ( "Colours" , new WText ( "Red" ) , new WText ( "Green" ) , new WText ( "Blue" ) ) ; // Example of adding multiple data items using multiple calls. list . addTerm ( "Shapes" , new WText ( "Circle" ) ) ; list . addTerm ( "Shapes" , new WText ( "Square" ) , new WText ( "Triangle" ) ) ; } | Adds some items to a definition list . | 124 | 8 |
19,255 | private void applySettings ( ) { container . reset ( ) ; // Now show an example of the number of different columns WPanel gridLayoutPanel = new WPanel ( ) ; if ( cbResponsive . isSelected ( ) ) { gridLayoutPanel . setHtmlClass ( HtmlClassProperties . RESPOND ) ; } GridLayout layout = new GridLayout ( rowCount . getValue ( ) . intValue ( ) , columnCount . getValue ( ) . intValue ( ) , hGap . getValue ( ) . intValue ( ) , vGap . getValue ( ) . intValue ( ) ) ; gridLayoutPanel . setLayout ( layout ) ; addBoxes ( gridLayoutPanel , boxCount . getValue ( ) . intValue ( ) ) ; // give approx 3 rows, with a different number // of boxes on the final row container . add ( gridLayoutPanel ) ; gridLayoutPanel . setVisible ( cbVisible . isSelected ( ) ) ; } | reset the container that holds the grid layout and create a new grid layout with the appropriate properties . | 213 | 19 |
19,256 | public Subscription getSubscription ( Reference reference ) { return getResourceFactory ( ) . getApiResource ( "/subscription/" + reference . toURLFragment ( false ) ) . get ( Subscription . class ) ; } | Get the subscription for the given object | 48 | 7 |
19,257 | public void subscribe ( Reference reference ) { getResourceFactory ( ) . getApiResource ( "/subscription/" + reference . toURLFragment ( false ) ) . entity ( new Empty ( ) , MediaType . APPLICATION_JSON_TYPE ) . post ( ) ; } | Subscribes the user to the given object . Based on the object type the user will receive notifications when actions are performed on the object . See the area for more details . | 58 | 35 |
19,258 | @ Override public void paint ( final RenderContext renderContext ) { AjaxOperation operation = AjaxHelper . getCurrentOperation ( ) ; if ( operation == null ) { // the request attribute that we place in the ui context in the action phase can't be null throw new SystemException ( "Can't paint AJAX response. Couldn't find the expected reference to the AjaxOperation." ) ; } if ( operation . getTargetContainerId ( ) != null ) { paintContainerResponse ( renderContext , operation ) ; } else { paintResponse ( renderContext , operation ) ; } } | Paints the targeted ajax regions . The format of the response is an agreement between the server and the client side JavaScript handling our ajax response . | 120 | 32 |
19,259 | private void paintContainerResponse ( final RenderContext renderContext , final AjaxOperation operation ) { WebXmlRenderContext webRenderContext = ( WebXmlRenderContext ) renderContext ; XmlStringBuilder xml = webRenderContext . getWriter ( ) ; // Get trigger's context ComponentWithContext trigger = AjaxHelper . getCurrentTriggerAndContext ( ) ; if ( trigger == null ) { throw new SystemException ( "No context available for trigger " + operation . getTriggerId ( ) ) ; } xml . appendTagOpen ( "ui:ajaxtarget" ) ; xml . appendAttribute ( "id" , operation . getTargetContainerId ( ) ) ; xml . appendAttribute ( "action" , AjaxOperation . AjaxAction . REPLACE_CONTENT . getDesc ( ) ) ; xml . appendClose ( ) ; // Paint targets - Assume targets are in the same context as the trigger UIContextHolder . pushContext ( trigger . getContext ( ) ) ; try { for ( String targetId : operation . getTargets ( ) ) { ComponentWithContext target ; if ( targetId . equals ( operation . getTriggerId ( ) ) ) { target = trigger ; } else { target = WebUtilities . getComponentById ( targetId , true ) ; if ( target == null ) { LOG . warn ( "Could not find ajax target to render [" + targetId + "]" ) ; continue ; } } target . getComponent ( ) . paint ( renderContext ) ; } } finally { UIContextHolder . popContext ( ) ; } xml . appendEndTag ( "ui:ajaxtarget" ) ; } | Paint the ajax container response . | 347 | 9 |
19,260 | private boolean isProcessTriggerOnly ( final ComponentWithContext triggerWithContext , final AjaxOperation operation ) { // Target container implies only process the trigger or is Internal Ajax if ( operation . getTargetContainerId ( ) != null || operation . isInternalAjaxRequest ( ) ) { return true ; } WComponent trigger = triggerWithContext . getComponent ( ) ; // Check if trigger is a polling AJAX control if ( trigger instanceof WAjaxControl ) { // Get user context UIContext uic = triggerWithContext . getContext ( ) ; UIContextHolder . pushContext ( uic ) ; try { WAjaxControl ajax = ( WAjaxControl ) trigger ; // Is a polling region so only process trigger if ( ajax . getDelay ( ) > 0 ) { return true ; } } finally { UIContextHolder . popContext ( ) ; } } return false ; } | Check if process this trigger only . | 197 | 7 |
19,261 | public static boolean getHandleErrorWithFatalErrorPageFactory ( ) { Boolean parameterValue = get ( ) . getBoolean ( HANDLE_ERROR_WITH_FATAL_PAGE_FACTORY , null ) ; if ( parameterValue != null ) { return parameterValue ; } // fall-back to the old parameter value if the new value is not set. return get ( ) . getBoolean ( HANDLE_ERROR_WITH_FATAL_PAGE_FACTORY_DEPRECATED , false ) ; } | The flag indicating whether to handle an error with a fatal error page factory . | 117 | 15 |
19,262 | public static String getRendererOverride ( final String classname ) { if ( StringUtils . isBlank ( classname ) ) { throw new IllegalArgumentException ( "classname cannot be blank." ) ; } return get ( ) . getString ( RENDERER_OVERRIDE_PREFIX + classname ) ; } | The overridden renderer class for the given fully qualified classname . | 73 | 14 |
19,263 | public static String getResponseCacheHeaderSettings ( final String contentType ) { String parameter = MessageFormat . format ( RESPONSE_CACHE_HEADER_SETTINGS , contentType ) ; return get ( ) . getString ( parameter ) ; } | The response cache header settings for the given contentType . | 54 | 11 |
19,264 | @ Override public void doRender ( final WComponent component , final WebXmlRenderContext renderContext ) { WSuggestions suggestions = ( WSuggestions ) component ; XmlStringBuilder xml = renderContext . getWriter ( ) ; // Cache key for a lookup table String dataKey = suggestions . getListCacheKey ( ) ; // Use AJAX if not using a cached list and have a refresh action boolean useAjax = dataKey == null && suggestions . getRefreshAction ( ) != null ; // Start tag xml . appendTagOpen ( "ui:suggestions" ) ; xml . appendAttribute ( "id" , component . getId ( ) ) ; xml . appendOptionalAttribute ( "class" , component . getHtmlClass ( ) ) ; xml . appendOptionalAttribute ( "track" , component . isTracking ( ) , "true" ) ; xml . appendOptionalAttribute ( "min" , suggestions . getMinRefresh ( ) > 0 , suggestions . getMinRefresh ( ) ) ; xml . appendOptionalAttribute ( "ajax" , useAjax , "true" ) ; xml . appendOptionalAttribute ( "data" , dataKey ) ; WSuggestions . Autocomplete autocomplete = suggestions . getAutocomplete ( ) ; if ( autocomplete == WSuggestions . Autocomplete . LIST ) { xml . appendOptionalAttribute ( "autocomplete" , "list" ) ; } xml . appendClose ( ) ; // Check if this is the current AJAX trigger boolean isTrigger = useAjax && AjaxHelper . isCurrentAjaxTrigger ( suggestions ) ; // Render suggestions if ( isTrigger || ( dataKey == null && ! useAjax ) ) { for ( String suggestion : suggestions . getSuggestions ( ) ) { xml . appendTagOpen ( "ui:suggestion" ) ; xml . appendAttribute ( "value" , suggestion ) ; xml . appendEnd ( ) ; } } // End tag xml . appendEndTag ( "ui:suggestions" ) ; } | Paints the given WSuggestions . | 432 | 8 |
19,265 | @ Override public void handleRequest ( final Request request ) { if ( ! isDisabled ( ) ) { final SelectToggleModel model = getComponentModel ( ) ; String requestParam = request . getParameter ( getId ( ) ) ; final State newValue ; if ( "all" . equals ( requestParam ) ) { newValue = State . ALL ; } else if ( "none" . equals ( requestParam ) ) { newValue = State . NONE ; } else if ( "some" . equals ( requestParam ) ) { newValue = State . SOME ; } else { newValue = model . state ; } if ( ! newValue . equals ( model . state ) ) { setState ( newValue ) ; } if ( ! model . clientSide && model . target != null && ! State . SOME . equals ( newValue ) ) { // We need to change the selections *after* all components // Have updated themselves from the request, as they may change // their values when their handleRequest methods are called. invokeLater ( new Runnable ( ) { @ Override public void run ( ) { setSelections ( model . target , State . ALL . equals ( newValue ) ) ; } } ) ; } } } | Override handleRequest to handle selection toggling if server - side processing is being used . | 260 | 18 |
19,266 | private static void setSelections ( final WComponent component , final boolean selected ) { if ( component instanceof WCheckBox ) { ( ( WCheckBox ) component ) . setSelected ( selected ) ; } else if ( component instanceof WCheckBoxSelect ) { WCheckBoxSelect select = ( WCheckBoxSelect ) component ; select . setSelected ( selected ? select . getOptions ( ) : new ArrayList ( 0 ) ) ; } else if ( component instanceof WMultiSelect ) { WMultiSelect list = ( WMultiSelect ) component ; list . setSelected ( selected ? list . getOptions ( ) : new ArrayList ( 0 ) ) ; } else if ( component instanceof WDataTable ) { WDataTable table = ( WDataTable ) component ; if ( table . getSelectMode ( ) == SelectMode . MULTIPLE ) { if ( selected ) { TableDataModel model = table . getDataModel ( ) ; int rowCount = model . getRowCount ( ) ; List < Integer > indices = new ArrayList <> ( rowCount ) ; for ( int i = 0 ; i < rowCount ; i ++ ) { if ( model . isSelectable ( i ) ) { indices . add ( i ) ; } } table . setSelectedRows ( indices ) ; } else { table . setSelectedRows ( new ArrayList < Integer > ( 0 ) ) ; } } } else if ( component instanceof Container ) { Container container = ( Container ) component ; final int childCount = container . getChildCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { WComponent child = container . getChildAt ( i ) ; setSelections ( child , selected ) ; } } } | Sets the selections for the given context . | 373 | 9 |
19,267 | private void buildSectionHeaders ( ) { // Update Artist maps HashMap < String , List < com . ftinc . kit . attributr . model . Library > > currMap = new HashMap <> ( ) ; // Loop through tuneRefs for ( int i = 0 ; i < getItemCount ( ) ; i ++ ) { com . ftinc . kit . attributr . model . Library library = getItem ( i ) ; String license = library . license . formalName ( ) ; List < com . ftinc . kit . attributr . model . Library > libraries = currMap . get ( license ) ; if ( libraries != null ) { libraries . add ( library ) ; currMap . put ( license , libraries ) ; } else { libraries = new ArrayList <> ( ) ; libraries . add ( library ) ; currMap . put ( license , libraries ) ; } } // Update maps mHeaders . clear ( ) ; mHeaders . addAll ( currMap . values ( ) ) ; mTitles . clear ( ) ; mTitles . addAll ( currMap . keySet ( ) ) ; } | Build the section headers for use in creating the headers | 243 | 10 |
19,268 | public void setChangeLog ( ChangeLog log ) { mChangeLog = log ; // Clear out any existing entries clear ( ) ; //sort all the changes Collections . sort ( mChangeLog . versions , new VersionComparator ( ) ) ; // Iterate and add all the 'Change' objects in the adapter for ( Version version : mChangeLog . versions ) { addAll ( version . changes ) ; } // Notify content has changed notifyDataSetChanged ( ) ; } | Set the changelog for this adapter | 99 | 8 |
19,269 | @ SuppressLint ( "NewApi" ) @ Override public void onItemClick ( View v , com . ftinc . kit . attributr . model . Library item , int position ) { if ( BuildUtils . isLollipop ( ) ) { v . setElevation ( SizeUtils . dpToPx ( this , 4 ) ) ; } View name = ButterKnife . findById ( v , R . id . line_1 ) ; View author = ButterKnife . findById ( v , R . id . line_2 ) ; Pair < View , String > [ ] transitions = new Pair [ ] { new Pair <> ( v , "display_content" ) , new Pair <> ( name , "library_name" ) , new Pair <> ( author , "library_author" ) , new Pair <> ( mToolbar , "app_bar" ) } ; Intent details = new Intent ( this , com . ftinc . kit . attributr . ui . DetailActivity . class ) ; details . putExtra ( com . ftinc . kit . attributr . ui . DetailActivity . EXTRA_LIBRARY , item ) ; startActivity ( details ) ; // UIUtils.startActivityWithTransition(this, details, transitions); } | Called when a Library item is clicked . | 279 | 9 |
19,270 | private void parseExtras ( Bundle icicle ) { Intent intent = getIntent ( ) ; if ( intent != null ) { mXmlConfigId = intent . getIntExtra ( EXTRA_CONFIG , - 1 ) ; mTitle = intent . getStringExtra ( EXTRA_TITLE ) ; } if ( icicle != null ) { mXmlConfigId = icicle . getInt ( EXTRA_CONFIG , - 1 ) ; mTitle = icicle . getString ( EXTRA_TITLE ) ; } if ( mXmlConfigId == - 1 ) finish ( ) ; // Set title if ( ! TextUtils . isEmpty ( mTitle ) ) getSupportActionBar ( ) . setTitle ( mTitle ) ; // Apply Configuration List < com . ftinc . kit . attributr . model . Library > libs = com . ftinc . kit . attributr . internal . Parser . parse ( this , mXmlConfigId ) ; mAdapter = new com . ftinc . kit . attributr . ui . LibraryAdapter ( ) ; mAdapter . addAll ( libs ) ; mAdapter . sort ( new com . ftinc . kit . attributr . model . Library . LibraryComparator ( ) ) ; mAdapter . notifyDataSetChanged ( ) ; } | Parse the Intent or saved bundle extras for the configuration and title data | 277 | 14 |
19,271 | public static boolean checkForRunningService ( Context ctx , String serviceClassName ) { ActivityManager manager = ( ActivityManager ) ctx . getSystemService ( Context . ACTIVITY_SERVICE ) ; for ( ActivityManager . RunningServiceInfo service : manager . getRunningServices ( Integer . MAX_VALUE ) ) { if ( serviceClassName . equals ( service . service . getClassName ( ) ) ) { return true ; } } return false ; } | Check for a running service | 96 | 5 |
19,272 | public static Intent openPlayStore ( Context context , boolean openInBrowser ) { String appPackageName = context . getPackageName ( ) ; Intent marketIntent = new Intent ( Intent . ACTION_VIEW , Uri . parse ( "market://details?id=" + appPackageName ) ) ; if ( isIntentAvailable ( context , marketIntent ) ) { return marketIntent ; } if ( openInBrowser ) { return openLink ( "https://play.google.com/store/apps/details?id=" + appPackageName ) ; } return marketIntent ; } | Open app page at Google Play | 123 | 6 |
19,273 | public static Intent sendEmail ( String to , String subject , String text ) { return sendEmail ( new String [ ] { to } , subject , text ) ; } | Send email message | 34 | 3 |
19,274 | public static Intent shareText ( String subject , String text ) { Intent intent = new Intent ( ) ; intent . setAction ( Intent . ACTION_SEND ) ; if ( ! TextUtils . isEmpty ( subject ) ) { intent . putExtra ( Intent . EXTRA_SUBJECT , subject ) ; } intent . putExtra ( Intent . EXTRA_TEXT , text ) ; intent . setType ( "text/plain" ) ; return intent ; } | Share text via thirdparty app like twitter facebook email sms etc . | 97 | 14 |
19,275 | public static Intent showLocation ( float latitude , float longitude , Integer zoomLevel ) { Intent intent = new Intent ( ) ; intent . setAction ( Intent . ACTION_VIEW ) ; String data = String . format ( "geo:%s,%s" , latitude , longitude ) ; if ( zoomLevel != null ) { data = String . format ( "%s?z=%s" , data , zoomLevel ) ; } intent . setData ( Uri . parse ( data ) ) ; return intent ; } | Opens the Maps application to the given location . | 109 | 10 |
19,276 | public static Intent findLocation ( String query ) { Intent intent = new Intent ( ) ; intent . setAction ( Intent . ACTION_VIEW ) ; String data = String . format ( "geo:0,0?q=%s" , query ) ; intent . setData ( Uri . parse ( data ) ) ; return intent ; } | Opens the Maps application to the given query . | 71 | 10 |
19,277 | public static Intent openLink ( String url ) { // if protocol isn't defined use http by default if ( ! TextUtils . isEmpty ( url ) && ! url . contains ( "://" ) ) { url = "http://" + url ; } Intent intent = new Intent ( ) ; intent . setAction ( Intent . ACTION_VIEW ) ; intent . setData ( Uri . parse ( url ) ) ; return intent ; } | Open a browser window to the URL specified . | 91 | 9 |
19,278 | public static Intent pickImage ( ) { Intent intent = new Intent ( Intent . ACTION_PICK ) ; intent . setType ( "image/*" ) ; return intent ; } | Pick image from gallery | 37 | 4 |
19,279 | public static boolean isCropAvailable ( Context context ) { Intent intent = new Intent ( "com.android.camera.action.CROP" ) ; intent . setType ( "image/*" ) ; return IntentUtils . isIntentAvailable ( context , intent ) ; } | Check that cropping application is available | 59 | 7 |
19,280 | public static Intent photoCapture ( String file ) { Uri uri = Uri . fromFile ( new File ( file ) ) ; Intent intent = new Intent ( MediaStore . ACTION_IMAGE_CAPTURE ) ; intent . putExtra ( MediaStore . EXTRA_OUTPUT , uri ) ; return intent ; } | Call standard camera application for capturing an image | 68 | 8 |
19,281 | public static boolean isIntentAvailable ( Context context , Intent intent ) { PackageManager packageManager = context . getPackageManager ( ) ; List < ResolveInfo > list = packageManager . queryIntentActivities ( intent , PackageManager . MATCH_DEFAULT_ONLY ) ; return list . size ( ) > 0 ; } | Check that in the system exists application which can handle this intent | 70 | 12 |
19,282 | public static float spToPx ( Context ctx , float spSize ) { return TypedValue . applyDimension ( TypedValue . COMPLEX_UNIT_SP , spSize , ctx . getResources ( ) . getDisplayMetrics ( ) ) ; } | Convert Scale - Dependent Pixels to actual pixels | 58 | 11 |
19,283 | public void setForegroundGravity ( int foregroundGravity ) { if ( mForegroundGravity != foregroundGravity ) { if ( ( foregroundGravity & Gravity . RELATIVE_HORIZONTAL_GRAVITY_MASK ) == 0 ) { foregroundGravity |= Gravity . START ; } if ( ( foregroundGravity & Gravity . VERTICAL_GRAVITY_MASK ) == 0 ) { foregroundGravity |= Gravity . TOP ; } mForegroundGravity = foregroundGravity ; if ( mForegroundGravity == Gravity . FILL && mForeground != null ) { Rect padding = new Rect ( ) ; mForeground . getPadding ( padding ) ; } requestLayout ( ) ; } } | Describes how the foreground is positioned . Defaults to START and TOP . | 159 | 15 |
19,284 | public void setForeground ( Drawable drawable ) { if ( mForeground != drawable ) { if ( mForeground != null ) { mForeground . setCallback ( null ) ; unscheduleDrawable ( mForeground ) ; } mForeground = drawable ; if ( drawable != null ) { setWillNotDraw ( false ) ; drawable . setCallback ( this ) ; if ( drawable . isStateful ( ) ) { drawable . setState ( getDrawableState ( ) ) ; } if ( mForegroundGravity == Gravity . FILL ) { Rect padding = new Rect ( ) ; drawable . getPadding ( padding ) ; } } else { setWillNotDraw ( true ) ; } requestLayout ( ) ; invalidate ( ) ; } } | Supply a Drawable that is to be rendered on top of all of the child views in the frame layout . Any padding in the Drawable will be taken into account by ensuring that the children are inset to be placed inside of the padding area . | 169 | 51 |
19,285 | public static int crapToDisk ( Context ctx , String filename , byte [ ] data ) { int code = IO_FAIL ; File dir = Environment . getExternalStorageDirectory ( ) ; File output = new File ( dir , filename ) ; try { FileOutputStream fos = new FileOutputStream ( output ) ; try { fos . write ( data ) ; code = IO_SUCCESS ; } catch ( IOException e ) { code = IO_FAIL ; } finally { fos . close ( ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } return code ; } | Dump Data straight to the SDCard | 133 | 9 |
19,286 | public static Bitmap getVideoThumbnail ( String videoPath ) { MediaMetadataRetriever mmr = new MediaMetadataRetriever ( ) ; mmr . setDataSource ( videoPath ) ; return mmr . getFrameAtTime ( ) ; } | Get a thumbnail bitmap for a given video | 55 | 9 |
19,287 | public static void getVideoThumbnail ( String videoPath , final VideoThumbnailCallback cb ) { new AsyncTask < String , Void , Bitmap > ( ) { @ Override protected Bitmap doInBackground ( String ... params ) { if ( params . length > 0 ) { String path = params [ 0 ] ; if ( ! TextUtils . isEmpty ( path ) ) { return getVideoThumbnail ( path ) ; } } return null ; } @ Override protected void onPostExecute ( Bitmap bitmap ) { cb . onThumbnail ( bitmap ) ; } } . execute ( videoPath ) ; } | Get the thumbnail of a video asynchronously | 130 | 9 |
19,288 | public static boolean copy ( File source , File output ) { // Check to see if output exists if ( output . exists ( ) && output . canWrite ( ) ) { // Delete the existing file, and create a new one if ( output . delete ( ) ) { try { output . createNewFile ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } else if ( ! output . exists ( ) ) { try { output . createNewFile ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } // now that we have performed a prelimanary check on the output, time to copy if ( source . exists ( ) && source . canRead ( ) ) { try { FileInputStream fis = new FileInputStream ( source ) ; FileOutputStream fos = new FileOutputStream ( output ) ; byte [ ] buffer = new byte [ 1024 ] ; int len = 0 ; while ( ( len = fis . read ( buffer ) ) > 0 ) { fos . write ( buffer , 0 , len ) ; } fis . close ( ) ; fos . close ( ) ; return true ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } return false ; } | Copy a file from it s source input to the specified output file if it can . | 294 | 17 |
19,289 | public static String fancyTimestamp ( long epoch ) { // First, check to see if it's within 1 minute of the current date if ( System . currentTimeMillis ( ) - epoch < 60000 ) { return "Just now" ; } // Get calendar for just now Calendar now = Calendar . getInstance ( ) ; // Generate Calendar for this time Calendar cal = Calendar . getInstance ( ) ; cal . setTimeInMillis ( epoch ) ; // Based on the date, determine what to print out // 1) Determine if time is the same day if ( cal . get ( YEAR ) == now . get ( YEAR ) ) { if ( cal . get ( MONTH ) == now . get ( MONTH ) ) { if ( cal . get ( DAY_OF_MONTH ) == now . get ( DAY_OF_MONTH ) ) { // Return just the time SimpleDateFormat format = new SimpleDateFormat ( "h:mm a" ) ; return format . format ( cal . getTime ( ) ) ; } else { // Return the day and time SimpleDateFormat format = new SimpleDateFormat ( "EEE, h:mm a" ) ; return format . format ( cal . getTime ( ) ) ; } } else { SimpleDateFormat format = new SimpleDateFormat ( "EEE, MMM d, h:mm a" ) ; return format . format ( cal . getTime ( ) ) ; } } else { SimpleDateFormat format = new SimpleDateFormat ( "M/d/yy" ) ; return format . format ( cal . getTime ( ) ) ; } } | Generate a fancy timestamp based on unix epoch time that is more user friendly than just a raw output by collapsing the time into manageable formats based on how much time has elapsed since epoch | 337 | 37 |
19,290 | public static String formatHumanFriendlyShortDate ( final Context context , long timestamp ) { long localTimestamp , localTime ; long now = System . currentTimeMillis ( ) ; TimeZone tz = TimeZone . getDefault ( ) ; localTimestamp = timestamp + tz . getOffset ( timestamp ) ; localTime = now + tz . getOffset ( now ) ; long dayOrd = localTimestamp / 86400000L ; long nowOrd = localTime / 86400000L ; if ( dayOrd == nowOrd ) { return context . getString ( R . string . day_title_today ) ; } else if ( dayOrd == nowOrd - 1 ) { return context . getString ( R . string . day_title_yesterday ) ; } else if ( dayOrd == nowOrd + 1 ) { return context . getString ( R . string . day_title_tomorrow ) ; } else { return formatShortDate ( context , new Date ( timestamp ) ) ; } } | Returns Today Tomorrow Yesterday or a short date format . | 212 | 10 |
19,291 | public static boolean isColorDark ( int color ) { return ( ( 30 * Color . red ( color ) + 59 * Color . green ( color ) + 11 * Color . blue ( color ) ) / 100 ) <= BRIGHTNESS_THRESHOLD ; } | Calculate whether a color is light or dark based on a commonly known brightness formula . | 55 | 18 |
19,292 | @ Override public View getView ( int position , View convertView , ViewGroup parent ) { VH holder ; if ( convertView == null ) { // Load the view from scratch convertView = inflater . inflate ( viewResource , parent , false ) ; // Load the ViewHolder holder = createHolder ( convertView ) ; // set holder to the tag convertView . setTag ( holder ) ; } else { // Pull the view holder from convertView's tag holder = ( VH ) convertView . getTag ( ) ; } // bind the data to the holder bindHolder ( holder , position , getItem ( position ) ) ; return convertView ; } | Called to retrieve the view | 141 | 6 |
19,293 | private static boolean validateVersion ( Context ctx , ChangeLog clog ) { // Get Preferences SharedPreferences prefs = PreferenceManager . getDefaultSharedPreferences ( ctx ) ; int lastSeen = prefs . getInt ( PREF_CHANGELOG_LAST_SEEN , - 1 ) ; // Second sort versions by it's code int latest = Integer . MIN_VALUE ; for ( Version version : clog . versions ) { if ( version . code > latest ) { latest = version . code ; } } // Get applications current version if ( latest > lastSeen ) { if ( ! BuildConfig . DEBUG ) prefs . edit ( ) . putInt ( PREF_CHANGELOG_LAST_SEEN , latest ) . apply ( ) ; return true ; } return false ; } | Validate the last seen stored verion code against the current changelog configuration to see if there is any updates and whether or not we should show the changelog dialog when called . | 175 | 38 |
19,294 | public void enableWatcher ( TextWatcher watcher , boolean enabled ) { int index = mWatchers . indexOfValue ( watcher ) ; if ( index >= 0 ) { int key = mWatchers . keyAt ( index ) ; mEnabledKeys . put ( key , enabled ) ; } } | Enable or Disable a text watcher by reference | 66 | 9 |
19,295 | private void parseAttributes ( Context context , AttributeSet attrs , int defStyle ) { int defaultColor = context . getResources ( ) . getColor ( R . color . black26 ) ; final TypedArray a = context . obtainStyledAttributes ( attrs , R . styleable . EmptyView , defStyle , 0 ) ; if ( a == null ) { mEmptyMessageColor = defaultColor ; mEmptyActionColor = defaultColor ; mEmptyMessageTextSize = ( int ) SizeUtils . dpToPx ( context , 18 ) ; mEmptyActionTextSize = ( int ) SizeUtils . dpToPx ( context , 14 ) ; mEmptyMessageTypeface = Face . ROBOTO_REGULAR ; mEmptyIconPadding = getResources ( ) . getDimensionPixelSize ( R . dimen . activity_padding ) ; return ; } // Parse attributes mEmptyIcon = a . getResourceId ( R . styleable . EmptyView_emptyIcon , - 1 ) ; mEmptyIconSize = a . getDimensionPixelSize ( R . styleable . EmptyView_emptyIconSize , - 1 ) ; mEmptyIconColor = a . getColor ( R . styleable . EmptyView_emptyIconColor , defaultColor ) ; mEmptyIconPadding = a . getDimensionPixelSize ( R . styleable . EmptyView_emptyIconPadding , getResources ( ) . getDimensionPixelSize ( R . dimen . activity_padding ) ) ; mEmptyMessage = a . getString ( R . styleable . EmptyView_emptyMessage ) ; mEmptyMessageColor = a . getColor ( R . styleable . EmptyView_emptyMessageColor , defaultColor ) ; int typeface = a . getInt ( R . styleable . EmptyView_emptyMessageTypeface , 0 ) ; mEmptyMessageTypeface = MessageTypeface . from ( typeface ) . getTypeface ( ) ; mEmptyMessageTextSize = a . getDimensionPixelSize ( R . styleable . EmptyView_emptyMessageTextSize , ( int ) SizeUtils . dpToPx ( context , 18 ) ) ; mEmptyActionColor = a . getColor ( R . styleable . EmptyView_emptyActionColor , defaultColor ) ; mEmptyActionText = a . getString ( R . styleable . EmptyView_emptyActionText ) ; mEmptyActionTextSize = a . getDimensionPixelSize ( R . styleable . EmptyView_emptyActionTextSize , ( int ) SizeUtils . dpToPx ( context , 14 ) ) ; mState = a . getInt ( R . styleable . EmptyView_emptyState , STATE_EMPTY ) ; a . recycle ( ) ; } | Parse XML attributes | 586 | 4 |
19,296 | public void setIcon ( Drawable drawable ) { mIcon . setImageDrawable ( drawable ) ; mIcon . setVisibility ( View . VISIBLE ) ; } | Set the icon for this empty view | 37 | 7 |
19,297 | public void setIconSize ( int size ) { mEmptyIconSize = size ; int width = mEmptyIconSize == - 1 ? WRAP_CONTENT : mEmptyIconSize ; int height = mEmptyIconSize == - 1 ? WRAP_CONTENT : mEmptyIconSize ; LinearLayout . LayoutParams iconParams = new LinearLayout . LayoutParams ( width , height ) ; mIcon . setLayoutParams ( iconParams ) ; } | Set the size of the icon in the center of the view | 98 | 12 |
19,298 | public void setActionLabel ( CharSequence label ) { mEmptyActionText = label ; mAction . setText ( mEmptyActionText ) ; mAction . setVisibility ( TextUtils . isEmpty ( mEmptyActionText ) ? View . GONE : View . VISIBLE ) ; } | Set the action button label this in - turn enables it . Pass null to disable . | 63 | 17 |
19,299 | @ Deprecated public void setLoading ( ) { mState = STATE_LOADING ; mProgress . setVisibility ( View . VISIBLE ) ; mAction . setVisibility ( View . GONE ) ; mMessage . setVisibility ( View . GONE ) ; mIcon . setVisibility ( View . GONE ) ; } | Set this view to loading state to show a loading indicator and hide the other parts of this view . | 71 | 20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.