code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public WebServiceTemplateBuilder setFaultMessageResolver( FaultMessageResolver faultMessageResolver) { return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, append(this.internalCustomizers, new FaultMessageResolverCustomizer(faultMessageResolver)), this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, this.destinationProvider, this.transformerFactoryClass, this.messageFactory); }
Set the {@link FaultMessageResolver} to use. @param faultMessageResolver the fault message resolver to use @return a new builder instance. @see WebServiceTemplate#setFaultMessageResolver(FaultMessageResolver)
public WebServiceTemplateBuilder setTransformerFactoryClass( Class<? extends TransformerFactory> transformerFactoryClass) { return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, this.internalCustomizers, this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, this.destinationProvider, transformerFactoryClass, this.messageFactory); }
Set the {@link TransformerFactory} implementation to use. @param transformerFactoryClass the transformer factory implementation to use @return a new builder instance. @see WebServiceTemplate#setTransformerFactoryClass(Class)
public WebServiceTemplateBuilder setDefaultUri(String defaultUri) { Assert.hasText(defaultUri, "DefaultUri must not be empty"); return setDestinationProvider(() -> URI.create(defaultUri)); }
Set the default URI to be used on operations that do not have a URI parameter. Typically, either this property is set, or {@link #setDestinationProvider(DestinationProvider)}, but not both. @param defaultUri the destination provider URI to be used on operations that do not have a URI parameter. @return a new builder instance. @see #setDestinationProvider(DestinationProvider)
public WebServiceTemplateBuilder setDestinationProvider( DestinationProvider destinationProvider) { Assert.notNull(destinationProvider, "DestinationProvider must not be null"); return new WebServiceTemplateBuilder(this.detectHttpMessageSender, this.interceptors, this.internalCustomizers, this.customizers, this.messageSenders, this.marshaller, this.unmarshaller, destinationProvider, this.transformerFactoryClass, this.messageFactory); }
Set the {@link DestinationProvider} to use. Typically, either this property is set, or {@link #setDefaultUri(String)}, but not both. @param destinationProvider the destination provider to be used on operations that do not have a URI parameter. @return a new builder instance. @see WebServiceTemplate#setDestinationProvider(DestinationProvider)
public <T extends WebServiceTemplate> T build(Class<T> webServiceTemplateClass) { Assert.notNull(webServiceTemplateClass, "WebServiceTemplateClass must not be null"); return configure(BeanUtils.instantiateClass(webServiceTemplateClass)); }
Build a new {@link WebServiceTemplate} instance of the specified type and configure it using this builder. @param <T> the type of web service template @param webServiceTemplateClass the template type to create @return a configured {@link WebServiceTemplate} instance. @see WebServiceTemplateBuilder#build() @see #configure(WebServiceTemplate)
public <T extends WebServiceTemplate> T configure(T webServiceTemplate) { Assert.notNull(webServiceTemplate, "WebServiceTemplate must not be null"); configureMessageSenders(webServiceTemplate); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); applyCustomizers(webServiceTemplate, this.internalCustomizers); map.from(this.marshaller).to(webServiceTemplate::setMarshaller); map.from(this.unmarshaller).to(webServiceTemplate::setUnmarshaller); map.from(this.destinationProvider).to(webServiceTemplate::setDestinationProvider); map.from(this.transformerFactoryClass) .to(webServiceTemplate::setTransformerFactoryClass); map.from(this.messageFactory).to(webServiceTemplate::setMessageFactory); if (!CollectionUtils.isEmpty(this.interceptors)) { Set<ClientInterceptor> merged = new LinkedHashSet<>(this.interceptors); if (webServiceTemplate.getInterceptors() != null) { merged.addAll(Arrays.asList(webServiceTemplate.getInterceptors())); } webServiceTemplate.setInterceptors(merged.toArray(new ClientInterceptor[0])); } applyCustomizers(webServiceTemplate, this.customizers); return webServiceTemplate; }
Configure the provided {@link WebServiceTemplate} instance using this builder. @param <T> the type of web service template @param webServiceTemplate the {@link WebServiceTemplate} to configure @return the web service template instance @see #build() @see #build(Class)
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. @param beanFactory the source bean factory @return a list of auto-configuration packages @throws IllegalStateException if auto-configuration is not enabled
public static void register(BeanDefinitionRegistry registry, String... packageNames) { if (registry.containsBeanDefinition(BEAN)) { BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN); ConstructorArgumentValues constructorArguments = beanDefinition .getConstructorArgumentValues(); constructorArguments.addIndexedArgumentValue(0, addBasePackages(constructorArguments, packageNames)); } else { GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(BasePackages.class); beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, packageNames); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN, beanDefinition); } }
Programmatically registers the auto-configuration package names. Subsequent invocations will add the given package names to those that have already been registered. You can use this method to manually define the base packages that will be used for a given {@link BeanDefinitionRegistry}. Generally it's recommended that you don't call this method directly, but instead rely on the default convention where the package name is set from your {@code @EnableAutoConfiguration} configuration class or classes. @param registry the bean definition registry @param packageNames the package names to set
public void setDeploymentInfoCustomizers( Collection<? extends UndertowDeploymentInfoCustomizer> customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.deploymentInfoCustomizers = new ArrayList<>(customizers); }
Set {@link UndertowDeploymentInfoCustomizer}s that should be applied to the Undertow {@link DeploymentInfo}. Calling this method will replace any existing customizers. @param customizers the customizers to set
public void setBuilderCustomizers( Collection<? extends UndertowBuilderCustomizer> customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.builderCustomizers = new ArrayList<>(customizers); }
Set {@link UndertowBuilderCustomizer}s that should be applied to the Undertow {@link io.undertow.Undertow.Builder Builder}. Calling this method will replace any existing customizers. @param customizers the customizers to set
@Override public void addBuilderCustomizers(UndertowBuilderCustomizer... customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.builderCustomizers.addAll(Arrays.asList(customizers)); }
Add {@link UndertowBuilderCustomizer}s that should be used to customize the Undertow {@link io.undertow.Undertow.Builder Builder}. @param customizers the customizers to add
private void definePackageIfNecessary(String className) { int lastDot = className.lastIndexOf('.'); if (lastDot >= 0) { String packageName = className.substring(0, lastDot); if (getPackage(packageName) == null) { try { definePackage(className, packageName); } catch (IllegalArgumentException ex) { // Tolerate race condition due to being parallel capable if (getPackage(packageName) == null) { // This should never happen as the IllegalArgumentException // indicates that the package has already been defined and, // therefore, getPackage(name) should not have returned null. throw new AssertionError( "Package " + packageName + " has already been defined " + "but it could not be found"); } } } } }
Define a package before a {@code findClass} call is made. This is necessary to ensure that the appropriate manifest for nested JARs is associated with the package. @param className the class name being found
public void clearCache() { for (URL url : getURLs()) { try { URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection) { clearCache(connection); } } catch (IOException ex) { // Ignore } } }
Clear URL caches.
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. @return the port on which the client is listening @throws IOException in case of I/O errors
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. @throws IOException in case of I/O errors
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. @param prefix server name @return the temp dir for given server.
public void writeManifest(Manifest manifest) throws IOException { JarArchiveEntry entry = new JarArchiveEntry("META-INF/MANIFEST.MF"); writeEntry(entry, manifest::write); }
Write the specified manifest. @param manifest the manifest to write @throws IOException of the manifest cannot be written
@Override public void writeEntry(String entryName, InputStream inputStream) throws IOException { JarArchiveEntry entry = new JarArchiveEntry(entryName); writeEntry(entry, new InputStreamEntryWriter(inputStream, true)); }
Writes an entry. The {@code inputStream} is closed once the entry has been written @param entryName the name of the entry @param inputStream the stream from which the entry's data can be read @throws IOException if the write fails
public void writeNestedLibrary(String destination, Library library) throws IOException { File file = library.getFile(); JarArchiveEntry entry = new JarArchiveEntry(destination + library.getName()); entry.setTime(getNestedLibraryTime(file)); new CrcAndSize(file).setupStoredEntry(entry); writeEntry(entry, new InputStreamEntryWriter(new FileInputStream(file), true), new LibraryUnpackHandler(library)); }
Write a nested library. @param destination the destination of the library @param library the library @throws IOException if the write fails
@Override public void writeLoaderClasses(String loaderJarResourceName) throws IOException { URL loaderJar = getClass().getClassLoader().getResource(loaderJarResourceName); try (JarInputStream inputStream = new JarInputStream( new BufferedInputStream(loaderJar.openStream()))) { JarEntry entry; while ((entry = inputStream.getNextJarEntry()) != null) { if (entry.getName().endsWith(".class")) { writeEntry(new JarArchiveEntry(entry), new InputStreamEntryWriter(inputStream, false)); } } } }
Write the required spring-boot-loader classes to the JAR. @param loaderJarResourceName the name of the resource containing the loader classes to be written @throws IOException if the classes cannot be written
private void writeEntry(JarArchiveEntry entry, EntryWriter entryWriter, UnpackHandler unpackHandler) throws IOException { String parent = entry.getName(); if (parent.endsWith("/")) { parent = parent.substring(0, parent.length() - 1); entry.setUnixMode(UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM); } else { entry.setUnixMode(UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM); } if (parent.lastIndexOf('/') != -1) { parent = parent.substring(0, parent.lastIndexOf('/') + 1); if (!parent.isEmpty()) { writeEntry(new JarArchiveEntry(parent), null, unpackHandler); } } if (this.writtenEntries.add(entry.getName())) { entryWriter = addUnpackCommentIfNecessary(entry, entryWriter, unpackHandler); this.jarOutput.putArchiveEntry(entry); if (entryWriter != null) { entryWriter.write(this.jarOutput); } this.jarOutput.closeArchiveEntry(); } }
Perform the actual write of a {@link JarEntry}. All other write methods delegate to this one. @param entry the entry to write @param entryWriter the entry writer or {@code null} if there is no content @param unpackHandler handles possible unpacking for the entry @throws IOException in case of I/O errors
JSONStringer open(Scope empty, String openBracket) throws JSONException { if (this.stack.isEmpty() && this.out.length() > 0) { throw new JSONException("Nesting problem: multiple top-level roots"); } beforeValue(); this.stack.add(empty); this.out.append(openBracket); return this; }
Enters a new scope by appending any necessary whitespace and the given bracket. @param empty any necessary whitespace @param openBracket the open bracket @return this object @throws JSONException if processing of json failed
JSONStringer close(Scope empty, Scope nonempty, String closeBracket) throws JSONException { Scope context = peek(); if (context != nonempty && context != empty) { throw new JSONException("Nesting problem"); } this.stack.remove(this.stack.size() - 1); if (context == nonempty) { newline(); } this.out.append(closeBracket); return this; }
Closes the current scope by appending any necessary whitespace and the given bracket. @param empty any necessary whitespace @param nonempty the current scope @param closeBracket the close bracket @return the JSON stringer @throws JSONException if processing of json failed
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. @return the scope @throws JSONException if processing of json failed
public JSONStringer value(Object value) throws JSONException { if (this.stack.isEmpty()) { throw new JSONException("Nesting problem"); } if (value instanceof JSONArray) { ((JSONArray) value).writeTo(this); return this; } else if (value instanceof JSONObject) { ((JSONObject) value).writeTo(this); return this; } beforeValue(); if (value == null || value instanceof Boolean || value == JSONObject.NULL) { this.out.append(value); } else if (value instanceof Number) { this.out.append(JSONObject.numberToString((Number) value)); } else { string(value.toString()); } return this; }
Encodes {@code value}. @param value a {@link JSONObject}, {@link JSONArray}, String, Boolean, Integer, Long, Double or null. May not be {@link Double#isNaN() NaNs} or {@link Double#isInfinite() infinities}. @return this stringer. @throws JSONException if processing of json failed
public JSONStringer value(boolean value) throws JSONException { if (this.stack.isEmpty()) { throw new JSONException("Nesting problem"); } beforeValue(); this.out.append(value); return this; }
Encodes {@code value} to this stringer. @param value the value to encode @return this stringer. @throws JSONException if processing of json failed
public JSONStringer key(String name) throws JSONException { if (name == null) { throw new JSONException("Names must be non-null"); } beforeKey(); string(name); return this; }
Encodes the key (property name) to this stringer. @param name the name of the forthcoming value. May not be null. @return this stringer. @throws JSONException if processing of json failed
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. @param properties the couchbase properties to use @return the {@link DefaultCouchbaseEnvironment} builder.
public static String findSingleMainClass(File rootFolder, String annotationName) throws IOException { SingleMainClassCallback callback = new SingleMainClassCallback(annotationName); MainClassFinder.doWithMainClasses(rootFolder, callback); return callback.getMainClassName(); }
Find a single main class from the given {@code rootFolder}. A main class annotated with an annotation with the given {@code annotationName} will be preferred over a main class with no such annotation. @param rootFolder the root folder to search @param annotationName the name of the annotation that may be present on the main class @return the main class or {@code null} @throws IOException if the folder cannot be read
static <T> T doWithMainClasses(File rootFolder, MainClassCallback<T> callback) throws IOException { if (!rootFolder.exists()) { return null; // nothing to do } if (!rootFolder.isDirectory()) { throw new IllegalArgumentException( "Invalid root folder '" + rootFolder + "'"); } String prefix = rootFolder.getAbsolutePath() + "/"; Deque<File> stack = new ArrayDeque<>(); stack.push(rootFolder); while (!stack.isEmpty()) { File file = stack.pop(); if (file.isFile()) { try (InputStream inputStream = new FileInputStream(file)) { ClassDescriptor classDescriptor = createClassDescriptor(inputStream); if (classDescriptor != null && classDescriptor.isMainMethodFound()) { String className = convertToClassName(file.getAbsolutePath(), prefix); T result = callback.doWith(new MainClass(className, classDescriptor.getAnnotationNames())); if (result != null) { return result; } } } } if (file.isDirectory()) { pushAllSorted(stack, file.listFiles(PACKAGE_FOLDER_FILTER)); pushAllSorted(stack, file.listFiles(CLASS_FILE_FILTER)); } } return null; }
Perform the given callback operation on all main classes from the given root folder. @param <T> the result type @param rootFolder the root folder @param callback the callback @return the first callback result or {@code null} @throws IOException in case of I/O errors
public static String findMainClass(JarFile jarFile, String classesLocation) throws IOException { return doWithMainClasses(jarFile, classesLocation, MainClass::getName); }
Find the main class in a given jar file. @param jarFile the jar file to search @param classesLocation the location within the jar containing classes @return the main class or {@code null} @throws IOException if the jar file cannot be read
public static String findSingleMainClass(JarFile jarFile, String classesLocation) throws IOException { return findSingleMainClass(jarFile, classesLocation, null); }
Find a single main class in a given jar file. @param jarFile the jar file to search @param classesLocation the location within the jar containing classes @return the main class or {@code null} @throws IOException if the jar file cannot be read
public static String findSingleMainClass(JarFile jarFile, String classesLocation, String annotationName) throws IOException { SingleMainClassCallback callback = new SingleMainClassCallback(annotationName); MainClassFinder.doWithMainClasses(jarFile, classesLocation, callback); return callback.getMainClassName(); }
Find a single main class in a given jar file. A main class annotated with an annotation with the given {@code annotationName} will be preferred over a main class with no such annotation. @param jarFile the jar file to search @param classesLocation the location within the jar containing classes @param annotationName the name of the annotation that may be present on the main class @return the main class or {@code null} @throws IOException if the jar file cannot be read
static <T> T doWithMainClasses(JarFile jarFile, String classesLocation, MainClassCallback<T> callback) throws IOException { List<JarEntry> classEntries = getClassEntries(jarFile, classesLocation); classEntries.sort(new ClassEntryComparator()); for (JarEntry entry : classEntries) { try (InputStream inputStream = new BufferedInputStream( jarFile.getInputStream(entry))) { ClassDescriptor classDescriptor = createClassDescriptor(inputStream); if (classDescriptor != null && classDescriptor.isMainMethodFound()) { String className = convertToClassName(entry.getName(), classesLocation); T result = callback.doWith(new MainClass(className, classDescriptor.getAnnotationNames())); if (result != null) { return result; } } } } return null; }
Perform the given callback operation on all main classes from the given jar. @param <T> the result type @param jarFile the jar file to search @param classesLocation the location within the jar containing classes @param callback the callback @return the first callback result or {@code null} @throws IOException in case of I/O errors
public static void attach(Environment environment) { Assert.isInstanceOf(ConfigurableEnvironment.class, environment); MutablePropertySources sources = ((ConfigurableEnvironment) environment) .getPropertySources(); PropertySource<?> attached = sources.get(ATTACHED_PROPERTY_SOURCE_NAME); if (attached != null && attached.getSource() != sources) { sources.remove(ATTACHED_PROPERTY_SOURCE_NAME); attached = null; } if (attached == null) { sources.addFirst(new ConfigurationPropertySourcesPropertySource( ATTACHED_PROPERTY_SOURCE_NAME, new SpringConfigurationPropertySources(sources))); } }
Attach a {@link ConfigurationPropertySource} support to the specified {@link Environment}. Adapts each {@link PropertySource} managed by the environment to a {@link ConfigurationPropertySource} and allows classic {@link PropertySourcesPropertyResolver} calls to resolve using {@link ConfigurationPropertyName configuration property names}. <p> The attached resolver will dynamically track any additions or removals from the underlying {@link Environment} property sources. @param environment the source environment (must be an instance of {@link ConfigurableEnvironment}) @see #get(Environment)
public static Iterable<ConfigurationPropertySource> get(Environment environment) { Assert.isInstanceOf(ConfigurableEnvironment.class, environment); MutablePropertySources sources = ((ConfigurableEnvironment) environment) .getPropertySources(); ConfigurationPropertySourcesPropertySource attached = (ConfigurationPropertySourcesPropertySource) sources .get(ATTACHED_PROPERTY_SOURCE_NAME); if (attached == null) { return from(sources); } return attached.getSource(); }
Return a set of {@link ConfigurationPropertySource} instances that have previously been {@link #attach(Environment) attached} to the {@link Environment}. @param environment the source environment (must be an instance of {@link ConfigurableEnvironment}) @return an iterable set of configuration property sources @throws IllegalStateException if not configuration property sources have been attached
public static Iterable<ConfigurationPropertySource> from(PropertySource<?> source) { return Collections.singleton(SpringConfigurationPropertySource.from(source)); }
Return {@link Iterable} containing a single new {@link ConfigurationPropertySource} adapted from the given Spring {@link PropertySource}. @param source the Spring property source to adapt @return an {@link Iterable} containing a single newly adapted {@link SpringConfigurationPropertySource}
public String getType(TypeElement element, TypeMirror type) { if (type == null) { return null; } return type.accept(this.typeExtractor, createTypeDescriptor(element)); }
Return the type of the specified {@link TypeMirror} including all its generic information. @param element the {@link TypeElement} in which this {@code type} is declared @param type the type to handle @return a representation of the type including all its generic information
public TypeMirror extractElementType(TypeMirror type) { if (!this.env.getTypeUtils().isAssignable(type, this.collectionType)) { return null; } return getCollectionElementType(type); }
Extract the target element type from the specified container type or {@code null} if no element type was found. @param type a type, potentially wrapping an element type @return the element type or {@code null} if no specific type was found
public PrimitiveType getPrimitiveType(TypeMirror typeMirror) { if (getPrimitiveFor(typeMirror) != null) { return this.types.unboxedType(typeMirror); } return null; }
Return the {@link PrimitiveType} of the specified type or {@code null} if the type does not represent a valid wrapper type. @param typeMirror a type @return the primitive type or {@code null} if the type is not a wrapper type
public static List<String> getUrls(String path, ClassLoader classLoader) { if (classLoader == null) { classLoader = ClassUtils.getDefaultClassLoader(); } path = StringUtils.cleanPath(path); try { return getUrlsFromWildcardPath(path, classLoader); } catch (Exception ex) { throw new IllegalArgumentException( "Cannot create URL from path [" + path + "]", ex); } }
Return URLs from a given source path. Source paths can be simple file locations (/some/file.java) or wildcard patterns (/some/**). Additionally the prefixes "file:", "classpath:" and "classpath*:" can be used for specific path types. @param path the source path @param classLoader the class loader or {@code null} to use the default @return a list of URLs
protected HttpHandler getHttpHandler() { // Use bean names so that we don't consider the hierarchy String[] beanNames = getBeanFactory().getBeanNamesForType(HttpHandler.class); if (beanNames.length == 0) { throw new ApplicationContextException( "Unable to start ReactiveWebApplicationContext due to missing HttpHandler bean."); } if (beanNames.length > 1) { throw new ApplicationContextException( "Unable to start ReactiveWebApplicationContext due to multiple HttpHandler beans : " + StringUtils.arrayToCommaDelimitedString(beanNames)); } return getBeanFactory().getBean(beanNames[0], HttpHandler.class); }
Return the {@link HttpHandler} that should be used to process the reactive web server. By default this method searches for a suitable bean in the context itself. @return a {@link HttpHandler} (never {@code null}
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. @param healths the health instances to aggregate @return a map of details @since 1.3.1
public void repackage(File destination, Libraries libraries) throws IOException { repackage(destination, libraries, null); }
Repackage to the given destination so that it can be launched using ' {@literal java -jar}'. @param destination the destination file (may be the same as the source) @param libraries the libraries required to run the archive @throws IOException if the file cannot be repackaged
public void repackage(File destination, Libraries libraries, LaunchScript launchScript) throws IOException { if (destination == null || destination.isDirectory()) { throw new IllegalArgumentException("Invalid destination"); } if (libraries == null) { throw new IllegalArgumentException("Libraries must not be null"); } if (this.layout == null) { this.layout = getLayoutFactory().getLayout(this.source); } destination = destination.getAbsoluteFile(); File workingSource = this.source; if (alreadyRepackaged() && this.source.equals(destination)) { return; } if (this.source.equals(destination)) { workingSource = getBackupFile(); workingSource.delete(); renameFile(this.source, workingSource); } destination.delete(); try { try (JarFile jarFileSource = new JarFile(workingSource)) { repackage(jarFileSource, destination, libraries, launchScript); } } finally { if (!this.backupSource && !this.source.equals(workingSource)) { deleteFile(workingSource); } } }
Repackage to the given destination so that it can be launched using ' {@literal java -jar}'. @param destination the destination file (may be the same as the source) @param libraries the libraries required to run the archive @param launchScript an optional launch script prepended to the front of the jar @throws IOException if the file cannot be repackaged @since 1.3.0
public static Tag uri(HttpRequest request) { return Tag.of("uri", ensureLeadingSlash(stripUri(request.getURI().toString()))); }
Creates a {@code uri} {@code Tag} for the URI of the given {@code request}. @param request the request @return the uri tag
public static Tag clientName(HttpRequest request) { String host = request.getURI().getHost(); if (host == null) { host = "none"; } return Tag.of("clientName", host); }
Create a {@code clientName} {@code Tag} derived from the {@link URI#getHost host} of the {@link HttpRequest#getURI() URI} of the given {@code request}. @param request the request @return the clientName tag
public static Tag outcome(ClientHttpResponse response) { try { if (response != null) { HttpStatus statusCode = response.getStatusCode(); if (statusCode.is1xxInformational()) { return OUTCOME_INFORMATIONAL; } if (statusCode.is2xxSuccessful()) { return OUTCOME_SUCCESS; } if (statusCode.is3xxRedirection()) { return OUTCOME_REDIRECTION; } if (statusCode.is4xxClientError()) { return OUTCOME_CLIENT_ERROR; } if (statusCode.is5xxServerError()) { return OUTCOME_SERVER_ERROR; } } return OUTCOME_UNKNOWN; } catch (IOException | IllegalArgumentException ex) { return OUTCOME_UNKNOWN; } }
Creates an {@code outcome} {@code Tag} derived from the {@link ClientHttpResponse#getStatusCode() status} of the given {@code response}. @param response the response @return the outcome tag @since 2.2.0
public void applyToMvcViewResolver(Object viewResolver) { Assert.isInstanceOf(AbstractTemplateViewResolver.class, viewResolver, "ViewResolver is not an instance of AbstractTemplateViewResolver :" + viewResolver); AbstractTemplateViewResolver resolver = (AbstractTemplateViewResolver) viewResolver; resolver.setPrefix(getPrefix()); resolver.setSuffix(getSuffix()); resolver.setCache(isCache()); if (getContentType() != null) { resolver.setContentType(getContentType().toString()); } resolver.setViewNames(getViewNames()); resolver.setExposeRequestAttributes(isExposeRequestAttributes()); resolver.setAllowRequestOverride(isAllowRequestOverride()); resolver.setAllowSessionOverride(isAllowSessionOverride()); resolver.setExposeSessionAttributes(isExposeSessionAttributes()); resolver.setExposeSpringMacroHelpers(isExposeSpringMacroHelpers()); resolver.setRequestContextAttribute(getRequestContextAttribute()); // The resolver usually acts as a fallback resolver (e.g. like a // InternalResourceViewResolver) so it needs to have low precedence resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 5); }
Apply the given properties to a {@link AbstractTemplateViewResolver}. Use Object in signature to avoid runtime dependency on MVC, which means that the template engine can be used in a non-web application. @param viewResolver the resolver to apply the properties to.
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. @param listener the listener to register
public static boolean isSupportedType(EventListener listener) { for (Class<?> type : SUPPORTED_TYPES) { if (ClassUtils.isAssignableValue(type, listener)) { return true; } } return false; }
Returns {@code true} if the specified listener is one of the supported types. @param listener the listener to test @return if the listener is of a supported type
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. @return the port @see #setAddresses(String) @see #getPort()
public String determineAddresses() { if (CollectionUtils.isEmpty(this.parsedAddresses)) { return this.host + ":" + this.port; } List<String> addressStrings = new ArrayList<>(); for (Address parsedAddress : this.parsedAddresses) { addressStrings.add(parsedAddress.host + ":" + parsedAddress.port); } return StringUtils.collectionToCommaDelimitedString(addressStrings); }
Returns the comma-separated addresses or a single address ({@code host:port}) created from the configured host and port if no addresses have been set. @return the addresses
public String determineUsername() { if (CollectionUtils.isEmpty(this.parsedAddresses)) { return this.username; } Address address = this.parsedAddresses.get(0); return (address.username != null) ? address.username : this.username; }
If addresses have been set and the first address has a username it is returned. Otherwise returns the result of calling {@code getUsername()}. @return the username @see #setAddresses(String) @see #getUsername()
public String determinePassword() { if (CollectionUtils.isEmpty(this.parsedAddresses)) { return getPassword(); } Address address = this.parsedAddresses.get(0); return (address.password != null) ? address.password : getPassword(); }
If addresses have been set and the first address has a password it is returned. Otherwise returns the result of calling {@code getPassword()}. @return the password or {@code null} @see #setAddresses(String) @see #getPassword()
public String determineVirtualHost() { if (CollectionUtils.isEmpty(this.parsedAddresses)) { return getVirtualHost(); } Address address = this.parsedAddresses.get(0); return (address.virtualHost != null) ? address.virtualHost : getVirtualHost(); }
If addresses have been set and the first address has a virtual host it is returned. Otherwise returns the result of calling {@code getVirtualHost()}. @return the virtual host or {@code null} @see #setAddresses(String) @see #getVirtualHost()
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. @param statusOrder an ordered list of the status
public static Tag uri(HttpServletRequest request, HttpServletResponse response) { if (request != null) { String pattern = getMatchingPattern(request); if (pattern != null) { return Tag.of("uri", pattern); } if (response != null) { HttpStatus status = extractStatus(response); if (status != null) { if (status.is3xxRedirection()) { return URI_REDIRECTION; } if (status == HttpStatus.NOT_FOUND) { return URI_NOT_FOUND; } } } String pathInfo = getPathInfo(request); if (pathInfo.isEmpty()) { return URI_ROOT; } } return URI_UNKNOWN; }
Creates a {@code uri} tag based on the URI of the given {@code request}. Uses the {@link HandlerMapping#BEST_MATCHING_PATTERN_ATTRIBUTE} best matching pattern if available. Falling back to {@code REDIRECTION} for 3xx responses, {@code NOT_FOUND} for 404 responses, {@code root} for requests with no path info, and {@code UNKNOWN} for all other requests. @param request the request @param response the response @return the uri tag derived from the request
protected final ServletContextInitializer[] mergeInitializers( ServletContextInitializer... initializers) { List<ServletContextInitializer> mergedInitializers = new ArrayList<>(); mergedInitializers.add((servletContext) -> this.initParameters .forEach(servletContext::setInitParameter)); mergedInitializers.add(new SessionConfiguringInitializer(this.session)); mergedInitializers.addAll(Arrays.asList(initializers)); mergedInitializers.addAll(this.initializers); return mergedInitializers.toArray(new ServletContextInitializer[0]); }
Utility method that can be used by subclasses wishing to combine the specified {@link ServletContextInitializer} parameters with those defined in this instance. @param initializers the initializers to merge @return a complete set of merged initializers (with the specified parameters appearing first)
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. @return {@code true} if the servlet should be registered, otherwise {@code false}
public void setServerCustomizers( Collection<? extends NettyServerCustomizer> serverCustomizers) { Assert.notNull(serverCustomizers, "ServerCustomizers must not be null"); this.serverCustomizers = new ArrayList<>(serverCustomizers); }
Set {@link NettyServerCustomizer}s that should be applied to the Netty server builder. Calling this method will replace any existing customizers. @param serverCustomizers the customizers to set
public void addServerCustomizers(NettyServerCustomizer... serverCustomizers) { Assert.notNull(serverCustomizers, "ServerCustomizer must not be null"); this.serverCustomizers.addAll(Arrays.asList(serverCustomizers)); }
Add {@link NettyServerCustomizer}s that should applied while building the server. @param serverCustomizers the customizers to add
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>(); configureHeadlessProperty(); SpringApplicationRunListeners listeners = getRunListeners(args); listeners.starting(); try { ApplicationArguments applicationArguments = new DefaultApplicationArguments( args); ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); configureIgnoreBeanInfo(environment); Banner printedBanner = printBanner(environment); context = createApplicationContext(); exceptionReporters = getSpringFactoriesInstances( SpringBootExceptionReporter.class, new Class[] { ConfigurableApplicationContext.class }, context); prepareContext(context, environment, listeners, applicationArguments, printedBanner); refreshContext(context); afterRefresh(context, applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass) .logStarted(getApplicationLog(), stopWatch); } listeners.started(context); callRunners(context, applicationArguments); } catch (Throwable ex) { handleRunFailure(context, ex, exceptionReporters, listeners); throw new IllegalStateException(ex); } try { listeners.running(context); } catch (Throwable ex) { handleRunFailure(context, ex, exceptionReporters, null); throw new IllegalStateException(ex); } return context; }
Run the Spring application, creating and refreshing a new {@link ApplicationContext}. @param args the application arguments (usually passed from a Java main method) @return a running {@link ApplicationContext}
protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) { if (this.addConversionService) { ConversionService conversionService = ApplicationConversionService .getSharedInstance(); environment.setConversionService( (ConfigurableConversionService) conversionService); } configurePropertySources(environment, args); configureProfiles(environment, args); }
Template method delegating to {@link #configurePropertySources(ConfigurableEnvironment, String[])} and {@link #configureProfiles(ConfigurableEnvironment, String[])} in that order. Override this method for complete control over Environment customization, or one of the above for fine-grained control over property sources or profiles, respectively. @param environment this application's environment @param args arguments passed to the {@code run} method @see #configureProfiles(ConfigurableEnvironment, String[]) @see #configurePropertySources(ConfigurableEnvironment, String[])
protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) { MutablePropertySources sources = environment.getPropertySources(); if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) { sources.addLast( new MapPropertySource("defaultProperties", this.defaultProperties)); } if (this.addCommandLineProperties && args.length > 0) { String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME; if (sources.contains(name)) { PropertySource<?> source = sources.get(name); CompositePropertySource composite = new CompositePropertySource(name); composite.addPropertySource(new SimpleCommandLinePropertySource( "springApplicationCommandLineArgs", args)); composite.addPropertySource(source); sources.replace(name, composite); } else { sources.addFirst(new SimpleCommandLinePropertySource(args)); } } }
Add, remove or re-order any {@link PropertySource}s in this application's environment. @param environment this application's environment @param args arguments passed to the {@code run} method @see #configureEnvironment(ConfigurableEnvironment, String[])
protected void configureProfiles(ConfigurableEnvironment environment, String[] args) { environment.getActiveProfiles(); // ensure they are initialized // But these ones should go first (last wins in a property key clash) Set<String> profiles = new LinkedHashSet<>(this.additionalProfiles); profiles.addAll(Arrays.asList(environment.getActiveProfiles())); environment.setActiveProfiles(StringUtils.toStringArray(profiles)); }
Configure which profiles are active (or active by default) for this application environment. Additional profiles may be activated during configuration file processing via the {@code spring.profiles.active} property. @param environment this application's environment @param args arguments passed to the {@code run} method @see #configureEnvironment(ConfigurableEnvironment, String[]) @see org.springframework.boot.context.config.ConfigFileApplicationListener
protected void bindToSpringApplication(ConfigurableEnvironment environment) { try { Binder.get(environment).bind("spring.main", Bindable.ofInstance(this)); } catch (Exception ex) { throw new IllegalStateException("Cannot bind to SpringApplication", ex); } }
Bind the environment to the {@link SpringApplication}. @param environment the environment to bind
protected ConfigurableApplicationContext createApplicationContext() { Class<?> contextClass = this.applicationContextClass; if (contextClass == null) { try { switch (this.webApplicationType) { case SERVLET: contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS); break; case REACTIVE: contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS); break; default: contextClass = Class.forName(DEFAULT_CONTEXT_CLASS); } } catch (ClassNotFoundException ex) { throw new IllegalStateException( "Unable create a default ApplicationContext, " + "please specify an ApplicationContextClass", ex); } } return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass); }
Strategy method used to create the {@link ApplicationContext}. By default this method will respect any explicitly set application context or application context class before falling back to a suitable default. @return the application context (not yet refreshed) @see #setApplicationContextClass(Class)
protected void postProcessApplicationContext(ConfigurableApplicationContext context) { if (this.beanNameGenerator != null) { context.getBeanFactory().registerSingleton( AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, this.beanNameGenerator); } if (this.resourceLoader != null) { if (context instanceof GenericApplicationContext) { ((GenericApplicationContext) context) .setResourceLoader(this.resourceLoader); } if (context instanceof DefaultResourceLoader) { ((DefaultResourceLoader) context) .setClassLoader(this.resourceLoader.getClassLoader()); } } if (this.addConversionService) { context.getBeanFactory().setConversionService( ApplicationConversionService.getSharedInstance()); } }
Apply any relevant post processing the {@link ApplicationContext}. Subclasses can apply additional processing as required. @param context the application context
@SuppressWarnings({ "rawtypes", "unchecked" }) protected void applyInitializers(ConfigurableApplicationContext context) { for (ApplicationContextInitializer initializer : getInitializers()) { Class<?> requiredType = GenericTypeResolver.resolveTypeArgument( initializer.getClass(), ApplicationContextInitializer.class); Assert.isInstanceOf(requiredType, context, "Unable to call initializer."); initializer.initialize(context); } }
Apply any {@link ApplicationContextInitializer}s to the context before it is refreshed. @param context the configured ApplicationContext (not refreshed yet) @see ConfigurableApplicationContext#refresh()
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. @param context the application context
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. @param context the context to load beans into @param sources the sources to load
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. @param context the application context @return the BeanDefinitionRegistry if it can be determined
protected void refresh(ApplicationContext applicationContext) { Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext); ((AbstractApplicationContext) applicationContext).refresh(); }
Refresh the underlying {@link ApplicationContext}. @param applicationContext the application context to refresh
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. @param exception the exception that was logged
public void setDefaultProperties(Properties defaultProperties) { this.defaultProperties = new HashMap<>(); for (Object key : Collections.list(defaultProperties.propertyNames())) { this.defaultProperties.put((String) key, defaultProperties.get(key)); } }
Convenient alternative to {@link #setDefaultProperties(Map)}. @param defaultProperties some {@link Properties}
public void setSources(Set<String> sources) { Assert.notNull(sources, "Sources must not be null"); this.sources = new LinkedHashSet<>(sources); }
Set additional sources that will be used to create an ApplicationContext. A source can be: a class name, package name, or an XML resource location. <p> Sources set here will be used in addition to any primary sources set in the constructor. @param sources the application sources to set @see #SpringApplication(Class...) @see #getAllSources()
public Set<Object> getAllSources() { Set<Object> allSources = new LinkedHashSet<>(); if (!CollectionUtils.isEmpty(this.primarySources)) { allSources.addAll(this.primarySources); } if (!CollectionUtils.isEmpty(this.sources)) { allSources.addAll(this.sources); } return Collections.unmodifiableSet(allSources); }
Return an immutable set of all the sources that will be added to an ApplicationContext when {@link #run(String...)} is called. This method combines any primary sources specified in the constructor with any additional ones that have been {@link #setSources(Set) explicitly set}. @return an immutable set of all sources
public void setApplicationContextClass( Class<? extends ConfigurableApplicationContext> applicationContextClass) { this.applicationContextClass = applicationContextClass; this.webApplicationType = WebApplicationType .deduceFromApplicationContext(applicationContextClass); }
Sets the type of Spring {@link ApplicationContext} that will be created. If not specified defaults to {@link #DEFAULT_SERVLET_WEB_CONTEXT_CLASS} for web based applications or {@link AnnotationConfigApplicationContext} for non web based applications. @param applicationContextClass the context class to set
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) { return run(new Class<?>[] { primarySource }, args); }
Static helper that can be used to run a {@link SpringApplication} from the specified source using default settings. @param primarySource the primary source to load @param args the application arguments (usually passed from a Java main method) @return the running {@link ApplicationContext}
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) { return new SpringApplication(primarySources).run(args); }
Static helper that can be used to run a {@link SpringApplication} from the specified sources using default settings and user supplied arguments. @param primarySources the primary sources to load @param args the application arguments (usually passed from a Java main method) @return the running {@link ApplicationContext}
public static int exit(ApplicationContext context, ExitCodeGenerator... exitCodeGenerators) { Assert.notNull(context, "Context must not be null"); int exitCode = 0; try { try { ExitCodeGenerators generators = new ExitCodeGenerators(); Collection<ExitCodeGenerator> beans = context .getBeansOfType(ExitCodeGenerator.class).values(); generators.addAll(exitCodeGenerators); generators.addAll(beans); exitCode = generators.getExitCode(); if (exitCode != 0) { context.publishEvent(new ExitCodeEvent(context, exitCode)); } } finally { close(context); } } catch (Exception ex) { ex.printStackTrace(); exitCode = (exitCode != 0) ? exitCode : 1; } return exitCode; }
Static helper that can be used to exit a {@link SpringApplication} and obtain a code indicating success (0) or otherwise. Does not throw exceptions but should print stack traces of any encountered. Applies the specified {@link ExitCodeGenerator} in addition to any Spring beans that implement {@link ExitCodeGenerator}. In the case of multiple exit codes the highest value will be used (or if all values are negative, the lowest value will be used) @param context the context to close if possible @param exitCodeGenerators exist code generators @return the outcome (0 if successful)
@Bean public TomcatServletWebServerFactory servletWebServerFactory() { return new TomcatServletWebServerFactory() { @Override protected void prepareContext(Host host, ServletContextInitializer[] initializers) { super.prepareContext(host, initializers); StandardContext child = new StandardContext(); child.addLifecycleListener(new Tomcat.FixContextListener()); child.setPath("/cloudfoundryapplication"); ServletContainerInitializer initializer = getServletContextInitializer( getContextPath()); child.addServletContainerInitializer(initializer, Collections.emptySet()); child.setCrossContext(true); host.addChild(child); } }; }
tag::configuration[]
public CompositeReactiveHealthIndicator timeoutStrategy(long timeout, Health timeoutHealth) { this.timeout = timeout; this.timeoutHealth = (timeoutHealth != null) ? timeoutHealth : Health.unknown().build(); return this; }
Specify an alternative timeout {@link Health} if a {@link HealthIndicator} failed to reply after specified {@code timeout}. @param timeout number of milliseconds to wait before using the {@code timeoutHealth} @param timeoutHealth the {@link Health} to use if an health indicator reached the {@code timeout} @return this instance
public ConditionMessage append(String message) { if (!StringUtils.hasLength(message)) { return this; } if (!StringUtils.hasLength(this.message)) { return new ConditionMessage(message); } return new ConditionMessage(this.message + " " + message); }
Return a new {@link ConditionMessage} based on the instance and an appended message. @param message the message to append @return a new {@link ConditionMessage} instance
public Builder andCondition(Class<? extends Annotation> condition, Object... details) { Assert.notNull(condition, "Condition must not be null"); return andCondition("@" + ClassUtils.getShortName(condition), details); }
Return a new builder to construct a new {@link ConditionMessage} based on the instance and a new condition outcome. @param condition the condition @param details details of the condition @return a {@link Builder} builder @see #andCondition(String, Object...) @see #forCondition(Class, Object...)
public Builder andCondition(String condition, Object... details) { Assert.notNull(condition, "Condition must not be null"); String detail = StringUtils.arrayToDelimitedString(details, " "); if (StringUtils.hasLength(detail)) { return new Builder(condition + " " + detail); } return new Builder(condition); }
Return a new builder to construct a new {@link ConditionMessage} based on the instance and a new condition outcome. @param condition the condition @param details details of the condition @return a {@link Builder} builder @see #andCondition(Class, Object...) @see #forCondition(String, Object...)
public static ConditionMessage of(String message, Object... args) { if (ObjectUtils.isEmpty(args)) { return new ConditionMessage(message); } return new ConditionMessage(String.format(message, args)); }
Factory method to create a new {@link ConditionMessage} with a specific message. @param message the source message (may be a format string if {@code args} are specified) @param args format arguments for the message @return a new {@link ConditionMessage} instance
public static ConditionMessage of(Collection<? extends ConditionMessage> messages) { ConditionMessage result = new ConditionMessage(); if (messages != null) { for (ConditionMessage message : messages) { result = new ConditionMessage(result, message.toString()); } } return result; }
Factory method to create a new {@link ConditionMessage} comprised of the specified messages. @param messages the source messages (may be {@code null}) @return a new {@link ConditionMessage} instance
public static Builder forCondition(Class<? extends Annotation> condition, Object... details) { return new ConditionMessage().andCondition(condition, details); }
Factory method for a builder to construct a new {@link ConditionMessage} for a condition. @param condition the condition @param details details of the condition @return a {@link Builder} builder @see #forCondition(String, Object...) @see #andCondition(String, Object...)
public static Builder forCondition(String condition, Object... details) { return new ConditionMessage().andCondition(condition, details); }
Factory method for a builder to construct a new {@link ConditionMessage} for a condition. @param condition the condition @param details details of the condition @return a {@link Builder} builder @see #forCondition(Class, Object...) @see #andCondition(String, Object...)
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. @param extension the file extension (excluding '.') @param mimeType the mime type to map @return any previous mapping or {@code null}
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. @param extension the file extension (excluding '.') @return a mime mapping or {@code null}
public String remove(String extension) { Mapping previous = this.map.remove(extension); return (previous != null) ? previous.getMimeType() : null; }
Remove an existing mapping. @param extension the file extension (excluding '.') @return the removed mime mapping or {@code null} if no item was removed
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. @param beanNameGenerator the bean name generator
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. @param resourceLoader the resource loader
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. @param environment the environment
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. @param map the source map
public void put(Object name, Object value) { this.source.put((name != null) ? name.toString() : null, value); }
Add an individual entry. @param name the name @param value the value
public static boolean hasAtLeastOneAnnotation(ClassNode node, String... annotations) { if (hasAtLeastOneAnnotation((AnnotatedNode) node, annotations)) { return true; } for (MethodNode method : node.getMethods()) { if (hasAtLeastOneAnnotation(method, annotations)) { return true; } } return false; }
Determine if a {@link ClassNode} has one or more of the specified annotations on the class or any of its methods. N.B. the type names are not normally fully qualified. @param node the class to examine @param annotations the annotations to look for @return {@code true} if at least one of the annotations is found, otherwise {@code false}