idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
17,100
public void shutdown ( ) { shuttingDown = true ; try { SocketAddress localAddress = serverSocket . getLocalAddress ( ) ; if ( localAddress instanceof InetSocketAddress ) { InetSocketAddress address = ( InetSocketAddress ) localAddress ; Socket client = new Socket ( address . getHostName ( ) , address . getPort ( ) ) ; client . setSoTimeout ( 1000 ) ; new PingAgentProtocol ( ) . connect ( client ) ; } } catch ( IOException e ) { LOGGER . log ( Level . FINE , "Failed to send Ping to wake acceptor loop" , e ) ; } try { serverSocket . close ( ) ; } catch ( IOException e ) { LOGGER . log ( Level . WARNING , "Failed to close down TCP port" , e ) ; } }
Initiates the shuts down of the listener .
17,101
@ SuppressWarnings ( { "unused" } ) private Object readResolve ( ) { if ( jdks == null ) { jdks = new ArrayList < > ( ) ; } if ( SLAVE_AGENT_PORT_ENFORCE ) { slaveAgentPort = getSlaveAgentPortInitialValue ( slaveAgentPort ) ; } if ( disabledAgentProtocols == null && _disabledAgentProtocols != null ) { disabledAgentProtocols = Arrays . asList ( _disabledAgentProtocols ) ; _disabledAgentProtocols = null ; } if ( enabledAgentProtocols == null && _enabledAgentProtocols != null ) { enabledAgentProtocols = Arrays . asList ( _enabledAgentProtocols ) ; _enabledAgentProtocols = null ; } agentProtocols = null ; return this ; }
Maintains backwards compatibility . Invoked by XStream when this object is de - serialized .
17,102
private void executeReactor ( final InitStrategy is , TaskBuilder ... builders ) throws IOException , InterruptedException , ReactorException { Reactor reactor = new Reactor ( builders ) { protected void runTask ( Task task ) throws Exception { if ( is != null && is . skipInitTask ( task ) ) return ; ACL . impersonate ( ACL . SYSTEM ) ; String taskName = InitReactorRunner . getDisplayName ( task ) ; Thread t = Thread . currentThread ( ) ; String name = t . getName ( ) ; if ( taskName != null ) t . setName ( taskName ) ; try { long start = System . currentTimeMillis ( ) ; super . runTask ( task ) ; if ( LOG_STARTUP_PERFORMANCE ) LOGGER . info ( String . format ( "Took %dms for %s by %s" , System . currentTimeMillis ( ) - start , taskName , name ) ) ; } catch ( Exception | Error x ) { if ( containsLinkageError ( x ) ) { LOGGER . log ( Level . WARNING , taskName + " failed perhaps due to plugin dependency issues" , x ) ; } else { throw x ; } } finally { t . setName ( name ) ; SecurityContextHolder . clearContext ( ) ; } } private boolean containsLinkageError ( Throwable x ) { if ( x instanceof LinkageError ) { return true ; } Throwable x2 = x . getCause ( ) ; return x2 != null && containsLinkageError ( x2 ) ; } } ; new InitReactorRunner ( ) { protected void onInitMilestoneAttained ( InitMilestone milestone ) { initLevel = milestone ; if ( milestone == PLUGINS_PREPARED ) { ExtensionList . lookup ( ExtensionFinder . class ) . getComponents ( ) ; } } } . run ( reactor ) ; }
Executes a reactor .
17,103
public Set < String > getAgentProtocols ( ) { if ( agentProtocols == null ) { Set < String > result = new TreeSet < > ( ) ; Set < String > disabled = new TreeSet < > ( ) ; for ( String p : Util . fixNull ( disabledAgentProtocols ) ) { disabled . add ( p . trim ( ) ) ; } Set < String > enabled = new TreeSet < > ( ) ; for ( String p : Util . fixNull ( enabledAgentProtocols ) ) { enabled . add ( p . trim ( ) ) ; } for ( AgentProtocol p : AgentProtocol . all ( ) ) { String name = p . getName ( ) ; if ( name != null && ( p . isRequired ( ) || ( ! disabled . contains ( name ) && ( ! p . isOptIn ( ) || enabled . contains ( name ) ) ) ) ) { result . add ( name ) ; } } agentProtocols = result ; return result ; } return agentProtocols ; }
Returns the enabled agent protocols .
17,104
public void setAgentProtocols ( Set < String > protocols ) { Set < String > disabled = new TreeSet < > ( ) ; Set < String > enabled = new TreeSet < > ( ) ; for ( AgentProtocol p : AgentProtocol . all ( ) ) { String name = p . getName ( ) ; if ( name != null && ! p . isRequired ( ) ) { if ( p . isOptIn ( ) ) { if ( protocols . contains ( name ) ) { enabled . add ( name ) ; } } else { if ( ! protocols . contains ( name ) ) { disabled . add ( name ) ; } } } } disabledAgentProtocols = disabled . isEmpty ( ) ? null : new ArrayList < > ( disabled ) ; enabledAgentProtocols = enabled . isEmpty ( ) ? null : new ArrayList < > ( enabled ) ; agentProtocols = null ; }
Sets the enabled agent protocols .
17,105
private < T extends Describable < T > > Descriptor < T > findDescriptor ( String shortClassName , Collection < ? extends Descriptor < T > > descriptors ) { String name = '.' + shortClassName ; for ( Descriptor < T > d : descriptors ) { if ( d . clazz . getName ( ) . endsWith ( name ) ) return d ; } return null ; }
Finds a descriptor that has the specified name .
17,106
@ SuppressWarnings ( "unchecked" ) public < P extends Plugin > P getPlugin ( Class < P > clazz ) { PluginWrapper p = pluginManager . getPlugin ( clazz ) ; if ( p == null ) return null ; return ( P ) p . getPlugin ( ) ; }
Gets the plugin object from its class .
17,107
public < P extends Plugin > List < P > getPlugins ( Class < P > clazz ) { List < P > result = new ArrayList < > ( ) ; for ( PluginWrapper w : pluginManager . getPlugins ( clazz ) ) { result . add ( ( P ) w . getPlugin ( ) ) ; } return Collections . unmodifiableList ( result ) ; }
Gets the plugin objects from their super - class .
17,108
public MarkupFormatter getMarkupFormatter ( ) { MarkupFormatter f = markupFormatter ; return f != null ? f : new EscapedMarkupFormatter ( ) ; }
Gets the markup formatter used in the system .
17,109
public void setViews ( Collection < View > views ) throws IOException { BulkChange bc = new BulkChange ( this ) ; try { this . views . clear ( ) ; for ( View v : views ) { addView ( v ) ; } } finally { bc . commit ( ) ; } }
offers no such operation
17,110
public boolean isUpgradedFromBefore ( VersionNumber v ) { try { return new VersionNumber ( version ) . isOlderThan ( v ) ; } catch ( IllegalArgumentException e ) { return false ; } }
Returns true if the current running Jenkins is upgraded from a version earlier than the specified version .
17,111
public Label getLabel ( String expr ) { if ( expr == null ) return null ; expr = hudson . util . QuotedStringTokenizer . unquote ( expr ) ; while ( true ) { Label l = labels . get ( expr ) ; if ( l != null ) return l ; try { labels . putIfAbsent ( expr , Label . parseExpression ( expr ) ) ; } catch ( ANTLRException e ) { return getLabelAtom ( expr ) ; } } }
Gets the label that exists on this system by the name .
17,112
public Set < Label > getLabels ( ) { Set < Label > r = new TreeSet < > ( ) ; for ( Label l : labels . values ( ) ) { if ( ! l . isEmpty ( ) ) r . add ( l ) ; } return r ; }
Gets all the active labels in the current system .
17,113
public JDK getJDK ( String name ) { if ( name == null ) { List < JDK > jdks = getJDKs ( ) ; if ( jdks . size ( ) == 1 ) return jdks . get ( 0 ) ; return null ; } for ( JDK j : getJDKs ( ) ) { if ( j . getName ( ) . equals ( name ) ) return j ; } return null ; }
Gets the JDK installation of the given name or returns null .
17,114
public List < AdministrativeMonitor > getActiveAdministrativeMonitors ( ) { return administrativeMonitors . stream ( ) . filter ( m -> m . isEnabled ( ) && m . isActivated ( ) ) . collect ( Collectors . toList ( ) ) ; }
Returns the enabled and activated administrative monitors .
17,115
private static String getXForwardedHeader ( StaplerRequest req , String header , String defaultValue ) { String value = req . getHeader ( header ) ; if ( value != null ) { int index = value . indexOf ( ',' ) ; return index == - 1 ? value . trim ( ) : value . substring ( 0 , index ) . trim ( ) ; } return defaultValue ; }
Gets the originating X - Forwarded - ... header from the request . If there are multiple headers the originating header is the first header . If the originating header contains a comma separated list the originating entry is the first one .
17,116
public SecurityMode getSecurity ( ) { SecurityRealm realm = securityRealm ; if ( realm == SecurityRealm . NO_AUTHENTICATION ) return SecurityMode . UNSECURED ; if ( realm instanceof LegacySecurityRealm ) return SecurityMode . LEGACY ; return SecurityMode . SECURED ; }
Returns the constant that captures the three basic security modes in Jenkins .
17,117
public Item getItem ( String pathName , ItemGroup context ) { if ( context == null ) context = this ; if ( pathName == null ) return null ; if ( pathName . startsWith ( "/" ) ) return getItemByFullName ( pathName ) ; Object ctx = context ; StringTokenizer tokens = new StringTokenizer ( pathName , "/" ) ; while ( tokens . hasMoreTokens ( ) ) { String s = tokens . nextToken ( ) ; if ( s . equals ( ".." ) ) { if ( ctx instanceof Item ) { ctx = ( ( Item ) ctx ) . getParent ( ) ; continue ; } ctx = null ; break ; } if ( s . equals ( "." ) ) { continue ; } if ( ctx instanceof ItemGroup ) { ItemGroup g = ( ItemGroup ) ctx ; Item i = g . getItem ( s ) ; if ( i == null || ! i . hasPermission ( Item . READ ) ) { ctx = null ; break ; } ctx = i ; } else { return null ; } } if ( ctx instanceof Item ) return ( Item ) ctx ; return getItemByFullName ( pathName ) ; }
Gets the item by its path name from the given context
17,118
public User getUser ( String name ) { return User . get ( name , User . ALLOW_USER_CREATION_VIA_URL && hasPermission ( ADMINISTER ) ) ; }
Gets the user of the given name .
17,119
public synchronized void putItem ( TopLevelItem item ) throws IOException , InterruptedException { String name = item . getName ( ) ; TopLevelItem old = items . get ( name ) ; if ( old == item ) return ; checkPermission ( Item . CREATE ) ; if ( old != null ) old . delete ( ) ; items . put ( name , item ) ; ItemListener . fireOnCreated ( item ) ; }
Overwrites the existing item by new one .
17,120
public synchronized < T extends TopLevelItem > T createProject ( Class < T > type , String name ) throws IOException { return type . cast ( createProject ( ( TopLevelItemDescriptor ) getDescriptor ( type ) , name ) ) ; }
Creates a new job .
17,121
public Object getFingerprint ( String md5sum ) throws IOException { Fingerprint r = fingerprintMap . get ( md5sum ) ; if ( r == null ) return new NoFingerprintMatch ( md5sum ) ; else return r ; }
if no finger print matches display not found page .
17,122
@ edu . umd . cs . findbugs . annotations . SuppressFBWarnings ( "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" ) public void cleanUp ( ) { if ( theInstance != this && theInstance != null ) { LOGGER . log ( Level . WARNING , "This instance is no longer the singleton, ignoring cleanUp()" ) ; return ; } synchronized ( Jenkins . class ) { if ( cleanUpStarted ) { LOGGER . log ( Level . WARNING , "Jenkins.cleanUp() already started, ignoring repeated cleanUp()" ) ; return ; } cleanUpStarted = true ; } try { LOGGER . log ( Level . INFO , "Stopping Jenkins" ) ; final List < Throwable > errors = new ArrayList < > ( ) ; fireBeforeShutdown ( errors ) ; _cleanUpRunTerminators ( errors ) ; terminating = true ; final Set < Future < ? > > pending = _cleanUpDisconnectComputers ( errors ) ; _cleanUpShutdownUDPBroadcast ( errors ) ; _cleanUpCloseDNSMulticast ( errors ) ; _cleanUpInterruptReloadThread ( errors ) ; _cleanUpShutdownTriggers ( errors ) ; _cleanUpShutdownTimer ( errors ) ; _cleanUpShutdownTcpSlaveAgent ( errors ) ; _cleanUpShutdownPluginManager ( errors ) ; _cleanUpPersistQueue ( errors ) ; _cleanUpShutdownThreadPoolForLoad ( errors ) ; _cleanUpAwaitDisconnects ( errors , pending ) ; _cleanUpPluginServletFilters ( errors ) ; _cleanUpReleaseAllLoggers ( errors ) ; LOGGER . log ( Level . INFO , "Jenkins stopped" ) ; if ( ! errors . isEmpty ( ) ) { StringBuilder message = new StringBuilder ( "Unexpected issues encountered during cleanUp: " ) ; Iterator < Throwable > iterator = errors . iterator ( ) ; message . append ( iterator . next ( ) . getMessage ( ) ) ; while ( iterator . hasNext ( ) ) { message . append ( "; " ) ; message . append ( iterator . next ( ) . getMessage ( ) ) ; } iterator = errors . iterator ( ) ; RuntimeException exception = new RuntimeException ( message . toString ( ) , iterator . next ( ) ) ; while ( iterator . hasNext ( ) ) { exception . addSuppressed ( iterator . next ( ) ) ; } throw exception ; } } finally { theInstance = null ; if ( JenkinsJVM . isJenkinsJVM ( ) ) { JenkinsJVMAccess . _setJenkinsJVM ( oldJenkinsJVM ) ; } ClassFilterImpl . unregister ( ) ; } }
Called to shut down the system .
17,123
public synchronized void doConfigExecutorsSubmit ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException , FormException { checkPermission ( ADMINISTER ) ; BulkChange bc = new BulkChange ( this ) ; try { JSONObject json = req . getSubmittedForm ( ) ; ExtensionList . lookupSingleton ( MasterBuildConfiguration . class ) . configure ( req , json ) ; getNodeProperties ( ) . rebuild ( req , json . optJSONObject ( "nodeProperties" ) , NodeProperty . all ( ) ) ; } finally { bc . commit ( ) ; } updateComputerList ( ) ; rsp . sendRedirect ( req . getContextPath ( ) + '/' + toComputer ( ) . getUrl ( ) ) ; }
Accepts submission from the node configuration page .
17,124
public synchronized HttpRedirect doCancelQuietDown ( ) { checkPermission ( ADMINISTER ) ; isQuietingDown = false ; getQueue ( ) . scheduleMaintenance ( ) ; return new HttpRedirect ( "." ) ; }
Cancel previous quiet down Jenkins - preparation for a restart
17,125
public static void checkGoodName ( String name ) throws Failure { if ( name == null || name . length ( ) == 0 ) throw new Failure ( Messages . Hudson_NoName ( ) ) ; if ( "." . equals ( name . trim ( ) ) ) throw new Failure ( Messages . Jenkins_NotAllowedName ( "." ) ) ; if ( ".." . equals ( name . trim ( ) ) ) throw new Failure ( Messages . Jenkins_NotAllowedName ( ".." ) ) ; for ( int i = 0 ; i < name . length ( ) ; i ++ ) { char ch = name . charAt ( i ) ; if ( Character . isISOControl ( ch ) ) { throw new Failure ( Messages . Hudson_ControlCodeNotAllowed ( toPrintableName ( name ) ) ) ; } if ( "?*/\\%!@#$^&|<>[]:;" . indexOf ( ch ) != - 1 ) throw new Failure ( Messages . Hudson_UnsafeChar ( ch ) ) ; } }
Check if the given name is suitable as a name for job view etc .
17,126
public void doSecured ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { if ( req . getUserPrincipal ( ) == null ) { rsp . setStatus ( HttpServletResponse . SC_UNAUTHORIZED ) ; return ; } String path = req . getContextPath ( ) + req . getOriginalRestOfPath ( ) ; String q = req . getQueryString ( ) ; if ( q != null ) path += '?' + q ; rsp . sendRedirect2 ( path ) ; }
Checks if the user was successfully authenticated .
17,127
public void doLogout ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { String user = getAuthentication ( ) . getName ( ) ; securityRealm . doLogout ( req , rsp ) ; SecurityListener . fireLoggedOut ( user ) ; }
Logs out the user .
17,128
public synchronized HttpResponse doReload ( ) throws IOException { checkPermission ( ADMINISTER ) ; LOGGER . log ( Level . WARNING , "Reloading Jenkins as requested by {0}" , getAuthentication ( ) . getName ( ) ) ; WebApp . get ( servletContext ) . setApp ( new HudsonIsLoading ( ) ) ; new Thread ( "Jenkins config reload thread" ) { public void run ( ) { try { ACL . impersonate ( ACL . SYSTEM ) ; reload ( ) ; } catch ( Exception e ) { LOGGER . log ( SEVERE , "Failed to reload Jenkins config" , e ) ; new JenkinsReloadFailed ( e ) . publish ( servletContext , root ) ; } } } . start ( ) ; return HttpResponses . redirectViaContextPath ( "/" ) ; }
Reloads the configuration .
17,129
public void doDoFingerprintCheck ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { try ( MultipartFormDataParser p = new MultipartFormDataParser ( req ) ) { if ( isUseCrumbs ( ) && ! getCrumbIssuer ( ) . validateCrumb ( req , p ) ) { rsp . sendError ( HttpServletResponse . SC_FORBIDDEN , "No crumb found" ) ; } rsp . sendRedirect2 ( req . getContextPath ( ) + "/fingerprint/" + Util . getDigestOf ( p . getFileItem ( "name" ) . getInputStream ( ) ) + '/' ) ; } }
Do a finger - print check .
17,130
@ edu . umd . cs . findbugs . annotations . SuppressFBWarnings ( "DM_GC" ) public void doGc ( StaplerResponse rsp ) throws IOException { checkPermission ( Jenkins . ADMINISTER ) ; System . gc ( ) ; rsp . setStatus ( HttpServletResponse . SC_OK ) ; rsp . setContentType ( "text/plain" ) ; rsp . getWriter ( ) . println ( "GCed" ) ; }
For debugging . Expose URL to perform GC .
17,131
public void doSimulateOutOfMemory ( ) throws IOException { checkPermission ( ADMINISTER ) ; System . out . println ( "Creating artificial OutOfMemoryError situation" ) ; List < Object > args = new ArrayList < > ( ) ; while ( true ) args . add ( new byte [ 1024 * 1024 ] ) ; }
Simulates OutOfMemoryError . Useful to make sure OutOfMemoryHeapDump setting .
17,132
@ CLIMethod ( name = "restart" ) public void doRestart ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException , RestartNotSupportedException { checkPermission ( ADMINISTER ) ; if ( req != null && req . getMethod ( ) . equals ( "GET" ) ) { req . getView ( this , "_restart.jelly" ) . forward ( req , rsp ) ; return ; } if ( req == null || req . getMethod ( ) . equals ( "POST" ) ) { restart ( ) ; } if ( rsp != null ) { rsp . sendRedirect2 ( "." ) ; } }
Perform a restart of Jenkins if we can .
17,133
@ CLIMethod ( name = "safe-restart" ) public HttpResponse doSafeRestart ( StaplerRequest req ) throws IOException , ServletException , RestartNotSupportedException { checkPermission ( ADMINISTER ) ; if ( req != null && req . getMethod ( ) . equals ( "GET" ) ) return HttpResponses . forwardToView ( this , "_safeRestart.jelly" ) ; if ( req == null || req . getMethod ( ) . equals ( "POST" ) ) { safeRestart ( ) ; } return HttpResponses . redirectToDot ( ) ; }
Queues up a restart of Jenkins for when there are no builds running if we can .
17,134
public void restart ( ) throws RestartNotSupportedException { final Lifecycle lifecycle = restartableLifecycle ( ) ; servletContext . setAttribute ( "app" , new HudsonIsRestarting ( ) ) ; new Thread ( "restart thread" ) { final String exitUser = getAuthentication ( ) . getName ( ) ; public void run ( ) { try { ACL . impersonate ( ACL . SYSTEM ) ; Thread . sleep ( TimeUnit . SECONDS . toMillis ( 5 ) ) ; LOGGER . info ( String . format ( "Restarting VM as requested by %s" , exitUser ) ) ; for ( RestartListener listener : RestartListener . all ( ) ) listener . onRestart ( ) ; lifecycle . restart ( ) ; } catch ( InterruptedException | IOException e ) { LOGGER . log ( Level . WARNING , "Failed to restart Jenkins" , e ) ; } } } . start ( ) ; }
Performs a restart .
17,135
@ CLIMethod ( name = "shutdown" ) public void doExit ( StaplerRequest req , StaplerResponse rsp ) throws IOException { checkPermission ( ADMINISTER ) ; if ( rsp != null ) { rsp . setStatus ( HttpServletResponse . SC_OK ) ; rsp . setContentType ( "text/plain" ) ; try ( PrintWriter w = rsp . getWriter ( ) ) { w . println ( "Shutting down" ) ; } } new Thread ( "exit thread" ) { public void run ( ) { try { ACL . impersonate ( ACL . SYSTEM ) ; LOGGER . info ( String . format ( "Shutting down VM as requested by %s from %s" , getAuthentication ( ) . getName ( ) , req != null ? req . getRemoteAddr ( ) : "???" ) ) ; cleanUp ( ) ; System . exit ( 0 ) ; } catch ( Exception e ) { LOGGER . log ( Level . WARNING , "Failed to shut down Jenkins" , e ) ; } } } . start ( ) ; }
Shutdown the system .
17,136
@ CLIMethod ( name = "safe-shutdown" ) public HttpResponse doSafeExit ( StaplerRequest req ) throws IOException { checkPermission ( ADMINISTER ) ; isQuietingDown = true ; final String exitUser = getAuthentication ( ) . getName ( ) ; final String exitAddr = req != null ? req . getRemoteAddr ( ) : "unknown" ; new Thread ( "safe-exit thread" ) { public void run ( ) { try { ACL . impersonate ( ACL . SYSTEM ) ; LOGGER . info ( String . format ( "Shutting down VM as requested by %s from %s" , exitUser , exitAddr ) ) ; doQuietDown ( true , 0 ) ; if ( isQuietingDown ) { cleanUp ( ) ; System . exit ( 0 ) ; } } catch ( Exception e ) { LOGGER . log ( Level . WARNING , "Failed to shut down Jenkins" , e ) ; } } } . start ( ) ; return HttpResponses . plainText ( "Shutting down as soon as all jobs are complete" ) ; }
Shutdown the system safely .
17,137
public void doEval ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { checkPermission ( RUN_SCRIPTS ) ; try { MetaClass mc = WebApp . getCurrent ( ) . getMetaClass ( getClass ( ) ) ; Script script = mc . classLoader . loadTearOff ( JellyClassLoaderTearOff . class ) . createContext ( ) . compileScript ( new InputSource ( req . getReader ( ) ) ) ; new JellyRequestDispatcher ( this , script ) . forward ( req , rsp ) ; } catch ( JellyException e ) { throw new ServletException ( e ) ; } }
Evaluates the Jelly script submitted by the client .
17,138
public void doSignup ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { if ( getSecurityRealm ( ) . allowsSignup ( ) ) { req . getView ( getSecurityRealm ( ) , "signup.jelly" ) . forward ( req , rsp ) ; return ; } req . getView ( SecurityRealm . class , "signup.jelly" ) . forward ( req , rsp ) ; }
Sign up for the user account .
17,139
public void doIconSize ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { String qs = req . getQueryString ( ) ; if ( qs == null ) throw new ServletException ( ) ; Cookie cookie = new Cookie ( "iconSize" , Functions . validateIconSize ( qs ) ) ; cookie . setMaxAge ( 9999999 ) ; rsp . addCookie ( cookie ) ; String ref = req . getHeader ( "Referer" ) ; if ( ref == null ) ref = "." ; rsp . sendRedirect2 ( ref ) ; }
Changes the icon size by changing the cookie
17,140
public void rebuildDependencyGraph ( ) { DependencyGraph graph = new DependencyGraph ( ) ; graph . build ( ) ; dependencyGraph = graph ; dependencyGraphDirty . set ( false ) ; }
Rebuilds the dependency map .
17,141
public Future < DependencyGraph > rebuildDependencyGraphAsync ( ) { dependencyGraphDirty . set ( true ) ; return Timer . get ( ) . schedule ( new java . util . concurrent . Callable < DependencyGraph > ( ) { public DependencyGraph call ( ) throws Exception { if ( dependencyGraphDirty . get ( ) ) { rebuildDependencyGraph ( ) ; } return dependencyGraph ; } } , 500 , TimeUnit . MILLISECONDS ) ; }
Rebuilds the dependency map asynchronously .
17,142
public boolean isSubjectToMandatoryReadPermissionCheck ( String restOfPath ) { for ( String name : ALWAYS_READABLE_PATHS ) { if ( restOfPath . startsWith ( name ) ) { return false ; } } for ( String name : getUnprotectedRootActions ( ) ) { if ( restOfPath . startsWith ( "/" + name + "/" ) || restOfPath . equals ( "/" + name ) ) { return false ; } } if ( restOfPath . matches ( "/computer/[^/]+/slave-agent[.]jnlp" ) && "true" . equals ( Stapler . getCurrentRequest ( ) . getParameter ( "encrypt" ) ) ) { return false ; } return true ; }
Test a path to see if it is subject to mandatory read permission checks by container - managed security
17,143
boolean isDisplayNameUnique ( String displayName , String currentJobName ) { Collection < TopLevelItem > itemCollection = items . values ( ) ; for ( TopLevelItem item : itemCollection ) { if ( item . getName ( ) . equals ( currentJobName ) ) { continue ; } else if ( displayName . equals ( item . getDisplayName ( ) ) ) { return false ; } } return true ; }
This method checks all existing jobs to see if displayName is unique . It does not check the displayName against the displayName of the job that the user is configuring though to prevent a validation warning if the user sets the displayName to what it currently is .
17,144
boolean isNameUnique ( String name , String currentJobName ) { Item item = getItem ( name ) ; if ( null == item ) { return true ; } else if ( item . getName ( ) . equals ( currentJobName ) ) { return true ; } else { return false ; } }
True if there is no item in Jenkins that has this name
17,145
public static DescriptorExtensionList < BuildWrapper , Descriptor < BuildWrapper > > all ( ) { return Jenkins . getInstance ( ) . < BuildWrapper , Descriptor < BuildWrapper > > getDescriptorList ( BuildWrapper . class ) ; }
for compatibility we can t use BuildWrapperDescriptor
17,146
public void update ( float f ) { counter = ( counter + 1 ) % 360 ; sec10 . update ( f ) ; if ( counter % 6 == 0 ) min . update ( f ) ; if ( counter == 0 ) hour . update ( f ) ; }
Call this method every 10 sec and supply a new data point .
17,147
protected List < Date > loadAttempts ( File home ) { List < Date > dates = new ArrayList < > ( ) ; if ( home != null ) { File f = getBootFailureFile ( home ) ; try { if ( f . exists ( ) ) { try ( BufferedReader failureFileReader = new BufferedReader ( new FileReader ( f ) ) ) { String line ; while ( ( line = failureFileReader . readLine ( ) ) != null ) { try { dates . add ( new Date ( line ) ) ; } catch ( Exception e ) { } } } } } catch ( IOException e ) { LOGGER . log ( Level . WARNING , "Failed to parse " + f , e ) ; } } return dates ; }
Parses the boot attempt file carefully so as not to cause the entire hook script to fail to execute .
17,148
public void toXMLUTF8 ( Object obj , OutputStream out ) throws IOException { Writer w = new OutputStreamWriter ( out , Charset . forName ( "UTF-8" ) ) ; w . write ( "<?xml version=\"1.1\" encoding=\"UTF-8\"?>\n" ) ; toXML ( obj , w ) ; }
Serializes to a byte stream . Uses UTF - 8 encoding and specifies that in the XML encoding declaration .
17,149
public boolean canAccept ( WorkChunk c ) { if ( this . size ( ) < c . size ( ) ) return false ; if ( c . assignedLabel != null && ! c . assignedLabel . contains ( node ) ) return false ; if ( ! ( Node . SKIP_BUILD_CHECK_ON_FLYWEIGHTS && item . task instanceof Queue . FlyweightTask ) && ! nodeAcl . hasPermission ( item . authenticate ( ) , Computer . BUILD ) ) return false ; return true ; }
Is this executor chunk and the given work chunk compatible? Can the latter be run on the former?
17,150
public BeanConfiguration addAbstractBean ( String name ) { BeanConfiguration bc = new DefaultBeanConfiguration ( name ) ; bc . setAbstract ( true ) ; registerBeanConfiguration ( name , bc ) ; return bc ; }
Adds an abstract bean and returns the BeanConfiguration instance
17,151
private static String addLineFeedForNonASCII ( String s ) { if ( ! s . startsWith ( "#!" ) ) { if ( s . indexOf ( '\n' ) != 0 ) { return "\n" + s ; } } return s ; }
Older versions of bash have a bug where non - ASCII on the first line makes the shell think the file is a binary file and not a script . Adding a leading line feed works around this problem .
17,152
public synchronized LottieTask < T > addListener ( LottieListener < T > listener ) { if ( result != null && result . getValue ( ) != null ) { listener . onResult ( result . getValue ( ) ) ; } successListeners . add ( listener ) ; return this ; }
Add a task listener . If the task has completed the listener will be called synchronously .
17,153
public synchronized LottieTask < T > addFailureListener ( LottieListener < Throwable > listener ) { if ( result != null && result . getException ( ) != null ) { listener . onResult ( result . getException ( ) ) ; } failureListeners . add ( listener ) ; return this ; }
Add a task failure listener . This will only be called in the even that an exception occurs . If an exception has already occurred the listener will be called immediately .
17,154
public static Bitmap renderPath ( Path path ) { RectF bounds = new RectF ( ) ; path . computeBounds ( bounds , false ) ; Bitmap bitmap = Bitmap . createBitmap ( ( int ) bounds . right , ( int ) bounds . bottom , Bitmap . Config . ARGB_8888 ) ; Canvas canvas = new Canvas ( bitmap ) ; Paint paint = new LPaint ( ) ; paint . setAntiAlias ( true ) ; paint . setColor ( Color . BLUE ) ; canvas . drawPath ( path , paint ) ; return bitmap ; }
For testing purposes only . DO NOT USE IN PRODUCTION .
17,155
public void playAnimation ( ) { if ( compositionLayer == null ) { lazyCompositionTasks . add ( new LazyCompositionTask ( ) { public void run ( LottieComposition composition ) { playAnimation ( ) ; } } ) ; return ; } if ( systemAnimationsEnabled || getRepeatCount ( ) == 0 ) { animator . playAnimation ( ) ; } if ( ! systemAnimationsEnabled ) { setFrame ( ( int ) ( getSpeed ( ) < 0 ? getMinFrame ( ) : getMaxFrame ( ) ) ) ; } }
Plays the animation from the beginning . If speed is < 0 it will start at the end and play towards the beginning
17,156
public void resumeAnimation ( ) { if ( compositionLayer == null ) { lazyCompositionTasks . add ( new LazyCompositionTask ( ) { public void run ( LottieComposition composition ) { resumeAnimation ( ) ; } } ) ; return ; } animator . resumeAnimation ( ) ; }
Continues playing the animation from its current position . If speed < 0 it will play backwards from the current position .
17,157
public void setMinFrame ( final int minFrame ) { if ( composition == null ) { lazyCompositionTasks . add ( new LazyCompositionTask ( ) { public void run ( LottieComposition composition ) { setMinFrame ( minFrame ) ; } } ) ; return ; } animator . setMinFrame ( minFrame ) ; }
Sets the minimum frame that the animation will start from when playing or looping .
17,158
public void setMinProgress ( final float minProgress ) { if ( composition == null ) { lazyCompositionTasks . add ( new LazyCompositionTask ( ) { public void run ( LottieComposition composition ) { setMinProgress ( minProgress ) ; } } ) ; return ; } setMinFrame ( ( int ) MiscUtils . lerp ( composition . getStartFrame ( ) , composition . getEndFrame ( ) , minProgress ) ) ; }
Sets the minimum progress that the animation will start from when playing or looping .
17,159
public void setMaxFrame ( final int maxFrame ) { if ( composition == null ) { lazyCompositionTasks . add ( new LazyCompositionTask ( ) { public void run ( LottieComposition composition ) { setMaxFrame ( maxFrame ) ; } } ) ; return ; } animator . setMaxFrame ( maxFrame + 0.99f ) ; }
Sets the maximum frame that the animation will end at when playing or looping .
17,160
public void setMaxProgress ( @ FloatRange ( from = 0f , to = 1f ) final float maxProgress ) { if ( composition == null ) { lazyCompositionTasks . add ( new LazyCompositionTask ( ) { public void run ( LottieComposition composition ) { setMaxProgress ( maxProgress ) ; } } ) ; return ; } setMaxFrame ( ( int ) MiscUtils . lerp ( composition . getStartFrame ( ) , composition . getEndFrame ( ) , maxProgress ) ) ; }
Sets the maximum progress that the animation will end at when playing or looping .
17,161
public void setMinFrame ( final String markerName ) { if ( composition == null ) { lazyCompositionTasks . add ( new LazyCompositionTask ( ) { public void run ( LottieComposition composition ) { setMinFrame ( markerName ) ; } } ) ; return ; } Marker marker = composition . getMarker ( markerName ) ; if ( marker == null ) { throw new IllegalArgumentException ( "Cannot find marker with name " + markerName + "." ) ; } setMinFrame ( ( int ) marker . startFrame ) ; }
Sets the minimum frame to the start time of the specified marker .
17,162
public void setFrame ( final int frame ) { if ( composition == null ) { lazyCompositionTasks . add ( new LazyCompositionTask ( ) { public void run ( LottieComposition composition ) { setFrame ( frame ) ; } } ) ; return ; } animator . setFrame ( frame ) ; }
Sets the progress to the specified frame . If the composition isn t set yet the progress will be set to the frame when it is .
17,163
public void setFontAssetDelegate ( @ SuppressWarnings ( "NullableProblems" ) FontAssetDelegate assetDelegate ) { this . fontAssetDelegate = assetDelegate ; if ( fontAssetManager != null ) { fontAssetManager . setDelegate ( assetDelegate ) ; } }
Use this to manually set fonts .
17,164
float getLinearCurrentKeyframeProgress ( ) { if ( isDiscrete ) { return 0f ; } Keyframe < K > keyframe = getCurrentKeyframe ( ) ; if ( keyframe . isStatic ( ) ) { return 0f ; } float progressIntoFrame = progress - keyframe . getStartProgress ( ) ; float keyframeProgress = keyframe . getEndProgress ( ) - keyframe . getStartProgress ( ) ; return progressIntoFrame / keyframeProgress ; }
Returns the progress into the current keyframe between 0 and 1 . This does not take into account any interpolation that the keyframe may have .
17,165
public void setAnimation ( final int rawRes ) { this . animationResId = rawRes ; animationName = null ; setCompositionTask ( LottieCompositionFactory . fromRawRes ( getContext ( ) , rawRes ) ) ; }
Sets the animation from a file in the raw directory . This will load and deserialize the file asynchronously .
17,166
public void setScale ( float scale ) { lottieDrawable . setScale ( scale ) ; if ( getDrawable ( ) == lottieDrawable ) { setImageDrawable ( null ) ; setImageDrawable ( lottieDrawable ) ; } }
Set the scale on the current composition . The only cost of this function is re - rendering the current frame so you may call it frequent to scale something up or down .
17,167
public void buildDrawingCache ( boolean autoScale ) { super . buildDrawingCache ( autoScale ) ; if ( getLayerType ( ) == LAYER_TYPE_SOFTWARE && getDrawingCache ( autoScale ) == null ) { setRenderMode ( HARDWARE ) ; } }
If rendering via software Android will fail to generate a bitmap if the view is too large . Rather than displaying nothing fallback on hardware acceleration which may incur a performance hit .
17,168
private static < T > List < Keyframe < T > > parse ( JsonReader reader , LottieComposition composition , ValueParser < T > valueParser ) throws IOException { return KeyframesParser . parse ( reader , composition , 1 , valueParser ) ; }
Will return null if the animation can t be played such as if it has expressions .
17,169
private File getCachedFile ( String url ) throws FileNotFoundException { File jsonFile = new File ( appContext . getCacheDir ( ) , filenameForUrl ( url , FileExtension . JSON , false ) ) ; if ( jsonFile . exists ( ) ) { return jsonFile ; } File zipFile = new File ( appContext . getCacheDir ( ) , filenameForUrl ( url , FileExtension . ZIP , false ) ) ; if ( zipFile . exists ( ) ) { return zipFile ; } return null ; }
Returns the cache file for the given url if it exists . Checks for both json and zip . Returns null if neither exist .
17,170
public void setText ( String input , String output ) { stringMap . put ( input , output ) ; invalidate ( ) ; }
Update the text that will be rendered for the given input text .
17,171
public static < T > void setEndFrames ( List < ? extends Keyframe < T > > keyframes ) { int size = keyframes . size ( ) ; for ( int i = 0 ; i < size - 1 ; i ++ ) { Keyframe < T > keyframe = keyframes . get ( i ) ; Keyframe < T > nextKeyframe = keyframes . get ( i + 1 ) ; keyframe . endFrame = nextKeyframe . startFrame ; if ( keyframe . endValue == null && nextKeyframe . startValue != null ) { keyframe . endValue = nextKeyframe . startValue ; if ( keyframe instanceof PathKeyframe ) { ( ( PathKeyframe ) keyframe ) . createPath ( ) ; } } } Keyframe < ? > lastKeyframe = keyframes . get ( size - 1 ) ; if ( ( lastKeyframe . startValue == null || lastKeyframe . endValue == null ) && keyframes . size ( ) > 1 ) { keyframes . remove ( lastKeyframe ) ; } }
The json doesn t include end frames . The data can be taken from the start frame of the next keyframe though .
17,172
@ FloatRange ( from = 0f , to = 1f ) public float getAnimatedValueAbsolute ( ) { if ( composition == null ) { return 0 ; } return ( frame - composition . getStartFrame ( ) ) / ( composition . getEndFrame ( ) - composition . getStartFrame ( ) ) ; }
Returns the current value of the animation from 0 to 1 regardless of the animation speed direction or min and max frames .
17,173
@ FloatRange ( from = 0f , to = 1f ) public float getAnimatedFraction ( ) { if ( composition == null ) { return 0 ; } if ( isReversed ( ) ) { return ( getMaxFrame ( ) - frame ) / ( getMaxFrame ( ) - getMinFrame ( ) ) ; } else { return ( frame - getMinFrame ( ) ) / ( getMaxFrame ( ) - getMinFrame ( ) ) ; } }
Returns the current value of the currently playing animation taking into account direction min and max frames .
17,174
private static < T > Keyframe < T > parseKeyframe ( LottieComposition composition , JsonReader reader , float scale , ValueParser < T > valueParser ) throws IOException { PointF cp1 = null ; PointF cp2 = null ; float startFrame = 0 ; T startValue = null ; T endValue = null ; boolean hold = false ; Interpolator interpolator = null ; PointF pathCp1 = null ; PointF pathCp2 = null ; reader . beginObject ( ) ; while ( reader . hasNext ( ) ) { switch ( reader . nextName ( ) ) { case "t" : startFrame = ( float ) reader . nextDouble ( ) ; break ; case "s" : startValue = valueParser . parse ( reader , scale ) ; break ; case "e" : endValue = valueParser . parse ( reader , scale ) ; break ; case "o" : cp1 = JsonUtils . jsonToPoint ( reader , scale ) ; break ; case "i" : cp2 = JsonUtils . jsonToPoint ( reader , scale ) ; break ; case "h" : hold = reader . nextInt ( ) == 1 ; break ; case "to" : pathCp1 = JsonUtils . jsonToPoint ( reader , scale ) ; break ; case "ti" : pathCp2 = JsonUtils . jsonToPoint ( reader , scale ) ; break ; default : reader . skipValue ( ) ; } } reader . endObject ( ) ; if ( hold ) { endValue = startValue ; interpolator = LINEAR_INTERPOLATOR ; } else if ( cp1 != null && cp2 != null ) { cp1 . x = MiscUtils . clamp ( cp1 . x , - scale , scale ) ; cp1 . y = MiscUtils . clamp ( cp1 . y , - MAX_CP_VALUE , MAX_CP_VALUE ) ; cp2 . x = MiscUtils . clamp ( cp2 . x , - scale , scale ) ; cp2 . y = MiscUtils . clamp ( cp2 . y , - MAX_CP_VALUE , MAX_CP_VALUE ) ; int hash = Utils . hashFor ( cp1 . x , cp1 . y , cp2 . x , cp2 . y ) ; WeakReference < Interpolator > interpolatorRef = getInterpolator ( hash ) ; if ( interpolatorRef != null ) { interpolator = interpolatorRef . get ( ) ; } if ( interpolatorRef == null || interpolator == null ) { interpolator = PathInterpolatorCompat . create ( cp1 . x / scale , cp1 . y / scale , cp2 . x / scale , cp2 . y / scale ) ; try { putInterpolator ( hash , new WeakReference < > ( interpolator ) ) ; } catch ( ArrayIndexOutOfBoundsException e ) { } } } else { interpolator = LINEAR_INTERPOLATOR ; } Keyframe < T > keyframe = new Keyframe < > ( composition , startValue , endValue , interpolator , startFrame , null ) ; keyframe . pathCp1 = pathCp1 ; keyframe . pathCp2 = pathCp2 ; return keyframe ; }
beginObject will already be called on the keyframe so it can be differentiated with a non animated value .
17,175
private void addOpacityStopsToGradientIfNeeded ( GradientColor gradientColor , List < Float > array ) { int startIndex = colorPoints * 4 ; if ( array . size ( ) <= startIndex ) { return ; } int opacityStops = ( array . size ( ) - startIndex ) / 2 ; double [ ] positions = new double [ opacityStops ] ; double [ ] opacities = new double [ opacityStops ] ; for ( int i = startIndex , j = 0 ; i < array . size ( ) ; i ++ ) { if ( i % 2 == 0 ) { positions [ j ] = array . get ( i ) ; } else { opacities [ j ] = array . get ( i ) ; j ++ ; } } for ( int i = 0 ; i < gradientColor . getSize ( ) ; i ++ ) { int color = gradientColor . getColors ( ) [ i ] ; color = Color . argb ( getOpacityAtPosition ( gradientColor . getPositions ( ) [ i ] , positions , opacities ) , Color . red ( color ) , Color . green ( color ) , Color . blue ( color ) ) ; gradientColor . getColors ( ) [ i ] = color ; } }
This cheats a little bit . Opacity stops can be at arbitrary intervals independent of color stops . This uses the existing color stops and modifies the opacity at each existing color stop based on what the opacity would be .
17,176
public static LottieTask < LottieComposition > fromJsonInputStream ( final InputStream stream , final String cacheKey ) { return cache ( cacheKey , new Callable < LottieResult < LottieComposition > > ( ) { public LottieResult < LottieComposition > call ( ) { return fromJsonInputStreamSync ( stream , cacheKey ) ; } } ) ; }
Auto - closes the stream .
17,177
private static LottieTask < LottieComposition > cache ( final String cacheKey , Callable < LottieResult < LottieComposition > > callable ) { final LottieComposition cachedComposition = cacheKey == null ? null : LottieCompositionCache . getInstance ( ) . get ( cacheKey ) ; if ( cachedComposition != null ) { return new LottieTask < > ( new Callable < LottieResult < LottieComposition > > ( ) { public LottieResult < LottieComposition > call ( ) { return new LottieResult < > ( cachedComposition ) ; } } ) ; } if ( cacheKey != null && taskCache . containsKey ( cacheKey ) ) { return taskCache . get ( cacheKey ) ; } LottieTask < LottieComposition > task = new LottieTask < > ( callable ) ; task . addListener ( new LottieListener < LottieComposition > ( ) { public void onResult ( LottieComposition result ) { if ( cacheKey != null ) { LottieCompositionCache . getInstance ( ) . put ( cacheKey , result ) ; } taskCache . remove ( cacheKey ) ; } } ) ; task . addFailureListener ( new LottieListener < Throwable > ( ) { public void onResult ( Throwable result ) { taskCache . remove ( cacheKey ) ; } } ) ; taskCache . put ( cacheKey , task ) ; return task ; }
First check to see if there are any in - progress tasks associated with the cache key and return it if there is . If not create a new task for the callable . Then add the new task to the task cache and set up listeners so it gets cleared when done .
17,178
@ RestrictTo ( RestrictTo . Scope . LIBRARY ) public KeyPath addKey ( String key ) { KeyPath newKeyPath = new KeyPath ( this ) ; newKeyPath . keys . add ( key ) ; return newKeyPath ; }
Returns a new KeyPath with the key added . This is used during keypath resolution . Children normally don t know about all of their parent elements so this is used to keep track of the fully qualified keypath . This returns a key keypath because during resolution the full keypath element tree is walked and if this modified the original copy it would remain after popping back up the element tree .
17,179
@ SuppressWarnings ( "RedundantIfStatement" ) @ RestrictTo ( RestrictTo . Scope . LIBRARY ) public boolean matches ( String key , int depth ) { if ( isContainer ( key ) ) { return true ; } if ( depth >= keys . size ( ) ) { return false ; } if ( keys . get ( depth ) . equals ( key ) || keys . get ( depth ) . equals ( "**" ) || keys . get ( depth ) . equals ( "*" ) ) { return true ; } return false ; }
Returns whether they key matches at the specified depth .
17,180
@ RestrictTo ( RestrictTo . Scope . LIBRARY ) public int incrementDepthBy ( String key , int depth ) { if ( isContainer ( key ) ) { return 0 ; } if ( ! keys . get ( depth ) . equals ( "**" ) ) { return 1 ; } if ( depth == keys . size ( ) - 1 ) { return 0 ; } if ( keys . get ( depth + 1 ) . equals ( key ) ) { return 2 ; } return 0 ; }
For a given key and depth returns how much the depth should be incremented by when resolving a keypath to children .
17,181
@ RestrictTo ( RestrictTo . Scope . LIBRARY ) public boolean fullyResolvesTo ( String key , int depth ) { if ( depth >= keys . size ( ) ) { return false ; } boolean isLastDepth = depth == keys . size ( ) - 1 ; String keyAtDepth = keys . get ( depth ) ; boolean isGlobstar = keyAtDepth . equals ( "**" ) ; if ( ! isGlobstar ) { boolean matches = keyAtDepth . equals ( key ) || keyAtDepth . equals ( "*" ) ; return ( isLastDepth || ( depth == keys . size ( ) - 2 && endsWithGlobstar ( ) ) ) && matches ; } boolean isGlobstarButNextKeyMatches = ! isLastDepth && keys . get ( depth + 1 ) . equals ( key ) ; if ( isGlobstarButNextKeyMatches ) { return depth == keys . size ( ) - 2 || ( depth == keys . size ( ) - 3 && endsWithGlobstar ( ) ) ; } if ( isLastDepth ) { return true ; } if ( depth + 1 < keys . size ( ) - 1 ) { return false ; } return keys . get ( depth + 1 ) . equals ( key ) ; }
Returns whether the key at specified depth is fully specific enough to match the full set of keys in this keypath .
17,182
public static void warn ( String msg ) { if ( loggedMessages . contains ( msg ) ) { return ; } Log . w ( TAG , msg ) ; loggedMessages . add ( msg ) ; }
Warn to logcat . Keeps track of messages so they are only logged once ever .
17,183
private LottieComposition fetchFromCache ( ) { Pair < FileExtension , InputStream > cacheResult = networkCache . fetch ( ) ; if ( cacheResult == null ) { return null ; } FileExtension extension = cacheResult . first ; InputStream inputStream = cacheResult . second ; LottieResult < LottieComposition > result ; if ( extension == FileExtension . ZIP ) { result = LottieCompositionFactory . fromZipStreamSync ( new ZipInputStream ( inputStream ) , url ) ; } else { result = LottieCompositionFactory . fromJsonInputStreamSync ( inputStream , url ) ; } if ( result . getValue ( ) != null ) { return result . getValue ( ) ; } return null ; }
Returns null if the animation doesn t exist in the cache .
17,184
private boolean checkUrl ( String url ) { try { URI uri = new URI ( url ) ; return uri . isAbsolute ( ) ; } catch ( URISyntaxException e ) { return false ; } }
Checks the syntax of the given URL .
17,185
public Mono < InstanceId > register ( Registration registration ) { Assert . notNull ( registration , "'registration' must not be null" ) ; InstanceId id = generator . generateId ( registration ) ; Assert . notNull ( id , "'id' must not be null" ) ; return repository . compute ( id , ( key , instance ) -> { if ( instance == null ) { instance = Instance . create ( key ) ; } return Mono . just ( instance . register ( registration ) ) ; } ) . map ( Instance :: getId ) ; }
Register instance .
17,186
public Mono < InstanceId > deregister ( InstanceId id ) { return repository . computeIfPresent ( id , ( key , instance ) -> Mono . just ( instance . deregister ( ) ) ) . map ( Instance :: getId ) ; }
Remove a specific instance from services
17,187
public boolean register ( ) { Application application = this . applicationFactory . createApplication ( ) ; boolean isRegistrationSuccessful = false ; for ( String adminUrl : this . adminUrls ) { LongAdder attempt = this . attempts . computeIfAbsent ( adminUrl , k -> new LongAdder ( ) ) ; boolean successful = register ( application , adminUrl , attempt . intValue ( ) == 0 ) ; if ( ! successful ) { attempt . increment ( ) ; } else { attempt . reset ( ) ; isRegistrationSuccessful = true ; if ( this . registerOnce ) { break ; } } } return isRegistrationSuccessful ; }
Registers the client application at spring - boot - admin - server .
17,188
public JsonReader newJsonReader ( Reader reader ) { JsonReader jsonReader = new JsonReader ( reader ) ; jsonReader . setLenient ( lenient ) ; return jsonReader ; }
Returns a new JSON reader configured for the settings on this Gson instance .
17,189
private void rebalance ( Node < K , V > unbalanced , boolean insert ) { for ( Node < K , V > node = unbalanced ; node != null ; node = node . parent ) { Node < K , V > left = node . left ; Node < K , V > right = node . right ; int leftHeight = left != null ? left . height : 0 ; int rightHeight = right != null ? right . height : 0 ; int delta = leftHeight - rightHeight ; if ( delta == - 2 ) { Node < K , V > rightLeft = right . left ; Node < K , V > rightRight = right . right ; int rightRightHeight = rightRight != null ? rightRight . height : 0 ; int rightLeftHeight = rightLeft != null ? rightLeft . height : 0 ; int rightDelta = rightLeftHeight - rightRightHeight ; if ( rightDelta == - 1 || ( rightDelta == 0 && ! insert ) ) { rotateLeft ( node ) ; } else { assert ( rightDelta == 1 ) ; rotateRight ( right ) ; rotateLeft ( node ) ; } if ( insert ) { break ; } } else if ( delta == 2 ) { Node < K , V > leftLeft = left . left ; Node < K , V > leftRight = left . right ; int leftRightHeight = leftRight != null ? leftRight . height : 0 ; int leftLeftHeight = leftLeft != null ? leftLeft . height : 0 ; int leftDelta = leftLeftHeight - leftRightHeight ; if ( leftDelta == 1 || ( leftDelta == 0 && ! insert ) ) { rotateRight ( node ) ; } else { assert ( leftDelta == - 1 ) ; rotateLeft ( left ) ; rotateRight ( node ) ; } if ( insert ) { break ; } } else if ( delta == 0 ) { node . height = leftHeight + 1 ; if ( insert ) { break ; } } else { assert ( delta == - 1 || delta == 1 ) ; node . height = Math . max ( leftHeight , rightHeight ) + 1 ; if ( ! insert ) { break ; } } } }
Rebalances the tree by making any AVL rotations necessary between the newly - unbalanced node and the tree s root .
17,190
private void rotateLeft ( Node < K , V > root ) { Node < K , V > left = root . left ; Node < K , V > pivot = root . right ; Node < K , V > pivotLeft = pivot . left ; Node < K , V > pivotRight = pivot . right ; root . right = pivotLeft ; if ( pivotLeft != null ) { pivotLeft . parent = root ; } replaceInParent ( root , pivot ) ; pivot . left = root ; root . parent = pivot ; root . height = Math . max ( left != null ? left . height : 0 , pivotLeft != null ? pivotLeft . height : 0 ) + 1 ; pivot . height = Math . max ( root . height , pivotRight != null ? pivotRight . height : 0 ) + 1 ; }
Rotates the subtree so that its root s right child is the new root .
17,191
public void add ( String property , JsonElement value ) { members . put ( property , value == null ? JsonNull . INSTANCE : value ) ; }
Adds a member which is a name - value pair to self . The name must be a String but the value can be an arbitrary JsonElement thereby allowing you to build a full tree of JsonElements rooted at this node .
17,192
public void addProperty ( String property , Character value ) { add ( property , value == null ? JsonNull . INSTANCE : new JsonPrimitive ( value ) ) ; }
Convenience method to add a char member . The specified value is converted to a JsonPrimitive of Character .
17,193
private static boolean checkOffset ( String value , int offset , char expected ) { return ( offset < value . length ( ) ) && ( value . charAt ( offset ) == expected ) ; }
Check if the expected character exist at the given offset in the value .
17,194
private static int parseInt ( String value , int beginIndex , int endIndex ) throws NumberFormatException { if ( beginIndex < 0 || endIndex > value . length ( ) || beginIndex > endIndex ) { throw new NumberFormatException ( value ) ; } int i = beginIndex ; int result = 0 ; int digit ; if ( i < endIndex ) { digit = Character . digit ( value . charAt ( i ++ ) , 10 ) ; if ( digit < 0 ) { throw new NumberFormatException ( "Invalid number: " + value . substring ( beginIndex , endIndex ) ) ; } result = - digit ; } while ( i < endIndex ) { digit = Character . digit ( value . charAt ( i ++ ) , 10 ) ; if ( digit < 0 ) { throw new NumberFormatException ( "Invalid number: " + value . substring ( beginIndex , endIndex ) ) ; } result *= 10 ; result -= digit ; } return - result ; }
Parse an integer located between 2 given offsets in a string
17,195
private static void padInt ( StringBuilder buffer , int value , int length ) { String strValue = Integer . toString ( value ) ; for ( int i = length - strValue . length ( ) ; i > 0 ; i -- ) { buffer . append ( '0' ) ; } buffer . append ( strValue ) ; }
Zero pad a number to a specified length
17,196
private static int indexOfNonDigit ( String string , int offset ) { for ( int i = offset ; i < string . length ( ) ; i ++ ) { char c = string . charAt ( i ) ; if ( c < '0' || c > '9' ) return i ; } return string . length ( ) ; }
Returns the index of the first character in the string that is not a digit starting at offset .
17,197
public static JsonElement parseReader ( Reader reader ) throws JsonIOException , JsonSyntaxException { try { JsonReader jsonReader = new JsonReader ( reader ) ; JsonElement element = parseReader ( jsonReader ) ; if ( ! element . isJsonNull ( ) && jsonReader . peek ( ) != JsonToken . END_DOCUMENT ) { throw new JsonSyntaxException ( "Did not consume the entire document." ) ; } return element ; } catch ( MalformedJsonException e ) { throw new JsonSyntaxException ( e ) ; } catch ( IOException e ) { throw new JsonIOException ( e ) ; } catch ( NumberFormatException e ) { throw new JsonSyntaxException ( e ) ; } }
Parses the specified JSON string into a parse tree
17,198
public static JsonElement parseReader ( JsonReader reader ) throws JsonIOException , JsonSyntaxException { boolean lenient = reader . isLenient ( ) ; reader . setLenient ( true ) ; try { return Streams . parse ( reader ) ; } catch ( StackOverflowError e ) { throw new JsonParseException ( "Failed parsing JSON source: " + reader + " to Json" , e ) ; } catch ( OutOfMemoryError e ) { throw new JsonParseException ( "Failed parsing JSON source: " + reader + " to Json" , e ) ; } finally { reader . setLenient ( lenient ) ; } }
Returns the next value from the JSON stream as a parse tree .
17,199
public void beginObject ( ) throws IOException { int p = peeked ; if ( p == PEEKED_NONE ) { p = doPeek ( ) ; } if ( p == PEEKED_BEGIN_OBJECT ) { push ( JsonScope . EMPTY_OBJECT ) ; peeked = PEEKED_NONE ; } else { throw new IllegalStateException ( "Expected BEGIN_OBJECT but was " + peek ( ) + locationString ( ) ) ; } }
Consumes the next token from the JSON stream and asserts that it is the beginning of a new object .