idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
13,600
public void stop ( ) throws IOException { synchronized ( this . monitor ) { if ( this . listenThread != null ) { closeAllConnections ( ) ; try { this . executor . shutdown ( ) ; this . executor . awaitTermination ( 1 , TimeUnit . MINUTES ) ; } catch ( InterruptedException ex ) { Thread . currentThread ( ) . interrupt ( ) ; } this . serverSocket . close ( ) ; try { this . listenThread . join ( ) ; } catch ( InterruptedException ex ) { Thread . currentThread ( ) . interrupt ( ) ; } this . listenThread = null ; this . serverSocket = null ; } } }
Gracefully stop the livereload server .
13,601
public void triggerReload ( ) { synchronized ( this . monitor ) { synchronized ( this . connections ) { for ( Connection connection : this . connections ) { try { connection . triggerReload ( ) ; } catch ( Exception ex ) { logger . debug ( "Unable to send reload message" , ex ) ; } } } } }
Trigger livereload of all connected clients .
13,602
public SpringApplicationBuilder child ( Class < ? > ... sources ) { SpringApplicationBuilder child = new SpringApplicationBuilder ( ) ; child . sources ( sources ) ; child . properties ( this . defaultProperties ) . environment ( this . environment ) . additionalProfiles ( this . additionalProfiles ) ; child . parent = this ; web ( WebApplicationType . NONE ) ; bannerMode ( Banner . Mode . OFF ) ; this . application . addPrimarySources ( this . sources ) ; return child ; }
Create a child application with the provided sources . Default args and environment are copied down into the child but everything else is a clean sheet .
13,603
public SpringApplicationBuilder parent ( Class < ? > ... sources ) { if ( this . parent == null ) { this . parent = new SpringApplicationBuilder ( sources ) . web ( WebApplicationType . NONE ) . properties ( this . defaultProperties ) . environment ( this . environment ) ; } else { this . parent . sources ( sources ) ; } return this . parent ; }
Add a parent application with the provided sources . Default args and environment are copied up into the parent but everything else is a clean sheet .
13,604
public SpringApplicationBuilder parent ( ConfigurableApplicationContext parent ) { this . parent = new SpringApplicationBuilder ( ) ; this . parent . context = parent ; this . parent . running . set ( true ) ; return this ; }
Add an already running parent context to an existing application .
13,605
public SpringApplicationBuilder properties ( Map < String , Object > defaults ) { this . defaultProperties . putAll ( defaults ) ; this . application . setDefaultProperties ( this . defaultProperties ) ; if ( this . parent != null ) { this . parent . properties ( this . defaultProperties ) ; this . parent . environment ( this . environment ) ; } return this ; }
Default properties for the environment . Multiple calls to this method are cumulative .
13,606
public static void addApplicationConverters ( ConverterRegistry registry ) { addDelimitedStringConverters ( registry ) ; registry . addConverter ( new StringToDurationConverter ( ) ) ; registry . addConverter ( new DurationToStringConverter ( ) ) ; registry . addConverter ( new NumberToDurationConverter ( ) ) ; registry . addConverter ( new DurationToNumberConverter ( ) ) ; registry . addConverter ( new StringToDataSizeConverter ( ) ) ; registry . addConverter ( new NumberToDataSizeConverter ( ) ) ; registry . addConverterFactory ( new StringToEnumIgnoringCaseConverterFactory ( ) ) ; }
Add converters useful for most Spring Boot applications .
13,607
public static void addDelimitedStringConverters ( ConverterRegistry registry ) { ConversionService service = ( ConversionService ) registry ; registry . addConverter ( new ArrayToDelimitedStringConverter ( service ) ) ; registry . addConverter ( new CollectionToDelimitedStringConverter ( service ) ) ; registry . addConverter ( new DelimitedStringToArrayConverter ( service ) ) ; registry . addConverter ( new DelimitedStringToCollectionConverter ( service ) ) ; }
Add converters to support delimited strings .
13,608
public static void addApplicationFormatters ( FormatterRegistry registry ) { registry . addFormatter ( new CharArrayFormatter ( ) ) ; registry . addFormatter ( new InetAddressFormatter ( ) ) ; registry . addFormatter ( new IsoOffsetFormatter ( ) ) ; }
Add formatters useful for most Spring Boot applications .
13,609
public String determineDriverClassName ( ) { if ( StringUtils . hasText ( this . driverClassName ) ) { Assert . state ( driverClassIsLoadable ( ) , ( ) -> "Cannot load driver class: " + this . driverClassName ) ; return this . driverClassName ; } String driverClassName = null ; if ( StringUtils . hasText ( this . url ) ) { driverClassName = DatabaseDriver . fromJdbcUrl ( this . url ) . getDriverClassName ( ) ; } if ( ! StringUtils . hasText ( driverClassName ) ) { driverClassName = this . embeddedDatabaseConnection . getDriverClassName ( ) ; } if ( ! StringUtils . hasText ( driverClassName ) ) { throw new DataSourceBeanCreationException ( "Failed to determine a suitable driver class" , this , this . embeddedDatabaseConnection ) ; } return driverClassName ; }
Determine the driver to use based on this configuration and the environment .
13,610
public String determineUrl ( ) { if ( StringUtils . hasText ( this . url ) ) { return this . url ; } String databaseName = determineDatabaseName ( ) ; String url = ( databaseName != null ) ? this . embeddedDatabaseConnection . getUrl ( databaseName ) : null ; if ( ! StringUtils . hasText ( url ) ) { throw new DataSourceBeanCreationException ( "Failed to determine suitable jdbc url" , this , this . embeddedDatabaseConnection ) ; } return url ; }
Determine the url to use based on this configuration and the environment .
13,611
public String determineDatabaseName ( ) { if ( this . generateUniqueName ) { if ( this . uniqueName == null ) { this . uniqueName = UUID . randomUUID ( ) . toString ( ) ; } return this . uniqueName ; } if ( StringUtils . hasLength ( this . name ) ) { return this . name ; } if ( this . embeddedDatabaseConnection != EmbeddedDatabaseConnection . NONE ) { return "testdb" ; } return null ; }
Determine the name to used based on this configuration .
13,612
public String determineUsername ( ) { if ( StringUtils . hasText ( this . username ) ) { return this . username ; } if ( EmbeddedDatabaseConnection . isEmbedded ( determineDriverClassName ( ) ) ) { return "sa" ; } return null ; }
Determine the username to use based on this configuration and the environment .
13,613
public String determinePassword ( ) { if ( StringUtils . hasText ( this . password ) ) { return this . password ; } if ( EmbeddedDatabaseConnection . isEmbedded ( determineDriverClassName ( ) ) ) { return "" ; } return null ; }
Determine the password to use based on this configuration and the environment .
13,614
private CloseableHttpResponse executeInitializrMetadataRetrieval ( String url ) { HttpGet request = new HttpGet ( url ) ; request . setHeader ( new BasicHeader ( HttpHeaders . ACCEPT , ACCEPT_META_DATA ) ) ; return execute ( request , url , "retrieve metadata" ) ; }
Retrieves the meta - data of the service at the specified URL .
13,615
public void compileAndRun ( ) throws Exception { synchronized ( this . monitor ) { try { stop ( ) ; Class < ? > [ ] compiledSources = compile ( ) ; monitorForChanges ( ) ; this . runThread = new RunThread ( compiledSources ) ; this . runThread . start ( ) ; this . runThread . join ( ) ; } catch ( Exception ex ) { if ( this . fileWatchThread == null ) { throw ex ; } else { ex . printStackTrace ( ) ; } } } }
Compile and run the application .
13,616
URI generateUrl ( InitializrServiceMetadata metadata ) { try { URIBuilder builder = new URIBuilder ( this . serviceUrl ) ; StringBuilder sb = new StringBuilder ( ) ; if ( builder . getPath ( ) != null ) { sb . append ( builder . getPath ( ) ) ; } ProjectType projectType = determineProjectType ( metadata ) ; this . type = projectType . getId ( ) ; sb . append ( projectType . getAction ( ) ) ; builder . setPath ( sb . toString ( ) ) ; if ( ! this . dependencies . isEmpty ( ) ) { builder . setParameter ( "dependencies" , StringUtils . collectionToCommaDelimitedString ( this . dependencies ) ) ; } if ( this . groupId != null ) { builder . setParameter ( "groupId" , this . groupId ) ; } String resolvedArtifactId = resolveArtifactId ( ) ; if ( resolvedArtifactId != null ) { builder . setParameter ( "artifactId" , resolvedArtifactId ) ; } if ( this . version != null ) { builder . setParameter ( "version" , this . version ) ; } if ( this . name != null ) { builder . setParameter ( "name" , this . name ) ; } if ( this . description != null ) { builder . setParameter ( "description" , this . description ) ; } if ( this . packageName != null ) { builder . setParameter ( "packageName" , this . packageName ) ; } if ( this . type != null ) { builder . setParameter ( "type" , projectType . getId ( ) ) ; } if ( this . packaging != null ) { builder . setParameter ( "packaging" , this . packaging ) ; } if ( this . javaVersion != null ) { builder . setParameter ( "javaVersion" , this . javaVersion ) ; } if ( this . language != null ) { builder . setParameter ( "language" , this . language ) ; } if ( this . bootVersion != null ) { builder . setParameter ( "bootVersion" , this . bootVersion ) ; } return builder . build ( ) ; } catch ( URISyntaxException ex ) { throw new ReportableException ( "Invalid service URL (" + ex . getMessage ( ) + ")" ) ; } }
Generates the URI to use to generate a project represented by this request .
13,617
protected final boolean anyMatches ( ConditionContext context , AnnotatedTypeMetadata metadata , Condition ... conditions ) { for ( Condition condition : conditions ) { if ( matches ( context , metadata , condition ) ) { return true ; } } return false ; }
Return true if any of the specified conditions match .
13,618
protected final boolean matches ( ConditionContext context , AnnotatedTypeMetadata metadata , Condition condition ) { if ( condition instanceof SpringBootCondition ) { return ( ( SpringBootCondition ) condition ) . getMatchOutcome ( context , metadata ) . isMatch ( ) ; } return condition . matches ( context , metadata ) ; }
Return true if any of the specified condition matches .
13,619
private boolean isLogConfigurationMessage ( Throwable ex ) { if ( ex instanceof InvocationTargetException ) { return isLogConfigurationMessage ( ex . getCause ( ) ) ; } String message = ex . getMessage ( ) ; if ( message != null ) { for ( String candidate : LOG_CONFIGURATION_MESSAGES ) { if ( message . contains ( candidate ) ) { return true ; } } } return false ; }
Check if the exception is a log configuration message i . e . the log call might not have actually output anything .
13,620
public TaskSchedulerBuilder awaitTerminationPeriod ( Duration awaitTerminationPeriod ) { return new TaskSchedulerBuilder ( this . poolSize , this . awaitTermination , awaitTerminationPeriod , this . threadNamePrefix , this . customizers ) ; }
Set the maximum time the executor is supposed to block on shutdown . When set the executor blocks on shutdown in order to wait for remaining tasks to complete their execution before the rest of the container continues to shut down . This is particularly useful if your remaining tasks are likely to need access to other resources that are also managed by the container .
13,621
public TaskSchedulerBuilder threadNamePrefix ( String threadNamePrefix ) { return new TaskSchedulerBuilder ( this . poolSize , this . awaitTermination , this . awaitTerminationPeriod , threadNamePrefix , this . customizers ) ; }
Set the prefix to use for the names of newly created threads .
13,622
public static LoggingSystem get ( ClassLoader classLoader ) { String loggingSystem = System . getProperty ( SYSTEM_PROPERTY ) ; if ( StringUtils . hasLength ( loggingSystem ) ) { if ( NONE . equals ( loggingSystem ) ) { return new NoOpLoggingSystem ( ) ; } return get ( classLoader , loggingSystem ) ; } return SYSTEMS . entrySet ( ) . stream ( ) . filter ( ( entry ) -> ClassUtils . isPresent ( entry . getKey ( ) , classLoader ) ) . map ( ( entry ) -> get ( classLoader , entry . getValue ( ) ) ) . findFirst ( ) . orElseThrow ( ( ) -> new IllegalStateException ( "No suitable logging system located" ) ) ; }
Detect and return the logging system in use . Supports Logback and Java Logging .
13,623
public void start ( ) { synchronized ( this . monitor ) { saveInitialSnapshots ( ) ; if ( this . watchThread == null ) { Map < File , FolderSnapshot > localFolders = new HashMap < > ( ) ; localFolders . putAll ( this . folders ) ; this . watchThread = new Thread ( new Watcher ( this . remainingScans , new ArrayList < > ( this . listeners ) , this . triggerFilter , this . pollInterval , this . quietPeriod , localFolders ) ) ; this . watchThread . setName ( "File Watcher" ) ; this . watchThread . setDaemon ( this . daemon ) ; this . watchThread . start ( ) ; } } }
Start monitoring the source folder for changes .
13,624
void stopAfter ( int remainingScans ) { Thread thread ; synchronized ( this . monitor ) { thread = this . watchThread ; if ( thread != null ) { this . remainingScans . set ( remainingScans ) ; if ( remainingScans <= 0 ) { thread . interrupt ( ) ; } } this . watchThread = null ; } if ( thread != null && Thread . currentThread ( ) != thread ) { try { thread . join ( ) ; } catch ( InterruptedException ex ) { Thread . currentThread ( ) . interrupt ( ) ; } } }
Stop monitoring the source folders .
13,625
protected Map < String , Object > getErrorAttributes ( ServerRequest request , boolean includeStackTrace ) { return this . errorAttributes . getErrorAttributes ( request , includeStackTrace ) ; }
Extract the error attributes from the current request to be used to populate error views or JSON payloads .
13,626
protected boolean isTraceEnabled ( ServerRequest request ) { String parameter = request . queryParam ( "trace" ) . orElse ( "false" ) ; return ! "false" . equalsIgnoreCase ( parameter ) ; }
Check whether the trace attribute has been set on the given request .
13,627
public void stop ( ) throws MojoExecutionException , IOException , InstanceNotFoundException { try { this . connection . invoke ( this . objectName , "shutdown" , null , null ) ; } catch ( ReflectionException ex ) { throw new MojoExecutionException ( "Shutdown failed" , ex . getCause ( ) ) ; } catch ( MBeanException ex ) { throw new MojoExecutionException ( "Could not invoke shutdown operation" , ex ) ; } }
Stop the application managed by this instance .
13,628
public String generate ( String url ) throws IOException { Object content = this . initializrService . loadServiceCapabilities ( url ) ; if ( content instanceof InitializrServiceMetadata ) { return generateHelp ( url , ( InitializrServiceMetadata ) content ) ; } return content . toString ( ) ; }
Generate a report for the specified service . The report contains the available capabilities as advertised by the root endpoint .
13,629
protected Mono < ServerResponse > renderErrorView ( ServerRequest request ) { boolean includeStackTrace = isIncludeStackTrace ( request , MediaType . TEXT_HTML ) ; Map < String , Object > error = getErrorAttributes ( request , includeStackTrace ) ; HttpStatus errorStatus = getHttpStatus ( error ) ; ServerResponse . BodyBuilder responseBody = ServerResponse . status ( errorStatus ) . contentType ( MediaType . TEXT_HTML ) ; return Flux . just ( "error/" + errorStatus . value ( ) , "error/" + SERIES_VIEWS . get ( errorStatus . series ( ) ) , "error/error" ) . flatMap ( ( viewName ) -> renderErrorView ( viewName , responseBody , error ) ) . switchIfEmpty ( this . errorProperties . getWhitelabel ( ) . isEnabled ( ) ? renderDefaultErrorView ( responseBody , error ) : Mono . error ( getError ( request ) ) ) . next ( ) ; }
Render the error information as an HTML view .
13,630
protected Mono < ServerResponse > renderErrorResponse ( ServerRequest request ) { boolean includeStackTrace = isIncludeStackTrace ( request , MediaType . ALL ) ; Map < String , Object > error = getErrorAttributes ( request , includeStackTrace ) ; return ServerResponse . status ( getHttpStatus ( error ) ) . contentType ( MediaType . APPLICATION_JSON_UTF8 ) . body ( BodyInserters . fromObject ( error ) ) ; }
Render the error information as a JSON payload .
13,631
protected HttpStatus getHttpStatus ( Map < String , Object > errorAttributes ) { int statusCode = ( int ) errorAttributes . get ( "status" ) ; return HttpStatus . valueOf ( statusCode ) ; }
Get the HTTP error status information from the error map .
13,632
private boolean shouldExtract ( ProjectGenerationRequest request , ProjectGenerationResponse response ) { if ( request . isExtract ( ) ) { return true ; } if ( isZipArchive ( response ) && request . getOutput ( ) != null && ! request . getOutput ( ) . contains ( "." ) ) { return true ; } return false ; }
Detect if the project should be extracted .
13,633
public final Set < Class < ? > > scan ( Class < ? extends Annotation > ... annotationTypes ) throws ClassNotFoundException { List < String > packages = getPackages ( ) ; if ( packages . isEmpty ( ) ) { return Collections . emptySet ( ) ; } ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider ( false ) ; scanner . setEnvironment ( this . context . getEnvironment ( ) ) ; scanner . setResourceLoader ( this . context ) ; for ( Class < ? extends Annotation > annotationType : annotationTypes ) { scanner . addIncludeFilter ( new AnnotationTypeFilter ( annotationType ) ) ; } Set < Class < ? > > entitySet = new HashSet < > ( ) ; for ( String basePackage : packages ) { if ( StringUtils . hasText ( basePackage ) ) { for ( BeanDefinition candidate : scanner . findCandidateComponents ( basePackage ) ) { entitySet . add ( ClassUtils . forName ( candidate . getBeanClassName ( ) , this . context . getClassLoader ( ) ) ) ; } } } return entitySet ; }
Scan for entities with the specified annotations .
13,634
private void resolveName ( ConfigurationMetadataItem item ) { item . setName ( item . getId ( ) ) ; ConfigurationMetadataSource source = getSource ( item ) ; if ( source != null ) { String groupId = source . getGroupId ( ) ; String dottedPrefix = groupId + "." ; String id = item . getId ( ) ; if ( hasLength ( groupId ) && id . startsWith ( dottedPrefix ) ) { String name = id . substring ( dottedPrefix . length ( ) ) ; item . setName ( name ) ; } } }
Resolve the name of an item against this instance .
13,635
protected void restart ( Set < URL > urls , ClassLoaderFiles files ) { Restarter restarter = Restarter . getInstance ( ) ; restarter . addUrls ( urls ) ; restarter . addClassLoaderFiles ( files ) ; restarter . restart ( ) ; }
Called to restart the application .
13,636
public final void load ( Class < ? > relativeClass , String ... resourceNames ) { Resource [ ] resources = new Resource [ resourceNames . length ] ; for ( int i = 0 ; i < resourceNames . length ; i ++ ) { resources [ i ] = new ClassPathResource ( resourceNames [ i ] , relativeClass ) ; } this . reader . loadBeanDefinitions ( resources ) ; }
Load bean definitions from the given XML resources .
13,637
public void ifBound ( Consumer < ? super T > consumer ) { Assert . notNull ( consumer , "Consumer must not be null" ) ; if ( this . value != null ) { consumer . accept ( this . value ) ; } }
Invoke the specified consumer with the bound value or do nothing if no value has been bound .
13,638
public < U > BindResult < U > map ( Function < ? super T , ? extends U > mapper ) { Assert . notNull ( mapper , "Mapper must not be null" ) ; return of ( ( this . value != null ) ? mapper . apply ( this . value ) : null ) ; }
Apply the provided mapping function to the bound value or return an updated unbound result if no value has been bound .
13,639
public T orElseCreate ( Class < ? extends T > type ) { Assert . notNull ( type , "Type must not be null" ) ; return ( this . value != null ) ? this . value : BeanUtils . instantiateClass ( type ) ; }
Return the object that was bound or a new instance of the specified class if no value has been bound .
13,640
protected ClassLoader createClassLoader ( List < Archive > archives ) throws Exception { List < URL > urls = new ArrayList < > ( archives . size ( ) ) ; for ( Archive archive : archives ) { urls . add ( archive . getUrl ( ) ) ; } return createClassLoader ( urls . toArray ( new URL [ 0 ] ) ) ; }
Create a classloader for the specified archives .
13,641
public static String toDashedForm ( String name , int start ) { StringBuilder result = new StringBuilder ( ) ; String replaced = name . replace ( '_' , '-' ) ; for ( int i = start ; i < replaced . length ( ) ; i ++ ) { char ch = replaced . charAt ( i ) ; if ( Character . isUpperCase ( ch ) && result . length ( ) > 0 && result . charAt ( result . length ( ) - 1 ) != '-' ) { result . append ( '-' ) ; } result . append ( Character . toLowerCase ( ch ) ) ; } return result . toString ( ) ; }
Return the specified Java Bean property name in dashed form .
13,642
public void replayTo ( Log destination ) { synchronized ( this . lines ) { for ( Line line : this . lines ) { logTo ( destination , line . getLevel ( ) , line . getMessage ( ) , line . getThrowable ( ) ) ; } this . lines . clear ( ) ; } }
Replay deferred logging to the specified destination .
13,643
public static ColorConverter newInstance ( Configuration config , String [ ] options ) { if ( options . length < 1 ) { LOGGER . error ( "Incorrect number of options on style. " + "Expected at least 1, received {}" , options . length ) ; return null ; } if ( options [ 0 ] == null ) { LOGGER . error ( "No pattern supplied on style" ) ; return null ; } PatternParser parser = PatternLayout . createPatternParser ( config ) ; List < PatternFormatter > formatters = parser . parse ( options [ 0 ] ) ; AnsiElement element = ( options . length != 1 ) ? ELEMENTS . get ( options [ 1 ] ) : null ; return new ColorConverter ( formatters , element ) ; }
Creates a new instance of the class . Required by Log4J2 .
13,644
public void run ( ) throws Exception { if ( this . header . contains ( "Upgrade: websocket" ) && this . header . contains ( "Sec-WebSocket-Version: 13" ) ) { runWebSocket ( ) ; } if ( this . header . contains ( "GET /livereload.js" ) ) { this . outputStream . writeHttp ( getClass ( ) . getResourceAsStream ( "livereload.js" ) , "text/javascript" ) ; } }
Run the connection .
13,645
@ SuppressWarnings ( "unchecked" ) public final Object bind ( ConfigurationPropertyName name , Bindable < ? > target , AggregateElementBinder elementBinder ) { Object result = bindAggregate ( name , target , elementBinder ) ; Supplier < ? > value = target . getValue ( ) ; if ( result == null || value == null ) { return result ; } return merge ( ( Supplier < T > ) value , ( T ) result ) ; }
Perform binding for the aggregate .
13,646
protected void addPropertySources ( ConfigurableEnvironment environment , ResourceLoader resourceLoader ) { RandomValuePropertySource . addToEnvironment ( environment ) ; new Loader ( environment , resourceLoader ) . load ( ) ; }
Add config file property sources to the specified environment .
13,647
public void setStatusMapping ( Map < String , Integer > statusMapping ) { Assert . notNull ( statusMapping , "StatusMapping must not be null" ) ; this . statusMapping = new HashMap < > ( statusMapping ) ; }
Set specific status mappings .
13,648
public void addStatusMapping ( Map < String , Integer > statusMapping ) { Assert . notNull ( statusMapping , "StatusMapping must not be null" ) ; this . statusMapping . putAll ( statusMapping ) ; }
Add specific status mappings to the existing set .
13,649
public String getRelativeName ( ) { File folder = this . sourceFolder . getAbsoluteFile ( ) ; File file = this . file . getAbsoluteFile ( ) ; String folderName = StringUtils . cleanPath ( folder . getPath ( ) ) ; String fileName = StringUtils . cleanPath ( file . getPath ( ) ) ; Assert . state ( fileName . startsWith ( folderName ) , ( ) -> "The file " + fileName + " is not contained in the source folder " + folderName ) ; return fileName . substring ( folderName . length ( ) + 1 ) ; }
Return the name of the file relative to the source folder .
13,650
AnsiString append ( String text , Code ... codes ) { if ( codes . length == 0 || ! isAnsiSupported ( ) ) { this . value . append ( text ) ; return this ; } Ansi ansi = Ansi . ansi ( ) ; for ( Code code : codes ) { ansi = applyCode ( ansi , code ) ; } this . value . append ( ansi . a ( text ) . reset ( ) . toString ( ) ) ; return this ; }
Append text with the given ANSI codes .
13,651
protected void logDisabledFork ( ) { if ( getLog ( ) . isWarnEnabled ( ) ) { if ( hasAgent ( ) ) { getLog ( ) . warn ( "Fork mode disabled, ignoring agent" ) ; } if ( hasJvmArgs ( ) ) { RunArguments runArguments = resolveJvmArguments ( ) ; getLog ( ) . warn ( "Fork mode disabled, ignoring JVM argument(s) [" + Arrays . stream ( runArguments . asArray ( ) ) . collect ( Collectors . joining ( " " ) ) + "]" ) ; } if ( hasWorkingDirectorySet ( ) ) { getLog ( ) . warn ( "Fork mode disabled, ignoring working directory configuration" ) ; } } }
Log a warning indicating that fork mode has been explicitly disabled while some conditions are present that require to enable it .
13,652
protected RunArguments resolveJvmArguments ( ) { StringBuilder stringBuilder = new StringBuilder ( ) ; if ( this . systemPropertyVariables != null ) { stringBuilder . append ( this . systemPropertyVariables . entrySet ( ) . stream ( ) . map ( ( e ) -> SystemPropertyFormatter . format ( e . getKey ( ) , e . getValue ( ) ) ) . collect ( Collectors . joining ( " " ) ) ) ; } if ( this . jvmArguments != null ) { stringBuilder . append ( " " ) . append ( this . jvmArguments ) ; } return new RunArguments ( stringBuilder . toString ( ) ) ; }
Resolve the JVM arguments to use .
13,653
protected ConditionOutcome getResourceOutcome ( ConditionContext context , AnnotatedTypeMetadata metadata ) { List < String > found = new ArrayList < > ( ) ; for ( String location : this . resourceLocations ) { Resource resource = context . getResourceLoader ( ) . getResource ( location ) ; if ( resource != null && resource . exists ( ) ) { found . add ( location ) ; } } if ( found . isEmpty ( ) ) { ConditionMessage message = startConditionMessage ( ) . didNotFind ( "resource" , "resources" ) . items ( Style . QUOTE , Arrays . asList ( this . resourceLocations ) ) ; return ConditionOutcome . noMatch ( message ) ; } ConditionMessage message = startConditionMessage ( ) . found ( "resource" , "resources" ) . items ( Style . QUOTE , found ) ; return ConditionOutcome . match ( message ) ; }
Check if one of the default resource locations actually exists .
13,654
public static List < String > get ( BeanFactory beanFactory ) { try { return beanFactory . getBean ( BEAN , BasePackages . class ) . get ( ) ; } catch ( NoSuchBeanDefinitionException ex ) { throw new IllegalStateException ( "Unable to retrieve @EnableAutoConfiguration base packages" ) ; } }
Return the auto - configuration base packages for the given bean factory .
13,655
public void clearCache ( ) { for ( URL url : getURLs ( ) ) { try { URLConnection connection = url . openConnection ( ) ; if ( connection instanceof JarURLConnection ) { clearCache ( connection ) ; } } catch ( IOException ex ) { } } }
Clear URL caches .
13,656
public int start ( ) throws IOException { synchronized ( this . monitor ) { Assert . state ( this . serverThread == null , "Server already started" ) ; ServerSocketChannel serverSocketChannel = ServerSocketChannel . open ( ) ; serverSocketChannel . socket ( ) . bind ( new InetSocketAddress ( this . listenPort ) ) ; int port = serverSocketChannel . socket ( ) . getLocalPort ( ) ; logger . trace ( "Listening for TCP traffic to tunnel on port " + port ) ; this . serverThread = new ServerThread ( serverSocketChannel ) ; this . serverThread . start ( ) ; return port ; } }
Start the client and accept incoming connections .
13,657
public void stop ( ) throws IOException { synchronized ( this . monitor ) { if ( this . serverThread != null ) { this . serverThread . close ( ) ; try { this . serverThread . join ( 2000 ) ; } catch ( InterruptedException ex ) { Thread . currentThread ( ) . interrupt ( ) ; } this . serverThread = null ; } } }
Stop the client disconnecting any servers .
13,658
protected final File createTempDir ( String prefix ) { try { File tempDir = File . createTempFile ( prefix + "." , "." + getPort ( ) ) ; tempDir . delete ( ) ; tempDir . mkdir ( ) ; tempDir . deleteOnExit ( ) ; return tempDir ; } catch ( IOException ex ) { throw new WebServerException ( "Unable to create tempDir. java.io.tmpdir is set to " + System . getProperty ( "java.io.tmpdir" ) , ex ) ; } }
Return the absolute temp dir for given web server .
13,659
private Scope peek ( ) throws JSONException { if ( this . stack . isEmpty ( ) ) { throw new JSONException ( "Nesting problem" ) ; } return this . stack . get ( this . stack . size ( ) - 1 ) ; }
Returns the value on the top of the stack .
13,660
protected DefaultCouchbaseEnvironment . Builder initializeEnvironmentBuilder ( CouchbaseProperties properties ) { CouchbaseProperties . Endpoints endpoints = properties . getEnv ( ) . getEndpoints ( ) ; CouchbaseProperties . Timeouts timeouts = properties . getEnv ( ) . getTimeouts ( ) ; DefaultCouchbaseEnvironment . Builder builder = DefaultCouchbaseEnvironment . builder ( ) ; if ( timeouts . getConnect ( ) != null ) { builder = builder . connectTimeout ( timeouts . getConnect ( ) . toMillis ( ) ) ; } builder = builder . keyValueServiceConfig ( KeyValueServiceConfig . create ( endpoints . getKeyValue ( ) ) ) ; if ( timeouts . getKeyValue ( ) != null ) { builder = builder . kvTimeout ( timeouts . getKeyValue ( ) . toMillis ( ) ) ; } if ( timeouts . getQuery ( ) != null ) { builder = builder . queryTimeout ( timeouts . getQuery ( ) . toMillis ( ) ) ; builder = builder . queryServiceConfig ( getQueryServiceConfig ( endpoints ) ) ; builder = builder . viewServiceConfig ( getViewServiceConfig ( endpoints ) ) ; } if ( timeouts . getSocketConnect ( ) != null ) { builder = builder . socketConnectTimeout ( ( int ) timeouts . getSocketConnect ( ) . toMillis ( ) ) ; } if ( timeouts . getView ( ) != null ) { builder = builder . viewTimeout ( timeouts . getView ( ) . toMillis ( ) ) ; } CouchbaseProperties . Ssl ssl = properties . getEnv ( ) . getSsl ( ) ; if ( ssl . getEnabled ( ) ) { builder = builder . sslEnabled ( true ) ; if ( ssl . getKeyStore ( ) != null ) { builder = builder . sslKeystoreFile ( ssl . getKeyStore ( ) ) ; } if ( ssl . getKeyStorePassword ( ) != null ) { builder = builder . sslKeystorePassword ( ssl . getKeyStorePassword ( ) ) ; } } return builder ; }
Initialize an environment builder based on the specified settings .
13,661
protected Map < String , Object > aggregateDetails ( Map < String , Health > healths ) { return new LinkedHashMap < > ( healths ) ; }
Return the map of aggregate details that should be used from the specified healths .
13,662
public void setListener ( T listener ) { Assert . notNull ( listener , "Listener must not be null" ) ; Assert . isTrue ( isSupportedType ( listener ) , "Listener is not of a supported type" ) ; this . listener = listener ; }
Set the listener that will be registered .
13,663
public int determinePort ( ) { if ( CollectionUtils . isEmpty ( this . parsedAddresses ) ) { return getPort ( ) ; } Address address = this . parsedAddresses . get ( 0 ) ; return address . port ; }
Returns the port from the first address or the configured port if no addresses have been set .
13,664
public void setStatusOrder ( Status ... statusOrder ) { String [ ] order = new String [ statusOrder . length ] ; for ( int i = 0 ; i < statusOrder . length ; i ++ ) { order [ i ] = statusOrder [ i ] . getCode ( ) ; } setStatusOrder ( Arrays . asList ( order ) ) ; }
Set the ordering of the status .
13,665
protected boolean shouldRegisterJspServlet ( ) { return this . jsp != null && this . jsp . getRegistered ( ) && ClassUtils . isPresent ( this . jsp . getClassName ( ) , getClass ( ) . getClassLoader ( ) ) ; }
Returns whether or not the JSP servlet should be registered with the web server .
13,666
protected void logStartupProfileInfo ( ConfigurableApplicationContext context ) { Log log = getApplicationLog ( ) ; if ( log . isInfoEnabled ( ) ) { String [ ] activeProfiles = context . getEnvironment ( ) . getActiveProfiles ( ) ; if ( ObjectUtils . isEmpty ( activeProfiles ) ) { String [ ] defaultProfiles = context . getEnvironment ( ) . getDefaultProfiles ( ) ; log . info ( "No active profile set, falling back to default profiles: " + StringUtils . arrayToCommaDelimitedString ( defaultProfiles ) ) ; } else { log . info ( "The following profiles are active: " + StringUtils . arrayToCommaDelimitedString ( activeProfiles ) ) ; } } }
Called to log active profile information .
13,667
protected void load ( ApplicationContext context , Object [ ] sources ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Loading source " + StringUtils . arrayToCommaDelimitedString ( sources ) ) ; } BeanDefinitionLoader loader = createBeanDefinitionLoader ( getBeanDefinitionRegistry ( context ) , sources ) ; if ( this . beanNameGenerator != null ) { loader . setBeanNameGenerator ( this . beanNameGenerator ) ; } if ( this . resourceLoader != null ) { loader . setResourceLoader ( this . resourceLoader ) ; } if ( this . environment != null ) { loader . setEnvironment ( this . environment ) ; } loader . load ( ) ; }
Load beans into the application context .
13,668
private BeanDefinitionRegistry getBeanDefinitionRegistry ( ApplicationContext context ) { if ( context instanceof BeanDefinitionRegistry ) { return ( BeanDefinitionRegistry ) context ; } if ( context instanceof AbstractApplicationContext ) { return ( BeanDefinitionRegistry ) ( ( AbstractApplicationContext ) context ) . getBeanFactory ( ) ; } throw new IllegalStateException ( "Could not locate BeanDefinitionRegistry" ) ; }
Get the bean definition registry .
13,669
protected void registerLoggedException ( Throwable exception ) { SpringBootExceptionHandler handler = getSpringBootExceptionHandler ( ) ; if ( handler != null ) { handler . registerLoggedException ( exception ) ; } }
Register that the given exception has been logged . By default if the running in the main thread this method will suppress additional printing of the stacktrace .
13,670
public String add ( String extension , String mimeType ) { Mapping previous = this . map . put ( extension , new Mapping ( extension , mimeType ) ) ; return ( previous != null ) ? previous . getMimeType ( ) : null ; }
Add a new mime mapping .
13,671
public String get ( String extension ) { Mapping mapping = this . map . get ( extension ) ; return ( mapping != null ) ? mapping . getMimeType ( ) : null ; }
Get a mime mapping for the given extension .
13,672
public String remove ( String extension ) { Mapping previous = this . map . remove ( extension ) ; return ( previous != null ) ? previous . getMimeType ( ) : null ; }
Remove an existing mapping .
13,673
public void setBeanNameGenerator ( BeanNameGenerator beanNameGenerator ) { this . annotatedReader . setBeanNameGenerator ( beanNameGenerator ) ; this . xmlReader . setBeanNameGenerator ( beanNameGenerator ) ; this . scanner . setBeanNameGenerator ( beanNameGenerator ) ; }
Set the bean name generator to be used by the underlying readers and scanner .
13,674
public void setResourceLoader ( ResourceLoader resourceLoader ) { this . resourceLoader = resourceLoader ; this . xmlReader . setResourceLoader ( resourceLoader ) ; this . scanner . setResourceLoader ( resourceLoader ) ; }
Set the resource loader to be used by the underlying readers and scanner .
13,675
public void setEnvironment ( ConfigurableEnvironment environment ) { this . annotatedReader . setEnvironment ( environment ) ; this . xmlReader . setEnvironment ( environment ) ; this . scanner . setEnvironment ( environment ) ; }
Set the environment to be used by the underlying readers and scanner .
13,676
public void putAll ( Map < ? , ? > map ) { Assert . notNull ( map , "Map must not be null" ) ; assertNotReadOnlySystemAttributesMap ( map ) ; map . forEach ( this :: put ) ; }
Add all entries from the specified map .
13,677
public void put ( Object name , Object value ) { this . source . put ( ( name != null ) ? name . toString ( ) : null , value ) ; }
Add an individual entry .
13,678
protected ServerThread getServerThread ( ) throws IOException { synchronized ( this ) { if ( this . serverThread == null ) { ByteChannel channel = this . serverConnection . open ( this . longPollTimeout ) ; this . serverThread = new ServerThread ( channel ) ; this . serverThread . start ( ) ; } return this . serverThread ; } }
Returns the active server thread creating and starting it if necessary .
13,679
public Mono < AccessLevel > getAccessLevel ( String token , String applicationId ) throws CloudFoundryAuthorizationException { String uri = getPermissionsUri ( applicationId ) ; return this . webClient . get ( ) . uri ( uri ) . header ( "Authorization" , "bearer " + token ) . retrieve ( ) . bodyToMono ( Map . class ) . map ( this :: getAccessLevel ) . onErrorMap ( this :: mapError ) ; }
Return a Mono of the access level that should be granted to the given token .
13,680
public Mono < String > getUaaUrl ( ) { this . uaaUrl = this . webClient . get ( ) . uri ( this . cloudControllerUrl + "/info" ) . retrieve ( ) . bodyToMono ( Map . class ) . map ( ( response ) -> ( String ) response . get ( "token_endpoint" ) ) . cache ( ) . onErrorMap ( ( ex ) -> new CloudFoundryAuthorizationException ( Reason . SERVICE_UNAVAILABLE , "Unable to fetch token keys from UAA." ) ) ; return this . uaaUrl ; }
Return a Mono of URL of the UAA .
13,681
protected final FilterArtifacts getFilters ( ArtifactsFilter ... additionalFilters ) { FilterArtifacts filters = new FilterArtifacts ( ) ; for ( ArtifactsFilter additionalFilter : additionalFilters ) { filters . addFilter ( additionalFilter ) ; } filters . addFilter ( new MatchingGroupIdFilter ( cleanFilterConfig ( this . excludeGroupIds ) ) ) ; if ( this . includes != null && ! this . includes . isEmpty ( ) ) { filters . addFilter ( new IncludeFilter ( this . includes ) ) ; } if ( this . excludes != null && ! this . excludes . isEmpty ( ) ) { filters . addFilter ( new ExcludeFilter ( this . excludes ) ) ; } return filters ; }
Return artifact filters configured for this MOJO .
13,682
public int size ( ) { int size = 0 ; for ( SourceFolder sourceFolder : this . sourceFolders . values ( ) ) { size += sourceFolder . getFiles ( ) . size ( ) ; } return size ; }
Return the size of the collection .
13,683
public int getExitCode ( ) { int exitCode = 0 ; for ( ExitCodeGenerator generator : this . generators ) { try { int value = generator . getExitCode ( ) ; if ( value > 0 && value > exitCode || value < 0 && value < exitCode ) { exitCode = value ; } } catch ( Exception ex ) { exitCode = ( exitCode != 0 ) ? exitCode : 1 ; ex . printStackTrace ( ) ; } } return exitCode ; }
Get the final exit code that should be returned based on all contained generators .
13,684
public void handle ( ServerHttpRequest request , ServerHttpResponse response ) throws IOException { try { Assert . state ( request . getHeaders ( ) . getContentLength ( ) > 0 , "No content" ) ; ObjectInputStream objectInputStream = new ObjectInputStream ( request . getBody ( ) ) ; ClassLoaderFiles files = ( ClassLoaderFiles ) objectInputStream . readObject ( ) ; objectInputStream . close ( ) ; this . server . updateAndRestart ( files ) ; response . setStatusCode ( HttpStatus . OK ) ; } catch ( Exception ex ) { logger . warn ( "Unable to handler restart server HTTP request" , ex ) ; response . setStatusCode ( HttpStatus . INTERNAL_SERVER_ERROR ) ; } }
Handle a server request .
13,685
protected File getPortFile ( ApplicationContext applicationContext ) { String namespace = getServerNamespace ( applicationContext ) ; if ( StringUtils . isEmpty ( namespace ) ) { return this . file ; } String name = this . file . getName ( ) ; String extension = StringUtils . getFilenameExtension ( this . file . getName ( ) ) ; name = name . substring ( 0 , name . length ( ) - extension . length ( ) - 1 ) ; if ( isUpperCase ( name ) ) { name = name + "-" + namespace . toUpperCase ( Locale . ENGLISH ) ; } else { name = name + "-" + namespace . toLowerCase ( Locale . ENGLISH ) ; } if ( StringUtils . hasLength ( extension ) ) { name = name + "." + extension ; } return new File ( this . file . getParentFile ( ) , name ) ; }
Return the actual port file that should be written for the given application context . The default implementation builds a file from the source file and the application context namespace if available .
13,686
public static OperationInvoker apply ( OperationInvoker invoker , long timeToLive ) { if ( timeToLive > 0 ) { return new CachingOperationInvoker ( invoker , timeToLive ) ; } return invoker ; }
Apply caching configuration when appropriate to the given invoker .
13,687
public void writeTo ( WritableByteChannel channel ) throws IOException { Assert . notNull ( channel , "Channel must not be null" ) ; while ( this . data . hasRemaining ( ) ) { channel . write ( this . data ) ; } }
Write the content of this payload to the given target channel .
13,688
public String toHexString ( ) { byte [ ] bytes = this . data . array ( ) ; char [ ] hex = new char [ this . data . remaining ( ) * 2 ] ; for ( int i = this . data . position ( ) ; i < this . data . remaining ( ) ; i ++ ) { int b = bytes [ i ] & 0xFF ; hex [ i * 2 ] = HEX_CHARS [ b >>> 4 ] ; hex [ i * 2 + 1 ] = HEX_CHARS [ b & 0x0F ] ; } return new String ( hex ) ; }
Return the payload as a hexadecimal string .
13,689
protected boolean isMain ( Thread thread ) { return thread . getName ( ) . equals ( "main" ) && thread . getContextClassLoader ( ) . getClass ( ) . getName ( ) . contains ( "AppClassLoader" ) ; }
Returns if the thread is for a main invocation . By default checks the name of the thread and the context classloader .
13,690
public AccessLevel getAccessLevel ( String token , String applicationId ) throws CloudFoundryAuthorizationException { try { URI uri = getPermissionsUri ( applicationId ) ; RequestEntity < ? > request = RequestEntity . get ( uri ) . header ( "Authorization" , "bearer " + token ) . build ( ) ; Map < ? , ? > body = this . restTemplate . exchange ( request , Map . class ) . getBody ( ) ; if ( Boolean . TRUE . equals ( body . get ( "read_sensitive_data" ) ) ) { return AccessLevel . FULL ; } return AccessLevel . RESTRICTED ; } catch ( HttpClientErrorException ex ) { if ( ex . getStatusCode ( ) . equals ( HttpStatus . FORBIDDEN ) ) { throw new CloudFoundryAuthorizationException ( Reason . ACCESS_DENIED , "Access denied" ) ; } throw new CloudFoundryAuthorizationException ( Reason . INVALID_TOKEN , "Invalid token" , ex ) ; } catch ( HttpServerErrorException ex ) { throw new CloudFoundryAuthorizationException ( Reason . SERVICE_UNAVAILABLE , "Cloud controller not reachable" ) ; } }
Return the access level that should be granted to the given token .
13,691
public Map < String , String > fetchTokenKeys ( ) { try { return extractTokenKeys ( this . restTemplate . getForObject ( getUaaUrl ( ) + "/token_keys" , Map . class ) ) ; } catch ( HttpStatusCodeException ex ) { throw new CloudFoundryAuthorizationException ( Reason . SERVICE_UNAVAILABLE , "UAA not reachable" ) ; } }
Return all token keys known by the UAA .
13,692
public String getUaaUrl ( ) { if ( this . uaaUrl == null ) { try { Map < ? , ? > response = this . restTemplate . getForObject ( this . cloudControllerUrl + "/info" , Map . class ) ; this . uaaUrl = ( String ) response . get ( "token_endpoint" ) ; } catch ( HttpStatusCodeException ex ) { throw new CloudFoundryAuthorizationException ( Reason . SERVICE_UNAVAILABLE , "Unable to fetch token keys from UAA" ) ; } } return this . uaaUrl ; }
Return the URL of the UAA .
13,693
public void addUrlMappings ( String ... urlMappings ) { Assert . notNull ( urlMappings , "UrlMappings must not be null" ) ; this . urlMappings . addAll ( Arrays . asList ( urlMappings ) ) ; }
Add URL mappings as defined in the Servlet specification for the servlet .
13,694
private Configuration getErrorPageConfiguration ( ) { return new AbstractConfiguration ( ) { public void configure ( WebAppContext context ) throws Exception { ErrorHandler errorHandler = context . getErrorHandler ( ) ; context . setErrorHandler ( new JettyEmbeddedErrorHandler ( errorHandler ) ) ; addJettyErrorPages ( errorHandler , getErrorPages ( ) ) ; } } ; }
Create a configuration object that adds error handlers .
13,695
private Configuration getMimeTypeConfiguration ( ) { return new AbstractConfiguration ( ) { public void configure ( WebAppContext context ) throws Exception { MimeTypes mimeTypes = context . getMimeTypes ( ) ; for ( MimeMappings . Mapping mapping : getMimeMappings ( ) ) { mimeTypes . addMimeMapping ( mapping . getExtension ( ) , mapping . getMimeType ( ) ) ; } } } ; }
Create a configuration object that adds mime type mappings .
13,696
public Object nextValue ( ) throws JSONException { int c = nextCleanInternal ( ) ; switch ( c ) { case - 1 : throw syntaxError ( "End of input" ) ; case '{' : return readObject ( ) ; case '[' : return readArray ( ) ; case '\'' : case '"' : return nextString ( ( char ) c ) ; default : this . pos -- ; return readLiteral ( ) ; } }
Returns the next value from the input .
13,697
public static List < RepositoryConfiguration > createDefaultRepositoryConfiguration ( ) { MavenSettings mavenSettings = new MavenSettingsReader ( ) . readSettings ( ) ; List < RepositoryConfiguration > repositoryConfiguration = new ArrayList < > ( ) ; repositoryConfiguration . add ( MAVEN_CENTRAL ) ; if ( ! Boolean . getBoolean ( "disableSpringSnapshotRepos" ) ) { repositoryConfiguration . add ( SPRING_MILESTONE ) ; repositoryConfiguration . add ( SPRING_SNAPSHOT ) ; } addDefaultCacheAsRepository ( mavenSettings . getLocalRepository ( ) , repositoryConfiguration ) ; addActiveProfileRepositories ( mavenSettings . getActiveProfiles ( ) , repositoryConfiguration ) ; return repositoryConfiguration ; }
Create a new default repository configuration .
13,698
protected void handleInvalidExcludes ( List < String > invalidExcludes ) { StringBuilder message = new StringBuilder ( ) ; for ( String exclude : invalidExcludes ) { message . append ( "\t- " ) . append ( exclude ) . append ( String . format ( "%n" ) ) ; } throw new IllegalStateException ( String . format ( "The following classes could not be excluded because they are" + " not auto-configuration classes:%n%s" , message ) ) ; }
Handle any invalid excludes that have been specified .
13,699
protected Set < String > getExclusions ( AnnotationMetadata metadata , AnnotationAttributes attributes ) { Set < String > excluded = new LinkedHashSet < > ( ) ; excluded . addAll ( asList ( attributes , "exclude" ) ) ; excluded . addAll ( Arrays . asList ( attributes . getStringArray ( "excludeName" ) ) ) ; excluded . addAll ( getExcludeAutoConfigurationsProperty ( ) ) ; return excluded ; }
Return any exclusions that limit the candidate configurations .