code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
protected final void bindIndexed(ConfigurationPropertyName name, Bindable<?> target, AggregateElementBinder elementBinder, ResolvableType aggregateType, ResolvableType elementType, IndexedCollectionSupplier result) { for (ConfigurationPropertySource source : getContext().getSources()) { bindIndexed(source, name, target, elementBinder, result, aggregateType, elementType); if (result.wasSupplied() && result.get() != null) { return; } } }
Bind indexed elements to the supplied collection. @param name the name of the property to bind @param target the target bindable @param elementBinder the binder to use for elements @param aggregateType the aggregate type, may be a collection or an array @param elementType the element type @param result the destination for results
public void setServletRegistrationBeans( Collection<? extends ServletRegistrationBean<?>> servletRegistrationBeans) { Assert.notNull(servletRegistrationBeans, "ServletRegistrationBeans must not be null"); this.servletRegistrationBeans = new LinkedHashSet<>(servletRegistrationBeans); }
Set {@link ServletRegistrationBean}s that the filter will be registered against. @param servletRegistrationBeans the Servlet registration beans
public void addServletRegistrationBeans( ServletRegistrationBean<?>... servletRegistrationBeans) { Assert.notNull(servletRegistrationBeans, "ServletRegistrationBeans must not be null"); Collections.addAll(this.servletRegistrationBeans, servletRegistrationBeans); }
Add {@link ServletRegistrationBean}s for the filter. @param servletRegistrationBeans the servlet registration beans to add @see #setServletRegistrationBeans
public void setServletNames(Collection<String> servletNames) { Assert.notNull(servletNames, "ServletNames must not be null"); this.servletNames = new LinkedHashSet<>(servletNames); }
Set servlet names that the filter will be registered against. This will replace any previously specified servlet names. @param servletNames the servlet names @see #setServletRegistrationBeans @see #setUrlPatterns
public void addServletNames(String... servletNames) { Assert.notNull(servletNames, "ServletNames must not be null"); this.servletNames.addAll(Arrays.asList(servletNames)); }
Add servlet names for the filter. @param servletNames the servlet names to add
public void setUrlPatterns(Collection<String> urlPatterns) { Assert.notNull(urlPatterns, "UrlPatterns must not be null"); this.urlPatterns = new LinkedHashSet<>(urlPatterns); }
Set the URL patterns that the filter will be registered against. This will replace any previously specified URL patterns. @param urlPatterns the URL patterns @see #setServletRegistrationBeans @see #setServletNames
public void addUrlPatterns(String... urlPatterns) { Assert.notNull(urlPatterns, "UrlPatterns must not be null"); Collections.addAll(this.urlPatterns, urlPatterns); }
Add URL patterns, as defined in the Servlet specification, that the filter will be registered against. @param urlPatterns the URL patterns
public void setDispatcherTypes(DispatcherType first, DispatcherType... rest) { this.dispatcherTypes = EnumSet.of(first, rest); }
Convenience method to {@link #setDispatcherTypes(EnumSet) set dispatcher types} using the specified elements. @param first the first dispatcher type @param rest additional dispatcher types
@Override protected void configure(FilterRegistration.Dynamic registration) { super.configure(registration); EnumSet<DispatcherType> dispatcherTypes = this.dispatcherTypes; if (dispatcherTypes == null) { dispatcherTypes = EnumSet.of(DispatcherType.REQUEST); } Set<String> servletNames = new LinkedHashSet<>(); for (ServletRegistrationBean<?> servletRegistrationBean : this.servletRegistrationBeans) { servletNames.add(servletRegistrationBean.getServletName()); } servletNames.addAll(this.servletNames); if (servletNames.isEmpty() && this.urlPatterns.isEmpty()) { registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, DEFAULT_URL_MAPPINGS); } else { if (!servletNames.isEmpty()) { registration.addMappingForServletNames(dispatcherTypes, this.matchAfter, StringUtils.toStringArray(servletNames)); } if (!this.urlPatterns.isEmpty()) { registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, StringUtils.toStringArray(this.urlPatterns)); } } }
Configure registration settings. Subclasses can override this method to perform additional configuration if required. @param registration the registration
public DependencyCustomizer ifAnyMissingClasses(String... classNames) { return new DependencyCustomizer(this) { @Override protected boolean canAdd() { for (String className : classNames) { try { DependencyCustomizer.this.loader.loadClass(className); } catch (Exception ex) { return true; } } return false; } }; }
Create a nested {@link DependencyCustomizer} that only applies if any of the specified class names are not on the class path. @param classNames the class names to test @return a nested {@link DependencyCustomizer}
public DependencyCustomizer ifAllMissingClasses(String... classNames) { return new DependencyCustomizer(this) { @Override protected boolean canAdd() { for (String className : classNames) { try { DependencyCustomizer.this.loader.loadClass(className); return false; } catch (Exception ex) { // swallow exception and continue } } return DependencyCustomizer.this.canAdd(); } }; }
Create a nested {@link DependencyCustomizer} that only applies if all of the specified class names are not on the class path. @param classNames the class names to test @return a nested {@link DependencyCustomizer}
public DependencyCustomizer ifAllResourcesPresent(String... paths) { return new DependencyCustomizer(this) { @Override protected boolean canAdd() { for (String path : paths) { try { if (DependencyCustomizer.this.loader.getResource(path) == null) { return false; } return true; } catch (Exception ex) { // swallow exception and continue } } return DependencyCustomizer.this.canAdd(); } }; }
Create a nested {@link DependencyCustomizer} that only applies if the specified paths are on the class path. @param paths the paths to test @return a nested {@link DependencyCustomizer}
public DependencyCustomizer add(String... modules) { for (String module : modules) { add(module, null, null, true); } return this; }
Add dependencies and all of their dependencies. The group ID and version of the dependencies are resolved from the modules using the customizer's {@link ArtifactCoordinatesResolver}. @param modules the module IDs @return this {@link DependencyCustomizer} for continued use
public DependencyCustomizer add(String module, boolean transitive) { return add(module, null, null, transitive); }
Add a single dependency and, optionally, all of its dependencies. The group ID and version of the dependency are resolved from the module using the customizer's {@link ArtifactCoordinatesResolver}. @param module the module ID @param transitive {@code true} if the transitive dependencies should also be added, otherwise {@code false} @return this {@link DependencyCustomizer} for continued use
public DependencyCustomizer add(String module, String classifier, String type, boolean transitive) { if (canAdd()) { ArtifactCoordinatesResolver artifactCoordinatesResolver = this.dependencyResolutionContext .getArtifactCoordinatesResolver(); this.classNode.addAnnotation( createGrabAnnotation(artifactCoordinatesResolver.getGroupId(module), artifactCoordinatesResolver.getArtifactId(module), artifactCoordinatesResolver.getVersion(module), classifier, type, transitive)); } return this; }
Add a single dependency with the specified classifier and type and, optionally, all of its dependencies. The group ID and version of the dependency are resolved from the module by using the customizer's {@link ArtifactCoordinatesResolver}. @param module the module ID @param classifier the classifier, may be {@code null} @param type the type, may be {@code null} @param transitive {@code true} if the transitive dependencies should also be added, otherwise {@code false} @return this {@link DependencyCustomizer} for continued use
public ReactiveHealthIndicatorRegistry createReactiveHealthIndicatorRegistry( Map<String, ReactiveHealthIndicator> reactiveHealthIndicators, Map<String, HealthIndicator> healthIndicators) { Assert.notNull(reactiveHealthIndicators, "ReactiveHealthIndicators must not be null"); return initialize(new DefaultReactiveHealthIndicatorRegistry(), reactiveHealthIndicators, healthIndicators); }
Create a {@link ReactiveHealthIndicatorRegistry} based on the specified health indicators. Each {@link HealthIndicator} are wrapped to a {@link HealthIndicatorReactiveAdapter}. If two instances share the same name, the reactive variant takes precedence. @param reactiveHealthIndicators the {@link ReactiveHealthIndicator} instances mapped by name @param healthIndicators the {@link HealthIndicator} instances mapped by name if any. @return a {@link ReactiveHealthIndicator} that delegates to the specified {@code reactiveHealthIndicators}.
public RandomAccessData parse(RandomAccessData data, boolean skipPrefixBytes) throws IOException { CentralDirectoryEndRecord endRecord = new CentralDirectoryEndRecord(data); if (skipPrefixBytes) { data = getArchiveData(endRecord, data); } RandomAccessData centralDirectoryData = endRecord.getCentralDirectory(data); visitStart(endRecord, centralDirectoryData); parseEntries(endRecord, centralDirectoryData); visitEnd(); return data; }
Parse the source data, triggering {@link CentralDirectoryVisitor visitors}. @param data the source data @param skipPrefixBytes if prefix bytes should be skipped @return the actual archive data without any prefix bytes @throws IOException on error
protected final <V> V get(Function<T, V> getter, Supplier<V> fallback) { V value = getter.apply(this.properties); return (value != null) ? value : fallback.get(); }
Get the value from the properties or use a fallback from the {@code defaults}. @param getter the getter for the properties @param fallback the fallback method, usually super interface method reference @param <V> the value type @return the property or fallback value
public File getDir(String subDir) { File dir = new File(getDir(), subDir); dir.mkdirs(); return dir; }
Return a sub-directory of the application temp. @param subDir the sub-directory name @return a sub-directory
public File getDir() { if (this.dir == null) { synchronized (this) { byte[] hash = generateHash(this.sourceClass); this.dir = new File(getTempDirectory(), toHexString(hash)); this.dir.mkdirs(); Assert.state(this.dir.exists(), () -> "Unable to create temp directory " + this.dir); } } return this.dir; }
Return the directory to be used for application specific temp files. @return the application temp directory
protected Map<String, Object> generateContent() { Map<String, Object> content = extractContent(toPropertySource()); postProcessContent(content); return content; }
Extract the content to contribute to the info endpoint. @return the content to expose @see #extractContent(PropertySource) @see #postProcessContent(Map)
protected Map<String, Object> extractContent(PropertySource<?> propertySource) { return new Binder(ConfigurationPropertySources.from(propertySource)) .bind("", STRING_OBJECT_MAP).orElseGet(LinkedHashMap::new); }
Extract the raw content based on the specified {@link PropertySource}. @param propertySource the property source to use @return the raw content
protected void copyIfSet(Properties target, String key) { String value = this.properties.get(key); if (StringUtils.hasText(value)) { target.put(key, value); } }
Copy the specified key to the target {@link Properties} if it is set. @param target the target properties to update @param key the key
protected void replaceValue(Map<String, Object> content, String key, Object value) { if (content.containsKey(key) && value != null) { content.put(key, value); } }
Replace the {@code value} for the specified key if the value is not {@code null}. @param content the content to expose @param key the property to replace @param value the new value
@SuppressWarnings("unchecked") protected Map<String, Object> getNestedMap(Map<String, Object> map, String key) { Object value = map.get(key); if (value == null) { return Collections.emptyMap(); } return (Map<String, Object>) value; }
Return the nested map with the specified key or empty map if the specified map contains no mapping for the key. @param map the content @param key the key of a nested map @return the nested map
@ReadOperation public Health healthForComponent(@Selector String component) { HealthIndicator indicator = getNestedHealthIndicator(this.healthIndicator, component); return (indicator != null) ? indicator.health() : null; }
Return the {@link Health} of a particular component or {@code null} if such component does not exist. @param component the name of a particular {@link HealthIndicator} @return the {@link Health} for the component or {@code null}
@ReadOperation public Health healthForComponentInstance(@Selector String component, @Selector String instance) { HealthIndicator indicator = getNestedHealthIndicator(this.healthIndicator, component); HealthIndicator nestedIndicator = getNestedHealthIndicator(indicator, instance); return (nestedIndicator != null) ? nestedIndicator.health() : null; }
Return the {@link Health} of a particular {@code instance} managed by the specified {@code component} or {@code null} if that particular component is not a {@link CompositeHealthIndicator} or if such instance does not exist. @param component the name of a particular {@link CompositeHealthIndicator} @param instance the name of an instance managed by that component @return the {@link Health} for the component instance of {@code null}
public static MeterValue valueOf(String value) { if (isNumber(value)) { return new MeterValue(Long.parseLong(value)); } return new MeterValue(DurationStyle.detectAndParse(value)); }
Return a new {@link MeterValue} instance for the given String value. The value may contain a simple number, or a {@link DurationStyle duration style string}. @param value the source value @return a {@link MeterValue} instance
public static <C, A> Callback<C, A> callback(Class<C> callbackType, C callbackInstance, A argument, Object... additionalArguments) { Assert.notNull(callbackType, "CallbackType must not be null"); Assert.notNull(callbackInstance, "CallbackInstance must not be null"); return new Callback<>(callbackType, callbackInstance, argument, additionalArguments); }
Start a call to a single callback instance, dealing with common generic type concerns and exceptions. @param callbackType the callback type (a {@link FunctionalInterface functional interface}) @param callbackInstance the callback instance (may be a lambda) @param argument the primary argument passed to the callback @param additionalArguments any additional arguments passed to the callback @param <C> the callback type @param <A> the primary argument type @return a {@link Callback} instance that can be invoked.
public static <C, A> Callbacks<C, A> callbacks(Class<C> callbackType, Collection<? extends C> callbackInstances, A argument, Object... additionalArguments) { Assert.notNull(callbackType, "CallbackType must not be null"); Assert.notNull(callbackInstances, "CallbackInstances must not be null"); return new Callbacks<>(callbackType, callbackInstances, argument, additionalArguments); }
Start a call to callback instances, dealing with common generic type concerns and exceptions. @param callbackType the callback type (a {@link FunctionalInterface functional interface}) @param callbackInstances the callback instances (elements may be lambdas) @param argument the primary argument passed to the callbacks @param additionalArguments any additional arguments passed to the callbacks @param <C> the callback type @param <A> the primary argument type @return a {@link Callbacks} instance that can be invoked.
public <R> Stream<R> invokeAnd(Function<C, R> invoker) { Function<C, InvocationResult<R>> mapper = (callbackInstance) -> invoke( callbackInstance, () -> invoker.apply(callbackInstance)); return this.callbackInstances.stream().map(mapper) .filter(InvocationResult::hasResult).map(InvocationResult::get); }
Invoke the callback instances where the callback method returns a result. @param invoker the invoker used to invoke the callback @param <R> the result type @return the results of the invocation (may be an empty stream if no callbacks could be called)
public int start() throws IOException { synchronized (this.monitor) { Assert.state(!isStarted(), "Server already started"); logger.debug("Starting live reload server on port " + this.port); this.serverSocket = new ServerSocket(this.port); int localPort = this.serverSocket.getLocalPort(); this.listenThread = this.threadFactory.newThread(this::acceptConnections); this.listenThread.setDaemon(true); this.listenThread.setName("Live Reload Server"); this.listenThread.start(); return localPort; } }
Start the livereload server and accept incoming connections. @return the port on which the server is listening @throws IOException in case of I/O errors
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. @throws IOException in case of I/O errors
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.
protected Connection createConnection(Socket socket, InputStream inputStream, OutputStream outputStream) throws IOException { return new Connection(socket, inputStream, outputStream); }
Factory method used to create the {@link Connection}. @param socket the source socket @param inputStream the socket input stream @param outputStream the socket output stream @return a connection @throws IOException in case of I/O errors
public ConfigurableApplicationContext run(String... args) { if (this.running.get()) { // If already created we just return the existing context return this.context; } configureAsChildIfNecessary(args); if (this.running.compareAndSet(false, true)) { synchronized (this.running) { // If not already running copy the sources over and then run. this.context = build().run(args); } } return this.context; }
Create an application context (and its parent if specified) with the command line args provided. The parent is run first with the same arguments if has not yet been started. @param args the command line arguments @return an application context created from the current state
public SpringApplication build(String... args) { configureAsChildIfNecessary(args); this.application.addPrimarySources(this.sources); return this.application; }
Returns a fully configured {@link SpringApplication} that is ready to run. Any parent that has been configured will be run with the given {@code args}. @param args the parent's args @return the fully configured {@link SpringApplication}.
public SpringApplicationBuilder child(Class<?>... sources) { SpringApplicationBuilder child = new SpringApplicationBuilder(); child.sources(sources); // Copy environment stuff from parent to child child.properties(this.defaultProperties).environment(this.environment) .additionalProfiles(this.additionalProfiles); child.parent = this; // It's not possible if embedded web server are enabled to support web contexts as // parents because the servlets cannot be initialized at the right point in // lifecycle. web(WebApplicationType.NONE); // Probably not interested in multiple banners bannerMode(Banner.Mode.OFF); // Make sure sources get copied over 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. @param sources the sources for the application (Spring configuration) @return the child application builder
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. @param sources the sources for the application (Spring configuration) @return the parent builder
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. @param parent the parent context @return the current builder (not the parent)
public SpringApplicationBuilder sibling(Class<?>[] sources, String... args) { return runAndExtractParent(args).child(sources); }
Create a sibling application (one with the same parent). A side effect of calling this method is that the current application (and its parent) are started if they are not already running. @param sources the sources for the application (Spring configuration) @param args the command line arguments to use when starting the current app and its parent @return the new sibling builder
public SpringApplicationBuilder sources(Class<?>... sources) { this.sources.addAll(new LinkedHashSet<>(Arrays.asList(sources))); return this; }
Add more sources (configuration classes and components) to this application. @param sources the sources to add @return the current builder
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. @param defaults the default properties @return the current builder @see SpringApplicationBuilder#properties(String...)
public SpringApplicationBuilder profiles(String... profiles) { this.additionalProfiles.addAll(Arrays.asList(profiles)); this.application.setAdditionalProfiles( StringUtils.toStringArray(this.additionalProfiles)); return this; }
Add to the active Spring profiles for this app (and its parent and children). @param profiles the profiles to add. @return the current builder
public static ConversionService getSharedInstance() { ApplicationConversionService sharedInstance = ApplicationConversionService.sharedInstance; if (sharedInstance == null) { synchronized (ApplicationConversionService.class) { sharedInstance = ApplicationConversionService.sharedInstance; if (sharedInstance == null) { sharedInstance = new ApplicationConversionService(); ApplicationConversionService.sharedInstance = sharedInstance; } } } return sharedInstance; }
Return a shared default application {@code ConversionService} instance, lazily building it once needed. <p> Note: This method actually returns an {@link ApplicationConversionService} instance. However, the {@code ConversionService} signature has been preserved for binary compatibility. @return the shared {@code ApplicationConversionService} instance (never {@code null})
public static void configure(FormatterRegistry registry) { DefaultConversionService.addDefaultConverters(registry); DefaultFormattingConversionService.addDefaultFormatters(registry); addApplicationFormatters(registry); addApplicationConverters(registry); }
Configure the given {@link FormatterRegistry} with formatters and converters appropriate for most Spring Boot applications. @param registry the registry of converters to add to (must also be castable to ConversionService, e.g. being a {@link ConfigurableConversionService}) @throws ClassCastException if the given FormatterRegistry could not be cast to a ConversionService
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. @param registry the registry of converters to add to (must also be castable to ConversionService, e.g. being a {@link ConfigurableConversionService}) @throws ClassCastException if the given ConverterRegistry could not be cast to a ConversionService
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. @param registry the registry of converters to add to (must also be castable to ConversionService, e.g. being a {@link ConfigurableConversionService}) @throws ClassCastException if the given ConverterRegistry could not be cast to a ConversionService
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. @param registry the service to register default formatters with
public void setServerCustomizers( Collection<? extends ServerRSocketFactoryCustomizer> serverCustomizers) { Assert.notNull(serverCustomizers, "ServerCustomizers must not be null"); this.serverCustomizers = new ArrayList<>(serverCustomizers); }
Set {@link ServerRSocketFactoryCustomizer}s that should be applied to the RSocket server builder. Calling this method will replace any existing customizers. @param serverCustomizers the customizers to set
public void addServerCustomizers( ServerRSocketFactoryCustomizer... serverCustomizers) { Assert.notNull(serverCustomizers, "ServerCustomizer must not be null"); this.serverCustomizers.addAll(Arrays.asList(serverCustomizers)); }
Add {@link ServerRSocketFactoryCustomizer}s that should applied while building the server. @param serverCustomizers the customizers to add
public MultipartConfigElement createMultipartConfig() { long maxFileSizeBytes = convertToBytes(this.maxFileSize, -1); long maxRequestSizeBytes = convertToBytes(this.maxRequestSize, -1); long fileSizeThresholdBytes = convertToBytes(this.fileSizeThreshold, 0); return new MultipartConfigElement(this.location, maxFileSizeBytes, maxRequestSizeBytes, (int) fileSizeThresholdBytes); }
Create a new {@link MultipartConfigElement} instance. @return the multipart config element
private long convertToBytes(DataSize size, int defaultValue) { if (size != null && !size.isNegative()) { return size.toBytes(); } return defaultValue; }
Return the amount of bytes from the specified {@link DataSize size}. If the size is {@code null} or negative, returns {@code defaultValue}. @param size the data size to handle @param defaultValue the default value if the size is {@code null} or negative @return the amount of bytes to use
public DataSourceBuilder<?> initializeDataSourceBuilder() { return DataSourceBuilder.create(getClassLoader()).type(getType()) .driverClassName(determineDriverClassName()).url(determineUrl()) .username(determineUsername()).password(determinePassword()); }
Initialize a {@link DataSourceBuilder} with the state of this instance. @return a {@link DataSourceBuilder} initialized with the customizations defined on this instance
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. @return the driver to use @since 1.4.0
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. @return the url to use @since 1.4.0
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. @return the database name to use or {@code null} @since 2.0.0
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. @return the username to use @since 1.4.0
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. @return the password to use @since 1.4.0
@SuppressWarnings({ "unchecked" }) protected final <D> D nullSafeValue(JsonNode jsonNode, Class<D> type) { Assert.notNull(type, "Type must not be null"); if (jsonNode == null) { return null; } if (type == String.class) { return (D) jsonNode.textValue(); } if (type == Boolean.class) { return (D) Boolean.valueOf(jsonNode.booleanValue()); } if (type == Long.class) { return (D) Long.valueOf(jsonNode.longValue()); } if (type == Integer.class) { return (D) Integer.valueOf(jsonNode.intValue()); } if (type == Short.class) { return (D) Short.valueOf(jsonNode.shortValue()); } if (type == Double.class) { return (D) Double.valueOf(jsonNode.doubleValue()); } if (type == Float.class) { return (D) Float.valueOf(jsonNode.floatValue()); } if (type == BigDecimal.class) { return (D) jsonNode.decimalValue(); } if (type == BigInteger.class) { return (D) jsonNode.bigIntegerValue(); } throw new IllegalArgumentException("Unsupported value type " + type.getName()); }
Helper method to extract a value from the given {@code jsonNode} or return {@code null} when the node itself is {@code null}. @param jsonNode the source node (may be {@code null}) @param type the data type. May be {@link String}, {@link Boolean}, {@link Long}, {@link Integer}, {@link Short}, {@link Double}, {@link Float}, {@link BigDecimal} or {@link BigInteger}. @param <D> the data type requested @return the node value or {@code null}
protected final JsonNode getRequiredNode(JsonNode tree, String fieldName) { Assert.notNull(tree, "Tree must not be null"); JsonNode node = tree.get(fieldName); Assert.state(node != null && !(node instanceof NullNode), () -> "Missing JSON field '" + fieldName + "'"); return node; }
Helper method to return a {@link JsonNode} from the tree. @param tree the source tree @param fieldName the field name to extract @return the {@link JsonNode}
public JmsPoolConnectionFactory createPooledConnectionFactory( ConnectionFactory connectionFactory) { JmsPoolConnectionFactory pooledConnectionFactory = new JmsPoolConnectionFactory(); pooledConnectionFactory.setConnectionFactory(connectionFactory); pooledConnectionFactory .setBlockIfSessionPoolIsFull(this.properties.isBlockIfFull()); if (this.properties.getBlockIfFullTimeout() != null) { pooledConnectionFactory.setBlockIfSessionPoolIsFullTimeout( this.properties.getBlockIfFullTimeout().toMillis()); } if (this.properties.getIdleTimeout() != null) { pooledConnectionFactory.setConnectionIdleTimeout( (int) this.properties.getIdleTimeout().toMillis()); } pooledConnectionFactory.setMaxConnections(this.properties.getMaxConnections()); pooledConnectionFactory.setMaxSessionsPerConnection( this.properties.getMaxSessionsPerConnection()); if (this.properties.getTimeBetweenExpirationCheck() != null) { pooledConnectionFactory.setConnectionCheckInterval( this.properties.getTimeBetweenExpirationCheck().toMillis()); } pooledConnectionFactory .setUseAnonymousProducers(this.properties.isUseAnonymousProducers()); return pooledConnectionFactory; }
Create a {@link JmsPoolConnectionFactory} based on the specified {@link ConnectionFactory}. @param connectionFactory the connection factory to wrap @return a pooled connection factory
public ProjectGenerationResponse generate(ProjectGenerationRequest request) throws IOException { Log.info("Using service at " + request.getServiceUrl()); InitializrServiceMetadata metadata = loadMetadata(request.getServiceUrl()); URI url = request.generateUrl(metadata); CloseableHttpResponse httpResponse = executeProjectGenerationRequest(url); HttpEntity httpEntity = httpResponse.getEntity(); validateResponse(httpResponse, request.getServiceUrl()); return createResponse(httpResponse, httpEntity); }
Generate a project based on the specified {@link ProjectGenerationRequest}. @param request the generation request @return an entity defining the project @throws IOException if generation fails
public InitializrServiceMetadata loadMetadata(String serviceUrl) throws IOException { CloseableHttpResponse httpResponse = executeInitializrMetadataRetrieval( serviceUrl); validateResponse(httpResponse, serviceUrl); return parseJsonMetadata(httpResponse.getEntity()); }
Load the {@link InitializrServiceMetadata} at the specified url. @param serviceUrl to url of the initializer service @return the metadata describing the service @throws IOException if the service's metadata cannot be loaded
public Object loadServiceCapabilities(String serviceUrl) throws IOException { HttpGet request = new HttpGet(serviceUrl); request.setHeader( new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES)); CloseableHttpResponse httpResponse = execute(request, serviceUrl, "retrieve help"); validateResponse(httpResponse, serviceUrl); HttpEntity httpEntity = httpResponse.getEntity(); ContentType contentType = ContentType.getOrDefault(httpEntity); if (contentType.getMimeType().equals("text/plain")) { return getContent(httpEntity); } return parseJsonMetadata(httpEntity); }
Loads the service capabilities of the service at the specified URL. If the service supports generating a textual representation of the capabilities, it is returned, otherwise {@link InitializrServiceMetadata} is returned. @param serviceUrl to url of the initializer service @return the service capabilities (as a String) or the {@link InitializrServiceMetadata} describing the service @throws IOException if the service capabilities cannot be loaded
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. @param url the URL @return the response
public PropertiesMigrationReport getReport() { PropertiesMigrationReport report = new PropertiesMigrationReport(); Map<String, List<PropertyMigration>> properties = getMatchingProperties( deprecatedFilter()); if (properties.isEmpty()) { return report; } properties.forEach((name, candidates) -> { PropertySource<?> propertySource = mapPropertiesWithReplacement(report, name, candidates); if (propertySource != null) { this.environment.getPropertySources().addBefore(name, propertySource); } }); return report; }
Analyse the {@link ConfigurableEnvironment environment} and attempt to rename legacy properties if a replacement exists. @return a report of the migration
public Collection<Resource> createEndpointResources(EndpointMapping endpointMapping, Collection<ExposableWebEndpoint> endpoints, EndpointMediaTypes endpointMediaTypes, EndpointLinksResolver linksResolver) { List<Resource> resources = new ArrayList<>(); endpoints.stream().flatMap((endpoint) -> endpoint.getOperations().stream()) .map((operation) -> createResource(endpointMapping, operation)) .forEach(resources::add); if (StringUtils.hasText(endpointMapping.getPath())) { Resource resource = createEndpointLinksResource(endpointMapping.getPath(), endpointMediaTypes, linksResolver); resources.add(resource); } return resources; }
Creates {@link Resource Resources} for the operations of the given {@code webEndpoints}. @param endpointMapping the base mapping for all endpoints @param endpoints the web endpoints @param endpointMediaTypes media types consumed and produced by the endpoints @param linksResolver resolver for determining links to available endpoints @return the resources for the operations
public StaticResourceServerWebExchange at(StaticResourceLocation first, StaticResourceLocation... rest) { return at(EnumSet.of(first, rest)); }
Returns a matcher that includes the specified {@link StaticResourceLocation Locations}. For example: <pre class="code"> PathRequest.toStaticResources().at(StaticResourceLocation.CSS, StaticResourceLocation.JAVA_SCRIPT) </pre> @param first the first location to include @param rest additional locations to include @return the configured {@link ServerWebExchangeMatcher}
public StaticResourceServerWebExchange at(Set<StaticResourceLocation> locations) { Assert.notNull(locations, "Locations must not be null"); return new StaticResourceServerWebExchange(new LinkedHashSet<>(locations)); }
Returns a matcher that includes the specified {@link StaticResourceLocation Locations}. For example: <pre class="code"> PathRequest.toStaticResources().at(locations) </pre> @param locations the locations to include @return the configured {@link ServerWebExchangeMatcher}
StandardEnvironment convertEnvironmentIfNecessary(ConfigurableEnvironment environment, Class<? extends StandardEnvironment> type) { if (type.equals(environment.getClass())) { return (StandardEnvironment) environment; } return convertEnvironment(environment, type); }
Converts the given {@code environment} to the given {@link StandardEnvironment} type. If the environment is already of the same type, no conversion is performed and it is returned unchanged. @param environment the Environment to convert @param type the type to convert the Environment to @return the converted Environment
public Set<String> getNamesForType(Class<?> type, TypeExtractor typeExtractor) { updateTypesIfNecessary(); return this.beanTypes.entrySet().stream().filter((entry) -> { Class<?> beanType = extractType(entry.getValue(), typeExtractor); return beanType != null && type.isAssignableFrom(beanType); }
Return the names of beans matching the given type (including subclasses), judging from either bean definitions or the value of {@link FactoryBean#getObjectType()} in the case of {@link FactoryBean FactoryBeans}. Will include singletons but will not cause early bean initialization. @param type the class or interface to match (must not be {@code null}) @param typeExtractor function used to extract the actual type @return the names of beans (or objects created by FactoryBeans) matching the given object type (including subclasses), or an empty set if none
@SuppressWarnings("unchecked") public <T extends CacheManager> T customize(T cacheManager) { LambdaSafe.callbacks(CacheManagerCustomizer.class, this.customizers, cacheManager) .withLogger(CacheManagerCustomizers.class) .invoke((customizer) -> customizer.customize(cacheManager)); return cacheManager; }
Customize the specified {@link CacheManager}. Locates all {@link CacheManagerCustomizer} beans able to handle the specified instance and invoke {@link CacheManagerCustomizer#customize(CacheManager)} on them. @param <T> the type of cache manager @param cacheManager the cache manager to customize @return the cache manager
public void compileAndRun() throws Exception { synchronized (this.monitor) { try { stop(); Class<?>[] compiledSources = compile(); monitorForChanges(); // Run in new thread to ensure that the context classloader is setup 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. @throws Exception on error
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. @param metadata the metadata that describes the service @return the project generation URI
protected String resolveArtifactId() { if (this.artifactId != null) { return this.artifactId; } if (this.output != null) { int i = this.output.lastIndexOf('.'); return (i != -1) ? this.output.substring(0, i) : this.output; } return null; }
Resolve the artifactId to use or {@code null} if it should not be customized. @return the artifactId
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. @param context the context @param metadata the annotation meta-data @param conditions conditions to test @return {@code true} if any condition matches.
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. @param context the context @param metadata the annotation meta-data @param condition condition to test @return {@code true} if the condition matches.
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. @param ex the source exception @return {@code true} if the exception contains a log configuration message
private void handle(ExecuteContext context, SQLExceptionTranslator translator, SQLException exception) { DataAccessException translated = translate(context, translator, exception); if (exception.getNextException() == null) { context.exception(translated); } else { logger.error("Execution of SQL statement failed.", translated); } }
Handle a single exception in the chain. SQLExceptions might be nested multiple levels deep. The outermost exception is usually the least interesting one ("Call getNextException to see the cause."). Therefore the innermost exception is propagated and all other exceptions are logged. @param context the execute context @param translator the exception translator @param exception the exception
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. @param awaitTerminationPeriod the await termination period to set @return a new builder instance
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. @param threadNamePrefix the thread name prefix to set @return a new builder instance
public TaskSchedulerBuilder customizers(TaskSchedulerCustomizer... customizers) { Assert.notNull(customizers, "Customizers must not be null"); return customizers(Arrays.asList(customizers)); }
Set the {@link TaskSchedulerCustomizer TaskSchedulerCustomizers} that should be applied to the {@link ThreadPoolTaskScheduler}. Customizers are applied in the order that they were added after builder configuration has been applied. Setting this value will replace any previously configured customizers. @param customizers the customizers to set @return a new builder instance @see #additionalCustomizers(TaskSchedulerCustomizer...)
public TaskSchedulerBuilder customizers( Iterable<TaskSchedulerCustomizer> customizers) { Assert.notNull(customizers, "Customizers must not be null"); return new TaskSchedulerBuilder(this.poolSize, this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, append(null, customizers)); }
Set the {@link TaskSchedulerCustomizer taskSchedulerCustomizers} that should be applied to the {@link ThreadPoolTaskScheduler}. Customizers are applied in the order that they were added after builder configuration has been applied. Setting this value will replace any previously configured customizers. @param customizers the customizers to set @return a new builder instance @see #additionalCustomizers(TaskSchedulerCustomizer...)
public TaskSchedulerBuilder additionalCustomizers( TaskSchedulerCustomizer... customizers) { Assert.notNull(customizers, "Customizers must not be null"); return additionalCustomizers(Arrays.asList(customizers)); }
Add {@link TaskSchedulerCustomizer taskSchedulerCustomizers} that should be applied to the {@link ThreadPoolTaskScheduler}. Customizers are applied in the order that they were added after builder configuration has been applied. @param customizers the customizers to add @return a new builder instance @see #customizers(TaskSchedulerCustomizer...)
public <T extends ThreadPoolTaskScheduler> T configure(T taskScheduler) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(this.poolSize).to(taskScheduler::setPoolSize); map.from(this.awaitTermination) .to(taskScheduler::setWaitForTasksToCompleteOnShutdown); map.from(this.awaitTerminationPeriod).asInt(Duration::getSeconds) .to(taskScheduler::setAwaitTerminationSeconds); map.from(this.threadNamePrefix).to(taskScheduler::setThreadNamePrefix); if (!CollectionUtils.isEmpty(this.customizers)) { this.customizers.forEach((customizer) -> customizer.customize(taskScheduler)); } return taskScheduler; }
Configure the provided {@link ThreadPoolTaskScheduler} instance using this builder. @param <T> the type of task scheduler @param taskScheduler the {@link ThreadPoolTaskScheduler} to configure @return the task scheduler instance @see #build()
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. @param classLoader the classloader @return the logging system
public void addListener(FileChangeListener fileChangeListener) { Assert.notNull(fileChangeListener, "FileChangeListener must not be null"); synchronized (this.monitor) { checkNotStarted(); this.listeners.add(fileChangeListener); } }
Add listener for file change events. Cannot be called after the watcher has been {@link #start() started}. @param fileChangeListener the listener to add
public void addSourceFolders(Iterable<File> folders) { Assert.notNull(folders, "Folders must not be null"); synchronized (this.monitor) { for (File folder : folders) { addSourceFolder(folder); } } }
Add source folders to monitor. Cannot be called after the watcher has been {@link #start() started}. @param folders the folders to monitor
public void addSourceFolder(File folder) { Assert.notNull(folder, "Folder must not be null"); Assert.isTrue(!folder.isFile(), "Folder '" + folder + "' must not be a file"); synchronized (this.monitor) { checkNotStarted(); this.folders.put(folder, null); } }
Add a source folder to monitor. Cannot be called after the watcher has been {@link #start() started}. @param folder the folder to monitor
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.
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. @param remainingScans the number of remaining scans
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. @param request the source request @param includeStackTrace whether to include the error stacktrace information @return the error attributes as a Map.
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. @param request the source request @return {@code true} if the error trace has been requested, {@code false} otherwise
protected Mono<ServerResponse> renderErrorView(String viewName, ServerResponse.BodyBuilder responseBody, Map<String, Object> error) { if (isTemplateAvailable(viewName)) { return responseBody.render(viewName, error); } Resource resource = resolveResource(viewName); if (resource != null) { return responseBody.body(BodyInserters.fromResource(resource)); } return Mono.empty(); }
Render the given error data as a view, using a template view if available or a static HTML file if available otherwise. This will return an empty {@code Publisher} if none of the above are available. @param viewName the view name @param responseBody the error response being built @param error the error data as a map @return a Publisher of the {@link ServerResponse}
protected Mono<ServerResponse> renderDefaultErrorView( ServerResponse.BodyBuilder responseBody, Map<String, Object> error) { StringBuilder builder = new StringBuilder(); Date timestamp = (Date) error.get("timestamp"); Object message = error.get("message"); Object trace = error.get("trace"); Object requestId = error.get("requestId"); builder.append("<html><body><h1>Whitelabel Error Page</h1>").append( "<p>This application has no configured error view, so you are seeing this as a fallback.</p>") .append("<div id='created'>").append(timestamp).append("</div>") .append("<div>[").append(requestId) .append("] There was an unexpected error (type=") .append(htmlEscape(error.get("error"))).append(", status=") .append(htmlEscape(error.get("status"))).append(").</div>"); if (message != null) { builder.append("<div>").append(htmlEscape(message)).append("</div>"); } if (trace != null) { builder.append("<div style='white-space:pre-wrap;'>") .append(htmlEscape(trace)).append("</div>"); } builder.append("</body></html>"); return responseBody.syncBody(builder.toString()); }
Render a default HTML "Whitelabel Error Page". <p> Useful when no other error view is available in the application. @param responseBody the error response being built @param error the error data as a map @return a Publisher of the {@link ServerResponse}
public String readHeader() throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; StringBuilder content = new StringBuilder(BUFFER_SIZE); while (content.indexOf(HEADER_END) == -1) { int amountRead = checkedRead(buffer, 0, BUFFER_SIZE); content.append(new String(buffer, 0, amountRead)); } return content.substring(0, content.indexOf(HEADER_END)); }
Read the HTTP header from the {@link InputStream}. Note: This method doesn't expect any HTTP content after the header since the initial request is usually just a WebSocket upgrade. @return the HTTP header @throws IOException in case of I/O errors
public void readFully(byte[] buffer, int offset, int length) throws IOException { while (length > 0) { int amountRead = checkedRead(buffer, offset, length); offset += amountRead; length -= amountRead; } }
Repeatedly read the underlying {@link InputStream} until the requested number of bytes have been loaded. @param buffer the destination buffer @param offset the buffer offset @param length the amount of data to read @throws IOException in case of I/O errors
public int checkedRead(byte[] buffer, int offset, int length) throws IOException { int amountRead = read(buffer, offset, length); if (amountRead == -1) { throw new IOException("End of stream"); } return amountRead; }
Read a number of bytes from the stream (checking that the end of the stream hasn't been reached). @param buffer the destination buffer @param offset the buffer offset @param length the length to read @return the amount of data read @throws IOException in case of I/O errors
private String getEntityManagerFactoryName(String beanName) { if (beanName.length() > ENTITY_MANAGER_FACTORY_SUFFIX.length() && StringUtils .endsWithIgnoreCase(beanName, ENTITY_MANAGER_FACTORY_SUFFIX)) { return beanName.substring(0, beanName.length() - ENTITY_MANAGER_FACTORY_SUFFIX.length()); } return beanName; }
Get the name of an {@link EntityManagerFactory} based on its {@code beanName}. @param beanName the name of the {@link EntityManagerFactory} bean @return a name for the given entity manager factory
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card