idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
141,800
public static Label newLabel ( String text , String ... styles ) { return setStyleNames ( new Label ( text ) , styles ) ; }
Creates a label with the supplied text and style and optional additional styles .
29
15
141,801
public static InlineLabel newInlineLabel ( String text , String ... styles ) { return setStyleNames ( new InlineLabel ( text ) , styles ) ; }
Creates an inline label with optional styles .
35
9
141,802
public static Label newActionLabel ( String text , ClickHandler onClick ) { return newActionLabel ( text , null , onClick ) ; }
Creates a label that triggers an action using the supplied text and handler .
30
15
141,803
public static Label newActionLabel ( String text , String style , ClickHandler onClick ) { return makeActionLabel ( newLabel ( text , style ) , onClick ) ; }
Creates a label that triggers an action using the supplied text and handler . The label will be styled as specified with an additional style that configures the mouse pointer and adds underline to the text .
37
40
141,804
public static Label makeActionLabel ( Label label , ClickHandler onClick ) { return makeActionable ( label , onClick , null ) ; }
Makes the supplied label into an action label . The label will be styled such that it configures the mouse pointer and adds underline to the text .
30
31
141,805
public static < T extends Widget & HasClickHandlers > T makeActionable ( final T target , final ClickHandler onClick , Value < Boolean > enabled ) { if ( onClick != null ) { if ( enabled != null ) { enabled . addListenerAndTrigger ( new Value . Listener < Boolean > ( ) { public void valueChanged ( Boolean enabled ) { if ( ! enabled && _regi != null ) { _regi . removeHandler ( ) ; _regi = null ; target . removeStyleName ( "actionLabel" ) ; } else if ( enabled && _regi == null ) { _regi = target . addClickHandler ( onClick ) ; target . addStyleName ( "actionLabel" ) ; } } protected HandlerRegistration _regi ; } ) ; } else { target . addClickHandler ( onClick ) ; target . addStyleName ( "actionLabel" ) ; } } return target ; }
Makes the supplied widget actionable which means adding the actionLabel style to it and binding the supplied click handler .
198
23
141,806
public static HTML newHTML ( String text , String ... styles ) { return setStyleNames ( new HTML ( text ) , styles ) ; }
Creates a new HTML element with the specified contents and style .
29
13
141,807
public static Image newImage ( String path , String ... styles ) { return setStyleNames ( new Image ( path ) , styles ) ; }
Creates an image with the supplied path and style .
29
11
141,808
public static Image makeActionImage ( Image image , String tip , ClickHandler onClick ) { if ( tip != null ) { image . setTitle ( tip ) ; } return makeActionable ( image , onClick , null ) ; }
Makes an image into one that responds to clicking .
49
11
141,809
public static TextBox newTextBox ( String text , int maxLength , int visibleLength ) { return initTextBox ( new TextBox ( ) , text , maxLength , visibleLength ) ; }
Creates a text box with all of the configuration that you re bound to want to do .
41
19
141,810
public static String getText ( TextBoxBase box , String defaultAsBlank ) { String s = box . getText ( ) . trim ( ) ; return s . equals ( defaultAsBlank ) ? "" : s ; }
Retrieve the text from the TextBox unless it is the specified default in which case we return .
48
20
141,811
public static TextBox initTextBox ( TextBox box , String text , int maxLength , int visibleLength ) { if ( text != null ) { box . setText ( text ) ; } box . setMaxLength ( maxLength > 0 ? maxLength : 255 ) ; if ( visibleLength > 0 ) { box . setVisibleLength ( visibleLength ) ; } return box ; }
Configures a text box with all of the configuration that you re bound to want to do . This is useful for configuring a PasswordTextBox .
81
30
141,812
public static TextArea newTextArea ( String text , int width , int height ) { TextArea area = new TextArea ( ) ; if ( text != null ) { area . setText ( text ) ; } if ( width > 0 ) { area . setCharacterWidth ( width ) ; } if ( height > 0 ) { area . setVisibleLines ( height ) ; } return area ; }
Creates a text area with all of the configuration that you re bound to want to do .
84
19
141,813
public static LimitedTextArea newTextArea ( String text , int width , int height , int maxLength ) { LimitedTextArea area = new LimitedTextArea ( maxLength , width , height ) ; if ( text != null ) { area . setText ( text ) ; } return area ; }
Creates a limited text area with all of the configuration that you re bound to want to do .
61
20
141,814
public static PushButton newImageButton ( String style , ClickHandler onClick ) { PushButton button = new PushButton ( ) ; maybeAddClickHandler ( button , onClick ) ; return setStyleNames ( button , style , "actionLabel" ) ; }
Creates an image button that changes appearance when you click and hover over it .
54
16
141,815
public static < T extends Widget > T setStyleNames ( T widget , String ... styles ) { int idx = 0 ; for ( String style : styles ) { if ( style == null ) { continue ; } if ( idx ++ == 0 ) { widget . setStyleName ( style ) ; } else { widget . addStyleName ( style ) ; } } return widget ; }
Configures the supplied styles on the supplied widget . Existing styles will not be preserved unless you call this with no - non - null styles . Returns the widget for easy chaining .
81
37
141,816
private ConcurrentManaged < T > newManaged ( ) { return ConcurrentManaged . newManaged ( async , caller , managedOptions , setup , teardown ) ; }
Construct a new managed reference .
39
6
141,817
public static PreProcessor changePrefix ( String from , String to ) { return mkPreProcessorWithMeta ( ( prefix , data , options ) -> { logger . debug ( "changing prefix at '{}' from '{}' to '{}'" , prefix , from , to ) ; return data . entrySet ( ) . stream ( ) . map ( e -> { if ( ! e . getKey ( ) . startsWith ( prefix ) ) return e ; else { String tail = e . getKey ( ) . substring ( prefix . length ( ) ) . replaceFirst ( "^[\\.]?" + Pattern . quote ( from ) , to ) . replaceFirst ( "^\\." , "" ) ; String newKey = isEmptyStr ( tail ) ? prefix : ( prefix + "." + tail ) . replaceFirst ( "^\\." , "" ) ; return entry ( newKey , e . getValue ( ) ) ; } } ) . collect ( Collectors . toMap ( Map . Entry :: getKey , Map . Entry :: getValue ) ) ; } , new ExtensionMeta ( PRE_PROCESSOR_CHANGE_PREFIX , "changePrefix(from '" + from + "' to '" + to + "')" , Arrays . asList ( from , to ) ) ) ; }
change data key prefix from one to other
283
8
141,818
public static Command delay ( final Command command , final int delay ) { return ( command == null ) ? null : new Command ( ) { public void execute ( ) { new Timer ( ) { @ Override public void run ( ) { command . execute ( ) ; } } . schedule ( delay ) ; } } ; }
Returns a command that when executed itself will execute the supplied command after the specified millisecond delay . For convenience purposes if a null command is supplied null is returned .
67
32
141,819
private String escapeSockJsSpecialChars ( char [ ] characters ) { StringBuilder result = new StringBuilder ( ) ; for ( char c : characters ) { if ( isSockJsSpecialChar ( c ) ) { result . append ( ' ' ) . append ( ' ' ) ; String hex = Integer . toHexString ( c ) . toLowerCase ( ) ; for ( int i = 0 ; i < ( 4 - hex . length ( ) ) ; i ++ ) { result . append ( ' ' ) ; } result . append ( hex ) ; } else { result . append ( c ) ; } } return result . toString ( ) ; }
See JSON Unicode Encoding section of SockJS protocol .
140
12
141,820
private boolean isSockJsSpecialChar ( char ch ) { return ch <= ' ' || ch >= ' ' && ch <= ' ' || ch >= ' ' && ch <= ' ' || ch >= ' ' && ch <= ' ' || ch >= ' ' || ch >= ' ' && ch <= ' ' ; }
See escapable_by_server variable in the SockJS protocol test suite .
65
18
141,821
@ MainThread private void scheduleActiveStatusesUpdates ( EventTarget target , EventStatus status ) { for ( Event event : activeEvents ) { for ( EventMethod method : target . methods ) { if ( event . getKey ( ) . equals ( method . eventKey ) && method . type == EventMethod . Type . STATUS ) { Utils . log ( event . getKey ( ) , method , "Scheduling status update for new target" ) ; executionQueue . addFirst ( Task . create ( this , target , method , event , status ) ) ; } } } }
Schedules status updates of all active events for given target .
123
13
141,822
@ MainThread private void scheduleStatusUpdates ( Event event , EventStatus status ) { for ( EventTarget target : targets ) { for ( EventMethod method : target . methods ) { if ( event . getKey ( ) . equals ( method . eventKey ) && method . type == EventMethod . Type . STATUS ) { Utils . log ( event . getKey ( ) , method , "Scheduling status update" ) ; executionQueue . add ( Task . create ( this , target , method , event , status ) ) ; } } } }
Schedules status update of given event for all registered targets .
116
13
141,823
@ MainThread private void scheduleSubscribersInvocation ( Event event ) { for ( EventTarget target : targets ) { for ( EventMethod method : target . methods ) { if ( event . getKey ( ) . equals ( method . eventKey ) && method . type == EventMethod . Type . SUBSCRIBE ) { Utils . log ( event . getKey ( ) , method , "Scheduling event execution" ) ; ( ( EventBase ) event ) . handlersCount ++ ; Task task = Task . create ( this , target , method , event ) ; executionQueue . add ( task ) ; } } } }
Schedules handling of given event for all registered targets .
132
12
141,824
@ MainThread private void scheduleResultCallbacks ( Event event , EventResult result ) { for ( EventTarget target : targets ) { for ( EventMethod method : target . methods ) { if ( event . getKey ( ) . equals ( method . eventKey ) && method . type == EventMethod . Type . RESULT ) { Utils . log ( event . getKey ( ) , method , "Scheduling result callback" ) ; executionQueue . add ( Task . create ( this , target , method , event , result ) ) ; } } } }
Schedules sending result to all registered targets .
116
10
141,825
@ MainThread private void scheduleFailureCallbacks ( Event event , EventFailure failure ) { // Sending failure callback for explicit handlers of given event for ( EventTarget target : targets ) { for ( EventMethod method : target . methods ) { if ( event . getKey ( ) . equals ( method . eventKey ) && method . type == EventMethod . Type . FAILURE ) { Utils . log ( event . getKey ( ) , method , "Scheduling failure callback" ) ; executionQueue . add ( Task . create ( this , target , method , event , failure ) ) ; } } } // Sending failure callback to general handlers (with no particular event key) for ( EventTarget target : targets ) { for ( EventMethod method : target . methods ) { if ( EventsParams . EMPTY_KEY . equals ( method . eventKey ) && method . type == EventMethod . Type . FAILURE ) { Utils . log ( event . getKey ( ) , method , "Scheduling general failure callback" ) ; executionQueue . add ( Task . create ( this , target , method , event , failure ) ) ; } } } }
Schedules sending failure callback to all registered targets .
242
11
141,826
@ MainThread private void handleRegistration ( Object targetObj ) { if ( targetObj == null ) { throw new NullPointerException ( "Target cannot be null" ) ; } for ( EventTarget target : targets ) { if ( target . targetObj == targetObj ) { Utils . logE ( targetObj , "Already registered" ) ; return ; } } EventTarget target = new EventTarget ( targetObj ) ; targets . add ( target ) ; Utils . log ( targetObj , "Registered" ) ; scheduleActiveStatusesUpdates ( target , EventStatus . STARTED ) ; executeTasks ( false ) ; }
Handles target object registration
132
5
141,827
@ MainThread private void handleUnRegistration ( Object targetObj ) { if ( targetObj == null ) { throw new NullPointerException ( "Target cannot be null" ) ; } EventTarget target = null ; for ( Iterator < EventTarget > iterator = targets . iterator ( ) ; iterator . hasNext ( ) ; ) { EventTarget listTarget = iterator . next ( ) ; if ( listTarget . targetObj == targetObj ) { iterator . remove ( ) ; target = listTarget ; target . targetObj = null ; break ; } } if ( target == null ) { Utils . logE ( targetObj , "Was not registered" ) ; } Utils . log ( targetObj , "Unregistered" ) ; }
Handles target un - registration
153
6
141,828
@ MainThread private void handleEventPost ( Event event ) { Utils . log ( event . getKey ( ) , "Handling posted event" ) ; int sizeBefore = executionQueue . size ( ) ; scheduleStatusUpdates ( event , EventStatus . STARTED ) ; scheduleSubscribersInvocation ( event ) ; if ( ( ( EventBase ) event ) . handlersCount == 0 ) { Utils . log ( event . getKey ( ) , "No subscribers found" ) ; // Removing all scheduled STARTED status callbacks while ( executionQueue . size ( ) > sizeBefore ) { executionQueue . removeLast ( ) ; } } else { activeEvents . add ( event ) ; executeTasks ( false ) ; } }
Handles event posting
155
4
141,829
@ MainThread private void handleEventResult ( Event event , EventResult result ) { if ( ! activeEvents . contains ( event ) ) { Utils . logE ( event . getKey ( ) , "Cannot send result of finished event" ) ; return ; } scheduleResultCallbacks ( event , result ) ; executeTasks ( false ) ; }
Handles event result
74
4
141,830
@ MainThread private void handleEventFailure ( Event event , EventFailure failure ) { if ( ! activeEvents . contains ( event ) ) { Utils . logE ( event . getKey ( ) , "Cannot send failure callback of finished event" ) ; return ; } scheduleFailureCallbacks ( event , failure ) ; executeTasks ( false ) ; }
Handles event failure
75
4
141,831
@ MainThread private void handleTaskFinished ( Task task ) { if ( task . method . type != EventMethod . Type . SUBSCRIBE ) { // We are not interested in finished callbacks, only finished subscriber calls return ; } if ( task . method . isSingleThread ) { Utils . log ( task , "Single-thread method is no longer in use" ) ; task . method . isInUse = false ; } Event event = task . event ; if ( ! activeEvents . contains ( event ) ) { Utils . logE ( event . getKey ( ) , "Cannot finish already finished event" ) ; return ; } ( ( EventBase ) event ) . handlersCount -- ; if ( ( ( EventBase ) event ) . handlersCount == 0 ) { // No more running handlers activeEvents . remove ( event ) ; scheduleStatusUpdates ( event , EventStatus . FINISHED ) ; executeTasks ( false ) ; } }
Handles finished event
203
4
141,832
@ MainThread private void handleTasksExecution ( ) { if ( isExecuting || executionQueue . isEmpty ( ) ) { return ; // Nothing to dispatch } try { isExecuting = true ; handleTasksExecutionWrapped ( ) ; } finally { isExecuting = false ; } }
Handles scheduled execution tasks
64
5
141,833
public static < T > ValueLabel < T > create ( Value < T > value , String ... styles ) { return new ValueLabel < T > ( value , styles ) ; }
Creates a value label for the supplied value with the specified CSS styles .
37
15
141,834
private boolean isApply ( ChangeSet changeSet ) { // 必须包含 PENDING_DROPS 不然无法在只删除列时产生变更脚本 return ( changeSet . getType ( ) == ChangeSetType . APPLY || changeSet . getType ( ) == ChangeSetType . PENDING_DROPS ) && ! changeSet . getChangeSetChildren ( ) . isEmpty ( ) ; }
Return true if the changeSet is APPLY and not empty .
117
14
141,835
protected void writeApplyDdl ( DdlWrite write ) { scriptInfo . setApplyDdl ( "-- drop dependencies\n" + write . applyDropDependencies ( ) . getBuffer ( ) + "\n" + "-- apply changes\n" + write . apply ( ) . getBuffer ( ) + write . applyForeignKeys ( ) . getBuffer ( ) + write . applyHistoryView ( ) . getBuffer ( ) + write . applyHistoryTrigger ( ) . getBuffer ( ) ) ; }
Write the Apply DDL buffers to the writer .
108
10
141,836
public void show ( PopupPanel popup , Widget onCenter ) { // determine the ypos of our onCenter target in case it's in the currently popped up popup, // because after we hide that popup we won't be able to compute it int ypos = ( onCenter == null ) ? 0 : ( onCenter . getAbsoluteTop ( ) + onCenter . getOffsetHeight ( ) / 2 ) ; PopupPanel showing = _showingPopup . get ( ) ; if ( showing != null ) { // null _showingPopup before hiding to avoid triggering the close handler logic _popups . add ( showing ) ; _showingPopup . update ( null ) ; showing . hide ( true ) ; } if ( onCenter == null ) { popup . center ( ) ; // this will show the popup } else { Popups . centerOn ( popup , ypos ) . show ( ) ; } // now that we've centered and shown our popup (which may have involved showing, hiding and // showing it again), we can add a close handler and listen for it to actually close popup . addCloseHandler ( new CloseHandler < PopupPanel > ( ) { public void onClose ( CloseEvent < PopupPanel > event ) { if ( _showingPopup . get ( ) == event . getTarget ( ) ) { if ( _popups . size ( ) > 0 ) { _showingPopup . update ( _popups . remove ( _popups . size ( ) - 1 ) ) ; _showingPopup . get ( ) . show ( ) ; } else { _showingPopup . update ( null ) ; } } } } ) ; _showingPopup . update ( popup ) ; }
Pushes any currently showing popup onto the stack and displays the supplied popup . The popup will centered horizontally in the page and centered vertically around the supplied widget .
367
31
141,837
public void clear ( ) { _popups . clear ( ) ; if ( _showingPopup . get ( ) != null ) { _showingPopup . get ( ) . hide ( true ) ; _showingPopup . update ( null ) ; } }
Clears out the stack completely removing all pending popups and clearing any currently showing popup .
57
18
141,838
public static String escapeAttribute ( String value ) { for ( int ii = 0 ; ii < ATTR_ESCAPES . length ; ++ ii ) { value = value . replace ( ATTR_ESCAPES [ ii ] [ 0 ] , ATTR_ESCAPES [ ii ] [ 1 ] ) ; } return value ; }
Escapes user or deployment values that we need to put into an html attribute .
70
16
141,839
public static String sanitizeAttribute ( String value ) { for ( int ii = 0 ; ii < ATTR_ESCAPES . length ; ++ ii ) { value = value . replace ( ATTR_ESCAPES [ ii ] [ 0 ] , "" ) ; } return value ; }
Nukes special attribute characters . Ideally this would not be needed but some integrations do not accept special characters in attributes .
61
24
141,840
public static String truncate ( String str , int limit , String appendage ) { if ( str == null || str . length ( ) <= limit ) { return str ; } return str . substring ( 0 , limit - appendage . length ( ) ) + appendage ; }
Truncates the string so it has length less than or equal to the given limit . If truncation occurs the result will end with the given appendage . Returns null if the input is null .
58
40
141,841
public static String join ( Iterable < ? > items , String sep ) { Iterator < ? > i = items . iterator ( ) ; if ( ! i . hasNext ( ) ) { return "" ; } StringBuilder buf = new StringBuilder ( String . valueOf ( i . next ( ) ) ) ; while ( i . hasNext ( ) ) { buf . append ( sep ) . append ( i . next ( ) ) ; } return buf . toString ( ) ; }
Joins the given sequence of strings which the given separator string between each consecutive pair .
101
18
141,842
public String createDefinition ( WidgetUtil . FlashObject obj ) { String transparent = obj . transparent ? "transparent" : "opaque" ; String params = "<param name=\"movie\" value=\"" + obj . movie + "\">" + "<param name=\"allowFullScreen\" value=\"true\">" + "<param name=\"wmode\" value=\"" + transparent + "\">" + "<param name=\"bgcolor\" value=\"" + obj . bgcolor + "\">" ; if ( obj . flashVars != null ) { params += "<param name=\"FlashVars\" value=\"" + obj . flashVars + "\">" ; } String tag = "<object id=\"" + obj . ident + "\" type=\"application/x-shockwave-flash\"" ; if ( obj . width . length ( ) > 0 ) { tag += " width=\"" + obj . width + "\"" ; } if ( obj . height . length ( ) > 0 ) { tag += " height=\"" + obj . height + "\"" ; } tag += " allowFullScreen=\"true\" allowScriptAccess=\"sameDomain\">" + params + "</object>" ; return tag ; }
Creates the HTML string definition of an embedded Flash object .
256
12
141,843
public HTML createApplet ( String ident , String archive , String clazz , String width , String height , boolean mayScript , String ptags ) { String html = "<object classid=\"java:" + clazz + ".class\" " + "type=\"application/x-java-applet\" archive=\"" + archive + "\" " + "width=\"" + width + "\" height=\"" + height + "\">" ; if ( mayScript ) { html += "<param name=\"mayscript\" value=\"true\"/>" ; } html += ptags ; html += "</object>" ; return new HTML ( html ) ; }
Creates the HTML needed to display a Java applet .
135
12
141,844
@ Override public void run ( ) { synchronized ( lock ) { if ( ! callables . hasNext ( ) ) { checkEnd ( ) ; return ; } for ( int i = 0 ; i < parallelism && callables . hasNext ( ) ; i ++ ) { setupNext ( callables . next ( ) ) ; } } future . whenCancelled ( ( ) -> { cancel = true ; checkNext ( ) ; } ) ; }
coordinate thread .
95
4
141,845
public static HandlerRegistration bind ( HasKeyDownHandlers target , ClickHandler onEnter ) { return target . addKeyDownHandler ( new EnterClickAdapter ( onEnter ) ) ; }
Binds a listener to the supplied target text box that triggers the supplied click handler when enter is pressed on the text box .
38
25
141,846
public void onKeyDown ( KeyDownEvent event ) { if ( event . getNativeKeyCode ( ) == KeyCodes . KEY_ENTER ) { _onEnter . onClick ( null ) ; } }
from interface KeyDownHandler
45
5
141,847
boolean isMatch ( Class < ? > beanType , Object id ) { return beanType . equals ( this . beanType ) && idMatch ( id ) ; }
Return true if matched by beanType and id value .
35
11
141,848
public static void set ( String path , int expires , String name , String value , String domain ) { String extra = "" ; if ( path . length ( ) > 0 ) { extra += "; path=" + path ; } if ( domain != null ) { extra += "; domain=" + domain ; } doSet ( name , value , expires , extra ) ; }
Sets the specified cookie to the supplied value .
77
10
141,849
public void show ( Popups . Position pos , Widget target ) { Popups . show ( this , pos , target ) ; }
Displays this info popup directly below the specified widget .
28
11
141,850
public String get ( String key , Object ... args ) { // First make the key for GWT-friendly return fetch ( key . replace ( ' ' , ' ' ) , args ) ; }
Translate a key with any number of arguments backed by the Lookup .
40
15
141,851
@ Deprecated public static void configure ( TextBoxBase target , String defaultText ) { DefaultTextListener listener = new DefaultTextListener ( target , defaultText ) ; target . addFocusHandler ( listener ) ; target . addBlurHandler ( listener ) ; }
Configures the target text box to display the supplied default text when it does not have focus and to clear it out when the user selects it to enter text .
54
32
141,852
@ Deprecated public static String getText ( TextBoxBase target , String defaultText ) { String text = target . getText ( ) . trim ( ) ; return text . equals ( defaultText . trim ( ) ) ? "" : text ; }
Returns the contents of the supplied text box accounting for the supplied default text .
51
15
141,853
public void onBlur ( BlurEvent event ) { if ( _target . getText ( ) . trim ( ) . equals ( "" ) ) { _target . setText ( _defaultText ) ; } }
from interface BlurHandler
45
5
141,854
static Object workObject ( Map < String , Object > workList , String name , boolean isArray ) { logger . trace ( "get working object for {}" , name ) ; if ( workList . get ( name ) != null ) return workList . get ( name ) ; else { String [ ] parts = splitName ( name ) ; // parts: (parent, name, isArray) Map < String , Object > parentObj = ( Map < String , Object > ) workObject ( workList , parts [ 0 ] , false ) ; Object theObj = isArray ? new ArrayList < String > ( ) : new HashMap < String , Object > ( ) ; parentObj . put ( parts [ 1 ] , theObj ) ; workList . put ( name , theObj ) ; return theObj ; } }
find work object specified by name create and attach it if not exists
171
13
141,855
public static < T > Constraint checking ( Function < String , T > check , String messageOrKey , boolean isKey , String ... extraMessageArgs ) { return mkSimpleConstraint ( ( ( label , vString , messages ) -> { logger . debug ( "checking for {}" , vString ) ; if ( isEmptyStr ( vString ) ) return null ; else { try { check . apply ( vString ) ; return null ; } catch ( Exception ex ) { String msgTemplate = isKey ? messages . get ( messageOrKey ) : messageOrKey ; List < String > messageArgs = appendList ( Arrays . asList ( vString ) , extraMessageArgs ) ; return String . format ( msgTemplate , messageArgs . toArray ( ) ) ; } } } ) , null ) ; }
make a Constraint which will try to check and collect errors
172
13
141,856
public static Constraint anyPassed ( Constraint ... constraints ) { return ( ( name , data , messages , options ) -> { logger . debug ( "checking any passed for {}" , name ) ; List < Map . Entry < String , String > > errErrors = new ArrayList <> ( ) ; for ( Constraint constraint : constraints ) { List < Map . Entry < String , String > > errors = constraint . apply ( name , data , messages , options ) ; if ( errors . isEmpty ( ) ) return Collections . emptyList ( ) ; else { errErrors . addAll ( errors ) ; } } String label = getLabel ( name , messages , options ) ; String errStr = errErrors . stream ( ) . map ( e -> e . getValue ( ) ) . collect ( Collectors . joining ( ", " , "[" , "]" ) ) ; return Arrays . asList ( entry ( name , String . format ( messages . get ( "error.anypassed" ) , label , errStr ) ) ) ; } ) ; }
make a compound Constraint which checks whether any inputting constraints passed
229
14
141,857
public static List < Integer > indexes ( String name , Map < String , String > data ) { logger . debug ( "get indexes for {}" , name ) ; // matches: 'prefix[index]...' Pattern keyPattern = Pattern . compile ( "^" + Pattern . quote ( name ) + "\\[(\\d+)\\].*$" ) ; return data . keySet ( ) . stream ( ) . map ( key -> { Matcher m = keyPattern . matcher ( key ) ; return m . matches ( ) ? Integer . parseInt ( m . group ( 1 ) ) : - 1 ; } ) . filter ( i -> i >= 0 ) . distinct ( ) . sorted ( ) . collect ( Collectors . toList ( ) ) ; }
Computes the available indexes for the given key in this set of data .
162
15
141,858
public static List < String > keys ( String prefix , Map < String , String > data ) { logger . debug ( "get keys for {}" , prefix ) ; // matches: 'prefix.xxx...' | 'prefix."xxx.t"...' Pattern keyPattern = Pattern . compile ( "^" + Pattern . quote ( prefix ) + "\\.(\"[^\"]+\"|[^\\.]+).*$" ) ; return data . keySet ( ) . stream ( ) . map ( key -> { Matcher m = keyPattern . matcher ( key ) ; return m . matches ( ) ? m . group ( 1 ) : null ; } ) . filter ( k -> k != null ) . distinct ( ) . collect ( Collectors . toList ( ) ) ; }
Computes the available keys for the given prefix in this set of data .
166
15
141,859
public static Map < String , String > json2map ( String prefix , JsonNode json ) { logger . trace ( "json to map - prefix: {}" , prefix ) ; if ( json . isArray ( ) ) { Map < String , String > result = new HashMap <> ( ) ; for ( int i = 0 ; i < json . size ( ) ; i ++ ) { result . putAll ( json2map ( prefix + "[" + i + "]" , json . get ( i ) ) ) ; } return result ; } else if ( json . isObject ( ) ) { Map < String , String > result = new HashMap <> ( ) ; json . fields ( ) . forEachRemaining ( e -> { String newPrefix = isEmptyStr ( prefix ) ? e . getKey ( ) : prefix + "." + e . getKey ( ) ; result . putAll ( json2map ( newPrefix , e . getValue ( ) ) ) ; } ) ; return result ; } else { return newmap ( entry ( prefix , json . asText ( ) ) ) ; } }
Construct data map from inputting jackson json object
238
10
141,860
private String getVersion ( MigrationModel migrationModel ) { String version = migrationConfig . getVersion ( ) ; if ( version == null ) { version = migrationModel . getNextVersion ( initialVersion ) ; } return version ; }
Return the full version for the migration being generated .
47
10
141,861
public < T > Predicate < T > in ( final Collection < ? extends T > target ) { return new Predicate < T > ( ) { public boolean apply ( T arg ) { try { return target . contains ( arg ) ; } catch ( NullPointerException e ) { return false ; } catch ( ClassCastException e ) { return false ; } } } ; }
Returns a predicate that evaluates to true if the object reference being tested is a member of the given collection .
79
21
141,862
public CommandResponse doVagrant ( String vagrantVm , final String ... vagrantCommand ) { CommandResponse response = commandProcessor . run ( aCommand ( "vagrant" ) . withArguments ( vagrantCommand ) . withOptions ( vagrantVm ) ) ; if ( ! response . isSuccessful ( ) ) { throw new RuntimeException ( "Errors during vagrant execution: \n" + response . getErrors ( ) ) ; } // Check for puppet errors. Not vagrant still returns 0 when puppet fails // May not be needed after this PR released: https://github.com/mitchellh/vagrant/pull/1175 for ( String line : response . getOutput ( ) . split ( "\n\u001B" ) ) { if ( line . startsWith ( "[1;35merr:" ) ) { throw new RuntimeException ( "Error in puppet output: " + line ) ; } } return response ; }
Executes vagrant command which means that arguments passed here will be prepended with vagrant
204
18
141,863
private LzoIndex readIndex ( Path file , FileSystem fs ) throws IOException { FSDataInputStream indexIn = null ; try { Path indexFile = new Path ( file . toString ( ) + LZO_INDEX_SUFFIX ) ; if ( ! fs . exists ( indexFile ) ) { // return empty index, fall back to the unsplittable mode return new LzoIndex ( ) ; } long indexLen = fs . getFileStatus ( indexFile ) . getLen ( ) ; int blocks = ( int ) ( indexLen / 8 ) ; LzoIndex index = new LzoIndex ( blocks ) ; indexIn = fs . open ( indexFile ) ; for ( int i = 0 ; i < blocks ; i ++ ) { index . set ( i , indexIn . readLong ( ) ) ; } return index ; } finally { if ( indexIn != null ) { indexIn . close ( ) ; } } }
Read the index of the lzo file .
201
9
141,864
public static void createIndex ( FileSystem fs , Path lzoFile ) throws IOException { Configuration conf = fs . getConf ( ) ; CompressionCodecFactory factory = new CompressionCodecFactory ( fs . getConf ( ) ) ; CompressionCodec codec = factory . getCodec ( lzoFile ) ; ( ( Configurable ) codec ) . setConf ( conf ) ; InputStream lzoIs = null ; FSDataOutputStream os = null ; Path outputFile = new Path ( lzoFile . toString ( ) + LzoTextInputFormat . LZO_INDEX_SUFFIX ) ; Path tmpOutputFile = outputFile . suffix ( ".tmp" ) ; try { FSDataInputStream is = fs . open ( lzoFile ) ; os = fs . create ( tmpOutputFile ) ; LzopDecompressor decompressor = ( LzopDecompressor ) codec . createDecompressor ( ) ; // for reading the header lzoIs = codec . createInputStream ( is , decompressor ) ; int numChecksums = decompressor . getChecksumsCount ( ) ; while ( true ) { // read and ignore, we just want to get to the next int int uncompressedBlockSize = is . readInt ( ) ; if ( uncompressedBlockSize == 0 ) { break ; } else if ( uncompressedBlockSize < 0 ) { throw new EOFException ( ) ; } int compressedBlockSize = is . readInt ( ) ; if ( compressedBlockSize <= 0 ) { throw new IOException ( "Could not read compressed block size" ) ; } long pos = is . getPos ( ) ; // write the pos of the block start os . writeLong ( pos - 8 ) ; // seek to the start of the next block, skip any checksums is . seek ( pos + compressedBlockSize + ( 4 * numChecksums ) ) ; } } finally { if ( lzoIs != null ) { lzoIs . close ( ) ; } if ( os != null ) { os . close ( ) ; } } fs . rename ( tmpOutputFile , outputFile ) ; }
Index an lzo file to allow the input format to split them into separate map jobs .
453
18
141,865
public static List < Domain > getDefinedDomains ( Connect libvirt ) { try { List < Domain > domains = new ArrayList <> ( ) ; String [ ] domainNames = libvirt . listDefinedDomains ( ) ; for ( String name : domainNames ) { domains . add ( libvirt . domainLookupByName ( name ) ) ; } return domains ; } catch ( LibvirtException e ) { throw new LibvirtRuntimeException ( "Unable to list defined domains" , e ) ; } }
Get list of the inactive domains .
110
7
141,866
public static List < Domain > getRunningDomains ( Connect libvirt ) { try { List < Domain > domains = new ArrayList <> ( ) ; int [ ] ids = libvirt . listDomains ( ) ; for ( int id : ids ) { domains . add ( libvirt . domainLookupByID ( id ) ) ; } return domains ; } catch ( LibvirtException e ) { throw new LibvirtRuntimeException ( "Unable to list defined domains" , e ) ; } }
Get list of the active domains .
107
7
141,867
public static Connect getConnection ( String libvirtURL , boolean readOnly ) { connectLock . lock ( ) ; try { return new Connect ( libvirtURL , readOnly ) ; } catch ( LibvirtException e ) { throw new LibvirtRuntimeException ( "Unable to connect to " + libvirtURL , e ) ; } finally { connectLock . unlock ( ) ; } }
Create a connection to libvirt in a thread safe manner .
80
12
141,868
public void addInstance ( Object instance ) throws Exception { if ( isDestroyed ( ) ) { throw new IllegalStateException ( "System already stopped" ) ; } else { startInstance ( instance ) ; if ( methodsMap . get ( instance . getClass ( ) ) . hasFor ( PreDestroy . class ) ) { managedInstances . add ( instance ) ; } } }
Add an additional managed instance
79
5
141,869
public static < T > T bind ( T service , String entryPoint ) { ( ( ServiceDefTarget ) service ) . setServiceEntryPoint ( entryPoint ) ; return service ; }
Binds the supplied service to the specified entry point .
38
11
141,870
@ SuppressWarnings ( "deprecation" ) public static Date toUtc ( Date date ) { if ( date == null ) { return null ; } return new Date ( Date . UTC ( date . getYear ( ) , date . getMonth ( ) , date . getDate ( ) , date . getHours ( ) , date . getMinutes ( ) , date . getSeconds ( ) ) ) ; }
Returns the equivalent of this date when it was in Greenwich . For example a date at 4pm pacific would result in a new date at 4pm gmt or 8am pacific . This has the effect of normalizing the date . It may be used to allow clients to send data requests to the server in absolute time which can then be treated appropriately on the server .
90
75
141,871
public void add ( final Metric metric ) { Preconditions . checkNotNull ( metric ) ; // get the aggregate for this minute MetricAggregate aggregate = getAggregate ( metric . getIdentity ( ) ) ; // add the current metric into the aggregate switch ( metric . getIdentity ( ) . getType ( ) ) { case COUNTER : case TIMER : case AVERAGE : aggregate . setCount ( aggregate . getCount ( ) + 1 ) ; aggregate . setValue ( aggregate . getValue ( ) + metric . getValue ( ) ) ; break ; case GAUGE : aggregate . setCount ( 1 ) ; if ( metric . isIncrement ( ) ) { aggregate . setValue ( aggregate . getValue ( ) + metric . getValue ( ) ) ; } else { aggregate . setValue ( metric . getValue ( ) ) ; } break ; default : LOGGER . info ( "Unable to aggregate {} metric type" , metric . getIdentity ( ) . getType ( ) ) ; break ; } }
Aggregates a single metric into the collection of aggregates
218
12
141,872
private boolean aggregateExistsForCurrentMinute ( final MetricIdentity identity ) { Preconditions . checkNotNull ( identity ) ; if ( aggregates . containsKey ( identity ) ) { if ( aggregates . get ( identity ) . containsKey ( currentMinute ) ) { return true ; } } return false ; }
Determines if the specified aggregate metric exists for the current minute
69
13
141,873
private MetricAggregate getAggregate ( final MetricIdentity identity ) { // get the map from utc minute to aggregate for this metric if ( ! aggregates . containsKey ( identity ) ) { aggregates . put ( identity , new HashMap < Long , MetricAggregate > ( ) ) ; } Map < Long , MetricAggregate > metricAggregates = aggregates . get ( identity ) ; // get the aggregate for this minute if ( ! metricAggregates . containsKey ( currentMinute ) ) { MetricAggregate initialAggregate = MetricAggregate . fromMetricIdentity ( identity , currentMinute ) ; if ( identity . getType ( ) . equals ( MetricMonitorType . GAUGE ) ) { if ( lastValues . containsKey ( identity ) ) { initialAggregate . setValue ( lastValues . get ( identity ) ) ; } } metricAggregates . put ( currentMinute , initialAggregate ) ; } MetricAggregate aggregate = metricAggregates . get ( currentMinute ) ; return aggregate ; }
Retrieves the specified metric for the current minute
228
10
141,874
public static < L > ListenerList < L > addListener ( ListenerList < L > list , L listener ) { if ( list == null ) { list = new ListenerList < L > ( ) ; } list . add ( listener ) ; return list ; }
Adds the supplied listener to the supplied list . If the list is null a new listener list will be created . The supplied or newly created list as appropriate will be returned .
57
34
141,875
public static < L , K > void addListener ( Map < K , ListenerList < L > > map , K key , L listener ) { ListenerList < L > list = map . get ( key ) ; if ( list == null ) { map . put ( key , list = new ListenerList < L > ( ) ) ; } list . add ( listener ) ; }
Adds a listener to the listener list in the supplied map . If no list exists one will be created and mapped to the supplied key .
81
27
141,876
public static < L , K > void removeListener ( Map < K , ListenerList < L > > map , K key , L listener ) { ListenerList < L > list = map . get ( key ) ; if ( list != null ) { list . remove ( listener ) ; } }
Removes a listener from the supplied list in the supplied map .
62
13
141,877
public Migration read ( ) { try ( StringReader reader = new StringReader ( info . getModelDiff ( ) ) ) { JAXBContext jaxbContext = JAXBContext . newInstance ( Migration . class ) ; Unmarshaller unmarshaller = jaxbContext . createUnmarshaller ( ) ; return ( Migration ) unmarshaller . unmarshal ( reader ) ; } catch ( JAXBException e ) { throw new RuntimeException ( e ) ; } }
Read and return the migration from the resource .
110
9
141,878
void add ( final byte type , final Object value ) { final int w = write . getAndIncrement ( ) ; if ( w < size ) { writeAt ( w , type , value ) ; } // countdown could wrap around, however we check the state of finished in here. // MUST be called after write to make sure that results and states are synchronized. final int c = countdown . decrementAndGet ( ) ; if ( c < 0 ) { throw new IllegalStateException ( "already finished (countdown)" ) ; } // if this thread is not the last thread to check-in, do nothing.. if ( c != 0 ) { return ; } // make sure this can only happen once. // This protects against countdown, and write wrapping around which should very rarely // happen. if ( ! done . compareAndSet ( false , true ) ) { throw new IllegalStateException ( "already finished" ) ; } done ( collect ( ) ) ; }
Checks in a doCall back . It also wraps up the group if all the callbacks have checked in .
202
23
141,879
public static synchronized void configure ( final ApiConfiguration config ) { ApiConfiguration . Builder builder = ApiConfiguration . newBuilder ( ) ; builder . apiUrl ( config . getApiUrl ( ) ) ; builder . apiKey ( config . getApiKey ( ) ) ; builder . application ( config . getApplication ( ) ) ; builder . environment ( config . getEnvironment ( ) ) ; if ( config . getEnvDetail ( ) == null ) { builder . envDetail ( EnvironmentDetails . getEnvironmentDetail ( config . getApplication ( ) , config . getEnvironment ( ) ) ) ; } else { builder . envDetail ( config . getEnvDetail ( ) ) ; } CONFIG = builder . build ( ) ; }
Manually configure the metrics api
158
6
141,880
private static synchronized void startup ( ) { try { if ( CONFIG == null ) { CONFIG = ApiConfigurations . fromProperties ( ) ; } ObjectMapper objectMapper = new ObjectMapper ( ) ; AppIdentityService appIdentityService = new AppIdentityService ( CONFIG , objectMapper , true ) ; MetricMonitorService monitorService = new MetricMonitorService ( CONFIG , objectMapper , appIdentityService ) ; MetricSender sender = new MetricSender ( CONFIG , objectMapper , monitorService ) ; BACKGROUND_SERVICE = new MetricBackgroundService ( COLLECTOR , sender ) ; BACKGROUND_SERVICE . start ( ) ; } catch ( Throwable t ) { LOGGER . error ( "Exception starting Stackify Metrics API service" , t ) ; } }
Start up the background thread that is processing metrics
174
9
141,881
public static synchronized void shutdown ( ) { if ( BACKGROUND_SERVICE != null ) { try { BACKGROUND_SERVICE . stop ( ) ; } catch ( Throwable t ) { LOGGER . error ( "Exception stopping Stackify Metrics API service" , t ) ; } INITIALIZED . compareAndSet ( true , false ) ; } }
Shut down the background thread that is processing metrics
76
9
141,882
public < T > WithStaticFinder < T > withFinder ( Class < T > beanType ) { WithStaticFinder < T > withFinder = new WithStaticFinder <> ( beanType ) ; staticFinderReplacement . add ( withFinder ) ; return withFinder ; }
Create and return a WithStaticFinder . Expects a static finder field on the beanType class .
65
22
141,883
RunnablePair takeAndClear ( ) { RunnablePair entries ; while ( ( entries = callbacks . get ( ) ) != END ) { if ( callbacks . compareAndSet ( entries , END ) ) { return entries ; } } return null ; }
Take and reset all callbacks in an atomic fashion .
58
11
141,884
boolean add ( Runnable runnable ) { int spins = 0 ; RunnablePair entries ; while ( ( entries = callbacks . get ( ) ) != END ) { if ( callbacks . compareAndSet ( entries , new RunnablePair ( runnable , entries ) ) ) { return true ; } if ( spins ++ > MAX_SPINS ) { Thread . yield ( ) ; spins = 0 ; } } return false ; }
Attempt to add an event listener to the list of listeners .
98
12
141,885
@ SuppressWarnings ( "unchecked" ) T result ( final Object r ) { return ( T ) ( r == NULL ? null : r ) ; }
Convert the result object to a result .
35
9
141,886
public static HTML createTransparentFlashContainer ( String ident , String movie , int width , int height , String flashVars ) { FlashObject obj = new FlashObject ( ident , movie , width , height , flashVars ) ; obj . transparent = true ; return createContainer ( obj ) ; }
Creates the HTML to display a transparent Flash movie for the browser on which we re running .
62
19
141,887
public static HTML createFlashContainer ( String ident , String movie , int width , int height , String flashVars ) { return createContainer ( new FlashObject ( ident , movie , width , height , flashVars ) ) ; }
Creates the HTML to display a Flash movie for the browser on which we re running .
48
18
141,888
public static String ensurePixels ( String value ) { int index = 0 ; for ( int nn = value . length ( ) ; index < nn ; index ++ ) { char c = value . charAt ( index ) ; if ( c < ' ' || c > ' ' ) { break ; } } return value . substring ( 0 , index ) ; }
Chops off any non - numeric suffix .
77
9
141,889
public static synchronized boolean isNativeLzoLoaded ( Configuration conf ) { if ( ! nativeLzoChecked ) { if ( GPLNativeCodeLoader . isNativeCodeLoaded ( ) ) { nativeLzoLoaded = LzoCompressor . isNativeLzoLoaded ( ) && LzoDecompressor . isNativeLzoLoaded ( ) ; if ( nativeLzoLoaded ) { LOG . info ( "Successfully loaded & initialized native-lzo library" ) ; } else { LOG . error ( "Failed to load/initialize native-lzo library" ) ; } } else { LOG . error ( "Cannot load native-lzo without native-hadoop" ) ; } nativeLzoChecked = true ; } return nativeLzoLoaded && conf . getBoolean ( "hadoop.native.lib" , true ) ; }
Check if native - lzo library is loaded & initialized .
188
12
141,890
@ RequestMapping ( path = "" , method = RequestMethod . GET ) public List < Product > getProducts ( ) { return productService . getProducts ( ) ; }
Request a page of products
36
5
141,891
@ RequestMapping ( path = "/{productId}" , method = RequestMethod . GET ) public ResponseEntity < Product > getCustomer ( @ PathVariable ( "productId" ) Long productId ) { Product product = productService . getProduct ( productId ) ; if ( product != null ) { return new ResponseEntity < Product > ( product , HttpStatus . OK ) ; } return new ResponseEntity < Product > ( HttpStatus . NOT_FOUND ) ; }
Get a specific product by id
100
6
141,892
public Number getNumber ( ) { String valstr = getText ( ) . length ( ) == 0 ? "0" : getText ( ) ; return _allowFloatingPoint ? ( Number ) ( new Double ( valstr ) ) : ( Number ) ( new Long ( valstr ) ) ; }
Get the numberic value of this box . Returns 0 if the box is empty .
63
17
141,893
public void send ( final List < MetricAggregate > aggregates ) throws IOException , HttpException { HttpClient httpClient = new HttpClient ( apiConfig ) ; // retransmit any metrics on the resend queue resendQueue . drain ( httpClient , "/Metrics/SubmitMetricsByID" ) ; // build the json objects List < JsonMetric > metrics = new ArrayList < JsonMetric > ( aggregates . size ( ) ) ; for ( MetricAggregate aggregate : aggregates ) { Integer monitorId = monitorService . getMonitorId ( aggregate . getIdentity ( ) ) ; if ( monitorId != null ) { JsonMetric . Builder builder = JsonMetric . newBuilder ( ) ; builder . monitorId ( monitorId ) ; builder . value ( Double . valueOf ( aggregate . getValue ( ) ) ) ; builder . count ( Integer . valueOf ( aggregate . getCount ( ) ) ) ; builder . occurredUtc ( new Date ( aggregate . getOccurredMillis ( ) ) ) ; builder . monitorTypeId ( Integer . valueOf ( aggregate . getIdentity ( ) . getType ( ) . getId ( ) ) ) ; builder . clientDeviceId ( monitorService . getDeviceId ( ) ) ; metrics . add ( builder . build ( ) ) ; } else { LOGGER . info ( "Unable to determine monitor id for aggregate metric {}" , aggregate ) ; } } if ( metrics . isEmpty ( ) ) { return ; } // post metrics to stackify byte [ ] jsonBytes = objectMapper . writer ( ) . writeValueAsBytes ( metrics ) ; try { httpClient . post ( "/Metrics/SubmitMetricsByID" , jsonBytes ) ; } catch ( IOException t ) { LOGGER . info ( "Queueing metrics for retransmission due to IOException" ) ; resendQueue . offer ( jsonBytes , t ) ; throw t ; } catch ( HttpException t ) { LOGGER . info ( "Queueing metrics for retransmission due to HttpException" ) ; resendQueue . offer ( jsonBytes , t ) ; throw t ; } }
Sends aggregate metrics to Stackify
463
7
141,894
public static Value < Boolean > not ( Value < Boolean > value ) { return value . map ( Functions . NOT ) ; }
Returns a value which is the logical NOT of the supplied value .
26
13
141,895
protected static boolean computeAnd ( Iterable < Value < Boolean > > values ) { for ( Value < Boolean > value : values ) { if ( ! value . get ( ) ) { return false ; } } return true ; }
my kingdom for a higher order
47
6
141,896
public static ClickHandler chain ( final ClickHandler ... handlers ) { return new ClickHandler ( ) { public void onClick ( ClickEvent event ) { for ( ClickHandler handler : handlers ) { try { handler . onClick ( event ) ; } catch ( Exception e ) { Console . log ( "Chained click handler failed" , "handler" , handler , e ) ; } } } } ; }
Creates a click handler that dispatches a single click event to a series of handlers in sequence . If any handler fails the error will be caught logged and the other handlers will still have a chance to process the event .
83
44
141,897
@ RequestMapping ( path = "" , method = RequestMethod . GET ) public Page < Customer > getCustomers ( Pageable pageable ) { return customerService . getCustomers ( pageable ) ; }
Request a page of customers
44
5
141,898
@ RequestMapping ( path = "/{customerId}" , method = RequestMethod . GET ) public ResponseEntity < Customer > getCustomer ( @ PathVariable ( "customerId" ) Long customerId , @ RequestParam ( required = true ) String name ) { Customer customer = customerService . getCustomer ( customerId ) ; if ( customer != null ) { return new ResponseEntity < Customer > ( customer , HttpStatus . OK ) ; } return new ResponseEntity < Customer > ( HttpStatus . NOT_FOUND ) ; }
Get a specific customer by id
113
6
141,899
@ RequestMapping ( path = "/{customerId}" , method = RequestMethod . DELETE ) public ResponseEntity removeCustomer ( @ PathVariable ( "customerId" ) Long customerId ) { boolean succeed = customerService . removeCustomer ( customerId ) ; if ( succeed ) { return new ResponseEntity ( HttpStatus . OK ) ; } else { return new ResponseEntity ( HttpStatus . NOT_FOUND ) ; } }
Delete customer by id
94
4