code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public static boolean hasAtLeastOneAnnotation(AnnotatedNode node,
String... annotations) {
for (AnnotationNode annotationNode : node.getAnnotations()) {
for (String annotation : annotations) {
if (PatternMatchUtils.simpleMatch(annotation,
annotationNode.getClassNode().getName())) {
return true;
}
}
}
return false;
} | Determine if an {@link AnnotatedNode} has one or more of the specified annotations.
N.B. the annotation type names are not normally fully qualified.
@param node the node to examine
@param annotations the annotations to look for
@return {@code true} if at least one of the annotations is found, otherwise
{@code false} |
public static boolean hasAtLeastOneFieldOrMethod(ClassNode node, String... types) {
Set<String> typesSet = new HashSet<>(Arrays.asList(types));
for (FieldNode field : node.getFields()) {
if (typesSet.contains(field.getType().getName())) {
return true;
}
}
for (MethodNode method : node.getMethods()) {
if (typesSet.contains(method.getReturnType().getName())) {
return true;
}
}
return false;
} | Determine if a {@link ClassNode} has one or more fields of the specified types or
method returning one or more of the specified types. N.B. the type names are not
normally fully qualified.
@param node the class to examine
@param types the types to look for
@return {@code true} if at least one of the types is found, otherwise {@code false} |
public static boolean subclasses(ClassNode node, String... types) {
for (String type : types) {
if (node.getSuperClass().getName().equals(type)) {
return true;
}
}
return false;
} | Determine if a {@link ClassNode} subclasses any of the specified types N.B. the
type names are not normally fully qualified.
@param node the class to examine
@param types the types that may have been sub-classed
@return {@code true} if the class subclasses any of the specified types, otherwise
{@code false} |
public static ClosureExpression getClosure(BlockStatement block, String name,
boolean remove) {
for (ExpressionStatement statement : getExpressionStatements(block)) {
Expression expression = statement.getExpression();
if (expression instanceof MethodCallExpression) {
ClosureExpression closure = getClosure(name,
(MethodCallExpression) expression);
if (closure != null) {
if (remove) {
block.getStatements().remove(statement);
}
return closure;
}
}
}
return null;
} | Extract a top-level {@code name} closure from inside this block if there is one,
optionally removing it from the block at the same time.
@param block a block statement (class definition)
@param name the name to look for
@param remove whether or not the extracted closure should be removed
@return a beans Closure if one can be found, null otherwise |
public void merge(ConfigurationMetadata metadata) {
for (ItemMetadata additionalItem : metadata.getItems()) {
mergeItemMetadata(additionalItem);
}
for (ItemHint itemHint : metadata.getHints()) {
add(itemHint);
}
} | Merge the content from another {@link ConfigurationMetadata}.
@param metadata the {@link ConfigurationMetadata} instance to merge |
public void handle(ServerHttpRequest request, ServerHttpResponse response)
throws IOException {
handle(new HttpConnection(request, response));
} | Handle an incoming HTTP connection.
@param request the HTTP request
@param response the HTTP response
@throws IOException in case of I/O errors |
protected void handle(HttpConnection httpConnection) throws IOException {
try {
getServerThread().handleIncomingHttp(httpConnection);
httpConnection.waitForResponse();
}
catch (ConnectException ex) {
httpConnection.respond(HttpStatus.GONE);
}
} | Handle an incoming HTTP connection.
@param httpConnection the HTTP connection
@throws IOException in case of I/O errors |
protected ServerThread getServerThread() throws IOException {
synchronized (this) {
if (this.serverThread == null) {
ByteChannel channel = this.serverConnection.open(this.longPollTimeout);
this.serverThread = new ServerThread(channel);
this.serverThread.start();
}
return this.serverThread;
}
} | Returns the active server thread, creating and starting it if necessary.
@return the {@code ServerThread} (never {@code null})
@throws IOException in case of I/O errors |
public HttpWebServiceMessageSenderBuilder requestFactory(
Supplier<ClientHttpRequestFactory> requestFactorySupplier) {
Assert.notNull(requestFactorySupplier,
"RequestFactory Supplier must not be null");
this.requestFactorySupplier = requestFactorySupplier;
return this;
} | Set the {@code Supplier} of {@link ClientHttpRequestFactory} that should be called
to create the HTTP-based {@link WebServiceMessageSender}.
@param requestFactorySupplier the supplier for the request factory
@return a new builder instance |
public Mono<AccessLevel> getAccessLevel(String token, String applicationId)
throws CloudFoundryAuthorizationException {
String uri = getPermissionsUri(applicationId);
return this.webClient.get().uri(uri).header("Authorization", "bearer " + token)
.retrieve().bodyToMono(Map.class).map(this::getAccessLevel)
.onErrorMap(this::mapError);
} | Return a Mono of the access level that should be granted to the given token.
@param token the token
@param applicationId the cloud foundry application ID
@return a Mono of the access level that should be granted
@throws CloudFoundryAuthorizationException if the token is not authorized |
public Mono<String> getUaaUrl() {
this.uaaUrl = this.webClient.get().uri(this.cloudControllerUrl + "/info")
.retrieve().bodyToMono(Map.class)
.map((response) -> (String) response.get("token_endpoint")).cache()
.onErrorMap((ex) -> new CloudFoundryAuthorizationException(
Reason.SERVICE_UNAVAILABLE,
"Unable to fetch token keys from UAA."));
return this.uaaUrl;
} | Return a Mono of URL of the UAA.
@return the UAA url Mono |
protected final FilterArtifacts getFilters(ArtifactsFilter... additionalFilters) {
FilterArtifacts filters = new FilterArtifacts();
for (ArtifactsFilter additionalFilter : additionalFilters) {
filters.addFilter(additionalFilter);
}
filters.addFilter(
new MatchingGroupIdFilter(cleanFilterConfig(this.excludeGroupIds)));
if (this.includes != null && !this.includes.isEmpty()) {
filters.addFilter(new IncludeFilter(this.includes));
}
if (this.excludes != null && !this.excludes.isEmpty()) {
filters.addFilter(new ExcludeFilter(this.excludes));
}
return filters;
} | Return artifact filters configured for this MOJO.
@param additionalFilters optional additional filters to apply
@return the filters |
public static Layout forFile(File file) {
if (file == null) {
throw new IllegalArgumentException("File must not be null");
}
String lowerCaseFileName = file.getName().toLowerCase(Locale.ENGLISH);
if (lowerCaseFileName.endsWith(".jar")) {
return new Jar();
}
if (lowerCaseFileName.endsWith(".war")) {
return new War();
}
if (file.isDirectory() || lowerCaseFileName.endsWith(".zip")) {
return new Expanded();
}
throw new IllegalStateException("Unable to deduce layout for '" + file + "'");
} | Return a layout for the given source file.
@param file the source file
@return a {@link Layout} |
public static JsonParser getJsonParser() {
if (ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", null)) {
return new JacksonJsonParser();
}
if (ClassUtils.isPresent("com.google.gson.Gson", null)) {
return new GsonJsonParser();
}
if (ClassUtils.isPresent("org.yaml.snakeyaml.Yaml", null)) {
return new YamlJsonParser();
}
return new BasicJsonParser();
} | Static factory for the "best" JSON parser available on the classpath. Tries
Jackson, then Gson, Snake YAML, and then falls back to the {@link BasicJsonParser}.
@return a {@link JsonParser} |
@TaskAction
public void generateBuildProperties() {
try {
new BuildPropertiesWriter(new File(getDestinationDir(),
"build-info.properties")).writeBuildProperties(new ProjectDetails(
this.properties.getGroup(),
(this.properties.getArtifact() != null)
? this.properties.getArtifact() : "unspecified",
this.properties.getVersion(), this.properties.getName(),
this.properties.getTime(),
coerceToStringValues(this.properties.getAdditional())));
}
catch (IOException ex) {
throw new TaskExecutionException(this, ex);
}
} | Generates the {@code build-info.properties} file in the configured
{@link #setDestinationDir(File) destination}. |
public static RootUriTemplateHandler addTo(RestTemplate restTemplate,
String rootUri) {
Assert.notNull(restTemplate, "RestTemplate must not be null");
RootUriTemplateHandler handler = new RootUriTemplateHandler(rootUri,
restTemplate.getUriTemplateHandler());
restTemplate.setUriTemplateHandler(handler);
return handler;
} | Add a {@link RootUriTemplateHandler} instance to the given {@link RestTemplate}.
@param restTemplate the {@link RestTemplate} to add the handler to
@param rootUri the root URI
@return the added {@link RootUriTemplateHandler}. |
protected ModelAndView resolveErrorView(HttpServletRequest request,
HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
for (ErrorViewResolver resolver : this.errorViewResolvers) {
ModelAndView modelAndView = resolver.resolveErrorView(request, status, model);
if (modelAndView != null) {
return modelAndView;
}
}
return null;
} | Resolve any specific error views. By default this method delegates to
{@link ErrorViewResolver ErrorViewResolvers}.
@param request the request
@param response the response
@param status the HTTP status
@param model the suggested model
@return a specific {@link ModelAndView} or {@code null} if the default should be
used
@since 1.4.0 |
public StaticResourceRequestMatcher 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 RequestMatcher} |
public StaticResourceRequestMatcher at(Set<StaticResourceLocation> locations) {
Assert.notNull(locations, "Locations must not be null");
return new StaticResourceRequestMatcher(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 RequestMatcher} |
public void addAll(ClassLoaderFiles files) {
Assert.notNull(files, "Files must not be null");
for (SourceFolder folder : files.getSourceFolders()) {
for (Map.Entry<String, ClassLoaderFile> entry : folder.getFilesEntrySet()) {
addFile(folder.getName(), entry.getKey(), entry.getValue());
}
}
} | Add all elements items from the specified {@link ClassLoaderFiles} to this
instance.
@param files the files to add |
public void addFile(String sourceFolder, String name, ClassLoaderFile file) {
Assert.notNull(sourceFolder, "SourceFolder must not be null");
Assert.notNull(name, "Name must not be null");
Assert.notNull(file, "File must not be null");
removeAll(name);
getOrCreateSourceFolder(sourceFolder).add(name, file);
} | Add a single {@link ClassLoaderFile} to the collection.
@param sourceFolder the source folder of the file
@param name the name of the file
@param file the file to add |
protected final SourceFolder getOrCreateSourceFolder(String name) {
SourceFolder sourceFolder = this.sourceFolders.get(name);
if (sourceFolder == null) {
sourceFolder = new SourceFolder(name);
this.sourceFolders.put(name, sourceFolder);
}
return sourceFolder;
} | Get or create a {@link SourceFolder} with the given name.
@param name the name of the folder
@return an existing or newly added {@link SourceFolder} |
public int size() {
int size = 0;
for (SourceFolder sourceFolder : this.sourceFolders.values()) {
size += sourceFolder.getFiles().size();
}
return size;
} | Return the size of the collection.
@return the size of the collection |
public int getExitCode() {
int exitCode = 0;
for (ExitCodeGenerator generator : this.generators) {
try {
int value = generator.getExitCode();
if (value > 0 && value > exitCode || value < 0 && value < exitCode) {
exitCode = value;
}
}
catch (Exception ex) {
exitCode = (exitCode != 0) ? exitCode : 1;
ex.printStackTrace();
}
}
return exitCode;
} | Get the final exit code that should be returned based on all contained generators.
@return the final exit code. |
public final File getValidDirectory() {
File file = this.directory;
file = (file != null) ? file : getWarFileDocumentRoot();
file = (file != null) ? file : getExplodedWarFileDocumentRoot();
file = (file != null) ? file : getCommonDocumentRoot();
if (file == null && this.logger.isDebugEnabled()) {
logNoDocumentRoots();
}
else if (this.logger.isDebugEnabled()) {
this.logger.debug("Document root: " + file);
}
return file;
} | Returns the absolute document root when it points to a valid directory, logging a
warning and returning {@code null} otherwise.
@return the valid document root |
public void handle(ServerHttpRequest request, ServerHttpResponse response)
throws IOException {
try {
Assert.state(request.getHeaders().getContentLength() > 0, "No content");
ObjectInputStream objectInputStream = new ObjectInputStream(
request.getBody());
ClassLoaderFiles files = (ClassLoaderFiles) objectInputStream.readObject();
objectInputStream.close();
this.server.updateAndRestart(files);
response.setStatusCode(HttpStatus.OK);
}
catch (Exception ex) {
logger.warn("Unable to handler restart server HTTP request", ex);
response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
}
} | Handle a server request.
@param request the request
@param response the response
@throws IOException in case of I/O errors |
public boolean exists(ResourcePatternResolver resolver) {
Assert.notNull(resolver, "Resolver must not be null");
if (resolver.getResource(this.path).exists()) {
return true;
}
try {
return anyExists(resolver);
}
catch (IOException ex) {
return false;
}
} | Determine if this template location exists using the specified
{@link ResourcePatternResolver}.
@param resolver the resolver used to test if the location exists
@return {@code true} if the location exists. |
protected File getPortFile(ApplicationContext applicationContext) {
String namespace = getServerNamespace(applicationContext);
if (StringUtils.isEmpty(namespace)) {
return this.file;
}
String name = this.file.getName();
String extension = StringUtils.getFilenameExtension(this.file.getName());
name = name.substring(0, name.length() - extension.length() - 1);
if (isUpperCase(name)) {
name = name + "-" + namespace.toUpperCase(Locale.ENGLISH);
}
else {
name = name + "-" + namespace.toLowerCase(Locale.ENGLISH);
}
if (StringUtils.hasLength(extension)) {
name = name + "." + extension;
}
return new File(this.file.getParentFile(), name);
} | Return the actual port file that should be written for the given application
context. The default implementation builds a file from the source file and the
application context namespace if available.
@param applicationContext the source application context
@return the file that should be written |
public static OperationInvoker apply(OperationInvoker invoker, long timeToLive) {
if (timeToLive > 0) {
return new CachingOperationInvoker(invoker, timeToLive);
}
return invoker;
} | Apply caching configuration when appropriate to the given invoker.
@param invoker the invoker to wrap
@param timeToLive the maximum time in milliseconds that a response can be cached
@return a caching version of the invoker or the original instance if caching is not
required |
public Object launch(Class<?>[] sources, String[] args) throws Exception {
Map<String, Object> defaultProperties = new HashMap<>();
defaultProperties.put("spring.groovy.template.check-template-location", "false");
Class<?> applicationClass = this.classLoader
.loadClass(getSpringApplicationClassName());
Constructor<?> constructor = applicationClass.getConstructor(Class[].class);
Object application = constructor.newInstance((Object) sources);
applicationClass.getMethod("setDefaultProperties", Map.class).invoke(application,
defaultProperties);
Method method = applicationClass.getMethod("run", String[].class);
return method.invoke(application, (Object) args);
} | Launches the application created using the given {@code sources}. The application
is launched with the given {@code args}.
@param sources the sources for the application
@param args the args for the application
@return the application's {@code ApplicationContext}
@throws Exception if the launch fails |
public void assignTo(HttpOutputMessage message) throws IOException {
Assert.notNull(message, "Message must not be null");
HttpHeaders headers = message.getHeaders();
headers.setContentLength(this.data.remaining());
headers.add(SEQ_HEADER, Long.toString(getSequence()));
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
WritableByteChannel body = Channels.newChannel(message.getBody());
while (this.data.hasRemaining()) {
body.write(this.data);
}
body.close();
} | Assign this payload to the given {@link HttpOutputMessage}.
@param message the message to assign this payload to
@throws IOException in case of I/O errors |
public void writeTo(WritableByteChannel channel) throws IOException {
Assert.notNull(channel, "Channel must not be null");
while (this.data.hasRemaining()) {
channel.write(this.data);
}
} | Write the content of this payload to the given target channel.
@param channel the channel to write to
@throws IOException in case of I/O errors |
public static HttpTunnelPayload get(HttpInputMessage message) throws IOException {
long length = message.getHeaders().getContentLength();
if (length <= 0) {
return null;
}
String seqHeader = message.getHeaders().getFirst(SEQ_HEADER);
Assert.state(StringUtils.hasLength(seqHeader), "Missing sequence header");
ReadableByteChannel body = Channels.newChannel(message.getBody());
ByteBuffer payload = ByteBuffer.allocate((int) length);
while (payload.hasRemaining()) {
body.read(payload);
}
body.close();
payload.flip();
return new HttpTunnelPayload(Long.valueOf(seqHeader), payload);
} | Return the {@link HttpTunnelPayload} for the given message or {@code null} if there
is no payload.
@param message the HTTP message
@return the payload or {@code null}
@throws IOException in case of I/O errors |
public static ByteBuffer getPayloadData(ReadableByteChannel channel)
throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
try {
int amountRead = channel.read(buffer);
Assert.state(amountRead != -1, "Target server connection closed");
buffer.flip();
return buffer;
}
catch (InterruptedIOException ex) {
return null;
}
} | Return the payload data for the given source {@link ReadableByteChannel} or null if
the channel timed out whilst reading.
@param channel the source channel
@return payload data or {@code null}
@throws IOException in case of I/O errors |
public String toHexString() {
byte[] bytes = this.data.array();
char[] hex = new char[this.data.remaining() * 2];
for (int i = this.data.position(); i < this.data.remaining(); i++) {
int b = bytes[i] & 0xFF;
hex[i * 2] = HEX_CHARS[b >>> 4];
hex[i * 2 + 1] = HEX_CHARS[b & 0x0F];
}
return new String(hex);
} | Return the payload as a hexadecimal string.
@return the payload as a hex string |
protected boolean isMain(Thread thread) {
return thread.getName().equals("main") && thread.getContextClassLoader()
.getClass().getName().contains("AppClassLoader");
} | Returns if the thread is for a main invocation. By default checks the name of the
thread and the context classloader.
@param thread the thread to check
@return {@code true} if the thread is a main invocation |
public boolean bindCacheToRegistry(Cache cache, Tag... tags) {
MeterBinder meterBinder = getMeterBinder(unwrapIfNecessary(cache), Tags.of(tags));
if (meterBinder != null) {
meterBinder.bindTo(this.registry);
return true;
}
return false;
} | Attempt to bind the specified {@link Cache} to the registry. Return {@code true} if
the cache is supported and was bound to the registry, {@code false} otherwise.
@param cache the cache to handle
@param tags the tags to associate with the metrics of that cache
@return {@code true} if the {@code cache} is supported and was registered |
public static OriginTrackedValue of(Object value, Origin origin) {
if (value == null) {
return null;
}
if (value instanceof CharSequence) {
return new OriginTrackedCharSequence((CharSequence) value, origin);
}
return new OriginTrackedValue(value, origin);
} | Create an {@link OriginTrackedValue} containing the specified {@code value} and
{@code origin}. If the source value implements {@link CharSequence} then so will
the resulting {@link OriginTrackedValue}.
@param value the source value
@param origin the origin
@return an {@link OriginTrackedValue} or {@code null} if the source value was
{@code null}. |
public AccessLevel getAccessLevel(String token, String applicationId)
throws CloudFoundryAuthorizationException {
try {
URI uri = getPermissionsUri(applicationId);
RequestEntity<?> request = RequestEntity.get(uri)
.header("Authorization", "bearer " + token).build();
Map<?, ?> body = this.restTemplate.exchange(request, Map.class).getBody();
if (Boolean.TRUE.equals(body.get("read_sensitive_data"))) {
return AccessLevel.FULL;
}
return AccessLevel.RESTRICTED;
}
catch (HttpClientErrorException ex) {
if (ex.getStatusCode().equals(HttpStatus.FORBIDDEN)) {
throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED,
"Access denied");
}
throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN,
"Invalid token", ex);
}
catch (HttpServerErrorException ex) {
throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE,
"Cloud controller not reachable");
}
} | Return the access level that should be granted to the given token.
@param token the token
@param applicationId the cloud foundry application ID
@return the access level that should be granted
@throws CloudFoundryAuthorizationException if the token is not authorized |
public Map<String, String> fetchTokenKeys() {
try {
return extractTokenKeys(this.restTemplate
.getForObject(getUaaUrl() + "/token_keys", Map.class));
}
catch (HttpStatusCodeException ex) {
throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE,
"UAA not reachable");
}
} | Return all token keys known by the UAA.
@return a list of token keys |
public String getUaaUrl() {
if (this.uaaUrl == null) {
try {
Map<?, ?> response = this.restTemplate
.getForObject(this.cloudControllerUrl + "/info", Map.class);
this.uaaUrl = (String) response.get("token_endpoint");
}
catch (HttpStatusCodeException ex) {
throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE,
"Unable to fetch token keys from UAA");
}
}
return this.uaaUrl;
} | Return the URL of the UAA.
@return the UAA url |
public static Log getLog(Class<?> source) {
synchronized (logs) {
Log log = new DeferredLog();
logs.put(log, source);
return log;
}
} | Get a {@link Log} instance for the specified source that will be automatically
{@link DeferredLog#switchTo(Class) switched} when the
{@link ApplicationPreparedEvent context is prepared}.
@param source the source for logging
@return a {@link DeferredLog} instance |
public void setUrlMappings(Collection<String> urlMappings) {
Assert.notNull(urlMappings, "UrlMappings must not be null");
this.urlMappings = new LinkedHashSet<>(urlMappings);
} | Set the URL mappings for the servlet. If not specified the mapping will default to
'/'. This will replace any previously specified mappings.
@param urlMappings the mappings to set
@see #addUrlMappings(String...) |
public void addUrlMappings(String... urlMappings) {
Assert.notNull(urlMappings, "UrlMappings must not be null");
this.urlMappings.addAll(Arrays.asList(urlMappings));
} | Add URL mappings, as defined in the Servlet specification, for the servlet.
@param urlMappings the mappings to add
@see #setUrlMappings(Collection) |
@Override
protected void configure(ServletRegistration.Dynamic registration) {
super.configure(registration);
String[] urlMapping = StringUtils.toStringArray(this.urlMappings);
if (urlMapping.length == 0 && this.alwaysMapUrl) {
urlMapping = DEFAULT_MAPPINGS;
}
if (!ObjectUtils.isEmpty(urlMapping)) {
registration.addMapping(urlMapping);
}
registration.setLoadOnStartup(this.loadOnStartup);
if (this.multipartConfig != null) {
registration.setMultipartConfig(this.multipartConfig);
}
} | Configure registration settings. Subclasses can override this method to perform
additional configuration if required.
@param registration the registration |
public ProcessBuilder processBuilder(String... arguments) {
ProcessBuilder processBuilder = new ProcessBuilder(toString());
processBuilder.command().addAll(Arrays.asList(arguments));
return processBuilder;
} | Create a new {@link ProcessBuilder} that will run with the Java executable.
@param arguments the command arguments
@return a {@link ProcessBuilder} |
protected void initialize(ConfigurableEnvironment environment,
ClassLoader classLoader) {
new LoggingSystemProperties(environment).apply();
LogFile logFile = LogFile.get(environment);
if (logFile != null) {
logFile.applyToSystemProperties();
}
initializeEarlyLoggingLevel(environment);
initializeSystem(environment, this.loggingSystem, logFile);
initializeFinalLoggingLevels(environment, this.loggingSystem);
registerShutdownHookIfNecessary(environment, this.loggingSystem);
} | Initialize the logging system according to preferences expressed through the
{@link Environment} and the classpath.
@param environment the environment
@param classLoader the classloader |
public RestTemplateBuilder rootUri(String rootUri) {
return new RestTemplateBuilder(this.detectRequestFactory, rootUri,
this.messageConverters, this.requestFactorySupplier,
this.uriTemplateHandler, this.errorHandler, this.basicAuthentication,
this.restTemplateCustomizers, this.requestFactoryCustomizer,
this.interceptors);
} | Set a root URL that should be applied to each request that starts with {@code '/'}.
See {@link RootUriTemplateHandler} for details.
@param rootUri the root URI or {@code null}
@return a new builder instance |
public RestTemplateBuilder messageConverters(
HttpMessageConverter<?>... messageConverters) {
Assert.notNull(messageConverters, "MessageConverters must not be null");
return messageConverters(Arrays.asList(messageConverters));
} | Set the {@link HttpMessageConverter HttpMessageConverters} that should be used with
the {@link RestTemplate}. Setting this value will replace any previously configured
converters and any converters configured on the builder will replace RestTemplate's
default converters.
@param messageConverters the converters to set
@return a new builder instance
@see #additionalMessageConverters(HttpMessageConverter...) |
public RestTemplateBuilder messageConverters(
Collection<? extends HttpMessageConverter<?>> messageConverters) {
Assert.notNull(messageConverters, "MessageConverters must not be null");
return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
Collections.unmodifiableSet(
new LinkedHashSet<HttpMessageConverter<?>>(messageConverters)),
this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler,
this.basicAuthentication, this.restTemplateCustomizers,
this.requestFactoryCustomizer, this.interceptors);
} | Set the {@link HttpMessageConverter HttpMessageConverters} that should be used with
the {@link RestTemplate}. Setting this value will replace any previously configured
converters and any converters configured on the builder will replace RestTemplate's
default converters.
@param messageConverters the converters to set
@return a new builder instance
@see #additionalMessageConverters(HttpMessageConverter...) |
public RestTemplateBuilder additionalMessageConverters(
HttpMessageConverter<?>... messageConverters) {
Assert.notNull(messageConverters, "MessageConverters must not be null");
return additionalMessageConverters(Arrays.asList(messageConverters));
} | Add additional {@link HttpMessageConverter HttpMessageConverters} that should be
used with the {@link RestTemplate}. Any converters configured on the builder will
replace RestTemplate's default converters.
@param messageConverters the converters to add
@return a new builder instance
@see #messageConverters(HttpMessageConverter...) |
public RestTemplateBuilder additionalMessageConverters(
Collection<? extends HttpMessageConverter<?>> messageConverters) {
Assert.notNull(messageConverters, "MessageConverters must not be null");
return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
append(this.messageConverters, messageConverters),
this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler,
this.basicAuthentication, this.restTemplateCustomizers,
this.requestFactoryCustomizer, this.interceptors);
} | Add additional {@link HttpMessageConverter HttpMessageConverters} that should be
used with the {@link RestTemplate}. Any converters configured on the builder will
replace RestTemplate's default converters.
@param messageConverters the converters to add
@return a new builder instance
@see #messageConverters(HttpMessageConverter...) |
public RestTemplateBuilder defaultMessageConverters() {
return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
Collections.unmodifiableSet(
new LinkedHashSet<>(new RestTemplate().getMessageConverters())),
this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler,
this.basicAuthentication, this.restTemplateCustomizers,
this.requestFactoryCustomizer, this.interceptors);
} | Set the {@link HttpMessageConverter HttpMessageConverters} that should be used with
the {@link RestTemplate} to the default set. Calling this method will replace any
previously defined converters.
@return a new builder instance
@see #messageConverters(HttpMessageConverter...) |
public RestTemplateBuilder interceptors(
ClientHttpRequestInterceptor... interceptors) {
Assert.notNull(interceptors, "interceptors must not be null");
return interceptors(Arrays.asList(interceptors));
} | Set the {@link ClientHttpRequestInterceptor ClientHttpRequestInterceptors} that
should be used with the {@link RestTemplate}. Setting this value will replace any
previously defined interceptors.
@param interceptors the interceptors to set
@return a new builder instance
@since 1.4.1
@see #additionalInterceptors(ClientHttpRequestInterceptor...) |
public RestTemplateBuilder interceptors(
Collection<ClientHttpRequestInterceptor> interceptors) {
Assert.notNull(interceptors, "interceptors must not be null");
return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
this.messageConverters, this.requestFactorySupplier,
this.uriTemplateHandler, this.errorHandler, this.basicAuthentication,
this.restTemplateCustomizers, this.requestFactoryCustomizer,
Collections.unmodifiableSet(new LinkedHashSet<>(interceptors)));
} | Set the {@link ClientHttpRequestInterceptor ClientHttpRequestInterceptors} that
should be used with the {@link RestTemplate}. Setting this value will replace any
previously defined interceptors.
@param interceptors the interceptors to set
@return a new builder instance
@since 1.4.1
@see #additionalInterceptors(ClientHttpRequestInterceptor...) |
public RestTemplateBuilder additionalInterceptors(
ClientHttpRequestInterceptor... interceptors) {
Assert.notNull(interceptors, "interceptors must not be null");
return additionalInterceptors(Arrays.asList(interceptors));
} | Add additional {@link ClientHttpRequestInterceptor ClientHttpRequestInterceptors}
that should be used with the {@link RestTemplate}.
@param interceptors the interceptors to add
@return a new builder instance
@since 1.4.1
@see #interceptors(ClientHttpRequestInterceptor...) |
public RestTemplateBuilder additionalInterceptors(
Collection<? extends ClientHttpRequestInterceptor> interceptors) {
Assert.notNull(interceptors, "interceptors must not be null");
return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
this.messageConverters, this.requestFactorySupplier,
this.uriTemplateHandler, this.errorHandler, this.basicAuthentication,
this.restTemplateCustomizers, this.requestFactoryCustomizer,
append(this.interceptors, interceptors));
} | Add additional {@link ClientHttpRequestInterceptor ClientHttpRequestInterceptors}
that should be used with the {@link RestTemplate}.
@param interceptors the interceptors to add
@return a new builder instance
@since 1.4.1
@see #interceptors(ClientHttpRequestInterceptor...) |
public RestTemplateBuilder requestFactory(
Class<? extends ClientHttpRequestFactory> requestFactory) {
Assert.notNull(requestFactory, "RequestFactory must not be null");
return requestFactory(() -> createRequestFactory(requestFactory));
} | Set the {@link ClientHttpRequestFactory} class that should be used with the
{@link RestTemplate}.
@param requestFactory the request factory to use
@return a new builder instance |
public RestTemplateBuilder requestFactory(
Supplier<ClientHttpRequestFactory> requestFactorySupplier) {
Assert.notNull(requestFactorySupplier,
"RequestFactory Supplier must not be null");
return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
this.messageConverters, requestFactorySupplier, this.uriTemplateHandler,
this.errorHandler, this.basicAuthentication, this.restTemplateCustomizers,
this.requestFactoryCustomizer, this.interceptors);
} | Set the {@code Supplier} of {@link ClientHttpRequestFactory} that should be called
each time we {@link #build()} a new {@link RestTemplate} instance.
@param requestFactorySupplier the supplier for the request factory
@return a new builder instance
@since 2.0.0 |
public RestTemplateBuilder uriTemplateHandler(UriTemplateHandler uriTemplateHandler) {
Assert.notNull(uriTemplateHandler, "UriTemplateHandler must not be null");
return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
this.messageConverters, this.requestFactorySupplier, uriTemplateHandler,
this.errorHandler, this.basicAuthentication, this.restTemplateCustomizers,
this.requestFactoryCustomizer, this.interceptors);
} | Set the {@link UriTemplateHandler} that should be used with the
{@link RestTemplate}.
@param uriTemplateHandler the URI template handler to use
@return a new builder instance |
public RestTemplateBuilder errorHandler(ResponseErrorHandler errorHandler) {
Assert.notNull(errorHandler, "ErrorHandler must not be null");
return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
this.messageConverters, this.requestFactorySupplier,
this.uriTemplateHandler, errorHandler, this.basicAuthentication,
this.restTemplateCustomizers, this.requestFactoryCustomizer,
this.interceptors);
} | Set the {@link ResponseErrorHandler} that should be used with the
{@link RestTemplate}.
@param errorHandler the error handler to use
@return a new builder instance |
public RestTemplateBuilder basicAuthentication(String username, String password) {
return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
this.messageConverters, this.requestFactorySupplier,
this.uriTemplateHandler, this.errorHandler,
new BasicAuthenticationInterceptor(username, password),
this.restTemplateCustomizers, this.requestFactoryCustomizer,
this.interceptors);
} | Add HTTP basic authentication to requests. See
{@link BasicAuthenticationInterceptor} for details.
@param username the user name
@param password the password
@return a new builder instance
@since 2.1.0 |
public RestTemplateBuilder customizers(
RestTemplateCustomizer... restTemplateCustomizers) {
Assert.notNull(restTemplateCustomizers,
"RestTemplateCustomizers must not be null");
return customizers(Arrays.asList(restTemplateCustomizers));
} | Set the {@link RestTemplateCustomizer RestTemplateCustomizers} that should be
applied to the {@link RestTemplate}. 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 restTemplateCustomizers the customizers to set
@return a new builder instance
@see #additionalCustomizers(RestTemplateCustomizer...) |
public RestTemplateBuilder customizers(
Collection<? extends RestTemplateCustomizer> restTemplateCustomizers) {
Assert.notNull(restTemplateCustomizers,
"RestTemplateCustomizers must not be null");
return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
this.messageConverters, this.requestFactorySupplier,
this.uriTemplateHandler, this.errorHandler, this.basicAuthentication,
Collections.unmodifiableSet(new LinkedHashSet<RestTemplateCustomizer>(
restTemplateCustomizers)),
this.requestFactoryCustomizer, this.interceptors);
} | Set the {@link RestTemplateCustomizer RestTemplateCustomizers} that should be
applied to the {@link RestTemplate}. 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 restTemplateCustomizers the customizers to set
@return a new builder instance
@see #additionalCustomizers(RestTemplateCustomizer...) |
public RestTemplateBuilder additionalCustomizers(
RestTemplateCustomizer... restTemplateCustomizers) {
Assert.notNull(restTemplateCustomizers,
"RestTemplateCustomizers must not be null");
return additionalCustomizers(Arrays.asList(restTemplateCustomizers));
} | Add {@link RestTemplateCustomizer RestTemplateCustomizers} that should be applied
to the {@link RestTemplate}. Customizers are applied in the order that they were
added after builder configuration has been applied.
@param restTemplateCustomizers the customizers to add
@return a new builder instance
@see #customizers(RestTemplateCustomizer...) |
public RestTemplateBuilder additionalCustomizers(
Collection<? extends RestTemplateCustomizer> customizers) {
Assert.notNull(customizers, "RestTemplateCustomizers must not be null");
return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
this.messageConverters, this.requestFactorySupplier,
this.uriTemplateHandler, this.errorHandler, this.basicAuthentication,
append(this.restTemplateCustomizers, customizers),
this.requestFactoryCustomizer, this.interceptors);
} | Add {@link RestTemplateCustomizer RestTemplateCustomizers} that should be applied
to the {@link RestTemplate}. 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(RestTemplateCustomizer...) |
public RestTemplateBuilder setConnectTimeout(Duration connectTimeout) {
return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
this.messageConverters, this.requestFactorySupplier,
this.uriTemplateHandler, this.errorHandler, this.basicAuthentication,
this.restTemplateCustomizers,
this.requestFactoryCustomizer.connectTimeout(connectTimeout),
this.interceptors);
} | Sets the connection timeout on the underlying {@link ClientHttpRequestFactory}.
@param connectTimeout the connection timeout
@return a new builder instance.
@since 2.1.0 |
public RestTemplateBuilder setReadTimeout(Duration readTimeout) {
return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
this.messageConverters, this.requestFactorySupplier,
this.uriTemplateHandler, this.errorHandler, this.basicAuthentication,
this.restTemplateCustomizers,
this.requestFactoryCustomizer.readTimeout(readTimeout),
this.interceptors);
} | Sets the read timeout on the underlying {@link ClientHttpRequestFactory}.
@param readTimeout the read timeout
@return a new builder instance.
@since 2.1.0 |
public <T extends RestTemplate> T build(Class<T> restTemplateClass) {
return configure(BeanUtils.instantiateClass(restTemplateClass));
} | Build a new {@link RestTemplate} instance of the specified type and configure it
using this builder.
@param <T> the type of rest template
@param restTemplateClass the template type to create
@return a configured {@link RestTemplate} instance.
@see RestTemplateBuilder#build()
@see #configure(RestTemplate) |
public <T extends RestTemplate> T configure(T restTemplate) {
configureRequestFactory(restTemplate);
if (!CollectionUtils.isEmpty(this.messageConverters)) {
restTemplate.setMessageConverters(new ArrayList<>(this.messageConverters));
}
if (this.uriTemplateHandler != null) {
restTemplate.setUriTemplateHandler(this.uriTemplateHandler);
}
if (this.errorHandler != null) {
restTemplate.setErrorHandler(this.errorHandler);
}
if (this.rootUri != null) {
RootUriTemplateHandler.addTo(restTemplate, this.rootUri);
}
if (this.basicAuthentication != null) {
restTemplate.getInterceptors().add(this.basicAuthentication);
}
restTemplate.getInterceptors().addAll(this.interceptors);
if (!CollectionUtils.isEmpty(this.restTemplateCustomizers)) {
for (RestTemplateCustomizer customizer : this.restTemplateCustomizers) {
customizer.customize(restTemplate);
}
}
return restTemplate;
} | Configure the provided {@link RestTemplate} instance using this builder.
@param <T> the type of rest template
@param restTemplate the {@link RestTemplate} to configure
@return the rest template instance
@see RestTemplateBuilder#build()
@see RestTemplateBuilder#build(Class) |
public ConfigurationMetadataRepositoryJsonBuilder withJsonResource(
InputStream inputStream, Charset charset) throws IOException {
if (inputStream == null) {
throw new IllegalArgumentException("InputStream must not be null.");
}
this.repositories.add(add(inputStream, charset));
return this;
} | Add the content of a {@link ConfigurationMetadataRepository} defined by the
specified {@link InputStream} json document using the specified {@link Charset}. If
this metadata repository holds items that were loaded previously, these are
ignored.
<p>
Leaves the stream open when done.
@param inputStream the source input stream
@param charset the charset of the input
@return this builder
@throws IOException in case of I/O errors |
public static ConfigurationMetadataRepositoryJsonBuilder create(
InputStream... inputStreams) throws IOException {
ConfigurationMetadataRepositoryJsonBuilder builder = create();
for (InputStream inputStream : inputStreams) {
builder = builder.withJsonResource(inputStream);
}
return builder;
} | Create a new builder instance using {@link StandardCharsets#UTF_8} as the default
charset and the specified json resource.
@param inputStreams the source input streams
@return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance.
@throws IOException on error |
protected final void configureWebAppContext(WebAppContext context,
ServletContextInitializer... initializers) {
Assert.notNull(context, "Context must not be null");
context.setTempDirectory(getTempDirectory());
if (this.resourceLoader != null) {
context.setClassLoader(this.resourceLoader.getClassLoader());
}
String contextPath = getContextPath();
context.setContextPath(StringUtils.hasLength(contextPath) ? contextPath : "/");
context.setDisplayName(getDisplayName());
configureDocumentRoot(context);
if (isRegisterDefaultServlet()) {
addDefaultServlet(context);
}
if (shouldRegisterJspServlet()) {
addJspServlet(context);
context.addBean(new JasperInitializer(context), true);
}
addLocaleMappings(context);
ServletContextInitializer[] initializersToUse = mergeInitializers(initializers);
Configuration[] configurations = getWebAppContextConfigurations(context,
initializersToUse);
context.setConfigurations(configurations);
context.setThrowUnavailableOnStartupException(true);
configureSession(context);
postProcessWebAppContext(context);
} | Configure the given Jetty {@link WebAppContext} for use.
@param context the context to configure
@param initializers the set of initializers to apply |
protected final void addDefaultServlet(WebAppContext context) {
Assert.notNull(context, "Context must not be null");
ServletHolder holder = new ServletHolder();
holder.setName("default");
holder.setClassName("org.eclipse.jetty.servlet.DefaultServlet");
holder.setInitParameter("dirAllowed", "false");
holder.setInitOrder(1);
context.getServletHandler().addServletWithMapping(holder, "/");
context.getServletHandler().getServletMapping("/").setDefault(true);
} | Add Jetty's {@code DefaultServlet} to the given {@link WebAppContext}.
@param context the jetty {@link WebAppContext} |
protected final void addJspServlet(WebAppContext context) {
Assert.notNull(context, "Context must not be null");
ServletHolder holder = new ServletHolder();
holder.setName("jsp");
holder.setClassName(getJsp().getClassName());
holder.setInitParameter("fork", "false");
holder.setInitParameters(getJsp().getInitParameters());
holder.setInitOrder(3);
context.getServletHandler().addServlet(holder);
ServletMapping mapping = new ServletMapping();
mapping.setServletName("jsp");
mapping.setPathSpecs(new String[] { "*.jsp", "*.jspx" });
context.getServletHandler().addServletMapping(mapping);
} | Add Jetty's {@code JspServlet} to the given {@link WebAppContext}.
@param context the jetty {@link WebAppContext} |
protected Configuration[] getWebAppContextConfigurations(WebAppContext webAppContext,
ServletContextInitializer... initializers) {
List<Configuration> configurations = new ArrayList<>();
configurations.add(
getServletContextInitializerConfiguration(webAppContext, initializers));
configurations.addAll(getConfigurations());
configurations.add(getErrorPageConfiguration());
configurations.add(getMimeTypeConfiguration());
return configurations.toArray(new Configuration[0]);
} | Return the Jetty {@link Configuration}s that should be applied to the server.
@param webAppContext the Jetty {@link WebAppContext}
@param initializers the {@link ServletContextInitializer}s to apply
@return configurations to apply |
private Configuration getErrorPageConfiguration() {
return new AbstractConfiguration() {
@Override
public void configure(WebAppContext context) throws Exception {
ErrorHandler errorHandler = context.getErrorHandler();
context.setErrorHandler(new JettyEmbeddedErrorHandler(errorHandler));
addJettyErrorPages(errorHandler, getErrorPages());
}
};
} | Create a configuration object that adds error handlers.
@return a configuration object for adding error pages |
private Configuration getMimeTypeConfiguration() {
return new AbstractConfiguration() {
@Override
public void configure(WebAppContext context) throws Exception {
MimeTypes mimeTypes = context.getMimeTypes();
for (MimeMappings.Mapping mapping : getMimeMappings()) {
mimeTypes.addMimeMapping(mapping.getExtension(),
mapping.getMimeType());
}
}
};
} | Create a configuration object that adds mime type mappings.
@return a configuration object for adding mime type mappings |
public void setConfigurations(Collection<? extends Configuration> configurations) {
Assert.notNull(configurations, "Configurations must not be null");
this.configurations = new ArrayList<>(configurations);
} | Sets Jetty {@link Configuration}s that will be applied to the {@link WebAppContext}
before the server is created. Calling this method will replace any existing
configurations.
@param configurations the Jetty configurations to apply |
public void addConfigurations(Configuration... configurations) {
Assert.notNull(configurations, "Configurations must not be null");
this.configurations.addAll(Arrays.asList(configurations));
} | Add {@link Configuration}s that will be applied to the {@link WebAppContext} before
the server is started.
@param configurations the configurations to add |
public static Database getDatabase(DataSource dataSource) {
if (dataSource == null) {
return Database.DEFAULT;
}
try {
String url = JdbcUtils.extractDatabaseMetaData(dataSource, "getURL");
DatabaseDriver driver = DatabaseDriver.fromJdbcUrl(url);
Database database = LOOKUP.get(driver);
if (database != null) {
return database;
}
}
catch (MetaDataAccessException ex) {
logger.warn("Unable to determine jdbc url from datasource", ex);
}
return Database.DEFAULT;
} | Return the most suitable {@link Database} for the given {@link DataSource}.
@param dataSource the source {@link DataSource}
@return the most suitable {@link Database} |
public Object nextValue() throws JSONException {
int c = nextCleanInternal();
switch (c) {
case -1:
throw syntaxError("End of input");
case '{':
return readObject();
case '[':
return readArray();
case '\'':
case '"':
return nextString((char) c);
default:
this.pos--;
return readLiteral();
}
} | Returns the next value from the input.
@return a {@link JSONObject}, {@link JSONArray}, String, Boolean, Integer, Long,
Double or {@link JSONObject#NULL}.
@throws JSONException if the input is malformed. |
private void skipToEndOfLine() {
for (; this.pos < this.in.length(); this.pos++) {
char c = this.in.charAt(this.pos);
if (c == '\r' || c == '\n') {
this.pos++;
break;
}
}
} | Advances the position until after the next newline character. If the line is
terminated by "\r\n", the '\n' must be consumed as whitespace by the caller. |
public String nextString(char quote) throws JSONException {
/*
* For strings that are free of escape sequences, we can just extract the result
* as a substring of the input. But if we encounter an escape sequence, we need to
* use a StringBuilder to compose the result.
*/
StringBuilder builder = null;
/* the index of the first character not yet appended to the builder. */
int start = this.pos;
while (this.pos < this.in.length()) {
int c = this.in.charAt(this.pos++);
if (c == quote) {
if (builder == null) {
// a new string avoids leaking memory
return new String(this.in.substring(start, this.pos - 1));
}
else {
builder.append(this.in, start, this.pos - 1);
return builder.toString();
}
}
if (c == '\\') {
if (this.pos == this.in.length()) {
throw syntaxError("Unterminated escape sequence");
}
if (builder == null) {
builder = new StringBuilder();
}
builder.append(this.in, start, this.pos - 1);
builder.append(readEscapeCharacter());
start = this.pos;
}
}
throw syntaxError("Unterminated string");
} | Returns the string up to but not including {@code quote}, unescaping any character
escape sequences encountered along the way. The opening quote should have already
been read. This consumes the closing quote, but does not include it in the returned
string.
@param quote either ' or ".
@return the string up to but not including {@code quote}
@throws NumberFormatException if any unicode escape sequences are malformed.
@throws JSONException if processing of json failed |
private JSONObject readObject() throws JSONException {
JSONObject result = new JSONObject();
/* Peek to see if this is the empty object. */
int first = nextCleanInternal();
if (first == '}') {
return result;
}
else if (first != -1) {
this.pos--;
}
while (true) {
Object name = nextValue();
if (!(name instanceof String)) {
if (name == null) {
throw syntaxError("Names cannot be null");
}
else {
throw syntaxError("Names must be strings, but " + name
+ " is of type " + name.getClass().getName());
}
}
/*
* Expect the name/value separator to be either a colon ':', an equals sign
* '=', or an arrow "=>". The last two are bogus but we include them because
* that's what the original implementation did.
*/
int separator = nextCleanInternal();
if (separator != ':' && separator != '=') {
throw syntaxError("Expected ':' after " + name);
}
if (this.pos < this.in.length() && this.in.charAt(this.pos) == '>') {
this.pos++;
}
result.put((String) name, nextValue());
switch (nextCleanInternal()) {
case '}':
return result;
case ';':
case ',':
continue;
default:
throw syntaxError("Unterminated object");
}
}
} | Reads a sequence of key/value pairs and the trailing closing brace '}' of an
object. The opening brace '{' should have already been read.
@return an object
@throws JSONException if processing of json failed |
private JSONArray readArray() throws JSONException {
JSONArray result = new JSONArray();
/* to cover input that ends with ",]". */
boolean hasTrailingSeparator = false;
while (true) {
switch (nextCleanInternal()) {
case -1:
throw syntaxError("Unterminated array");
case ']':
if (hasTrailingSeparator) {
result.put(null);
}
return result;
case ',':
case ';':
/* A separator without a value first means "null". */
result.put(null);
hasTrailingSeparator = true;
continue;
default:
this.pos--;
}
result.put(nextValue());
switch (nextCleanInternal()) {
case ']':
return result;
case ',':
case ';':
hasTrailingSeparator = true;
continue;
default:
throw syntaxError("Unterminated array");
}
}
} | Reads a sequence of values and the trailing closing brace ']' of an array. The
opening brace '[' should have already been read. Note that "[]" yields an empty
array, but "[,]" returns a two-element array equivalent to "[null,null]".
@return an array
@throws JSONException if processing of json failed |
protected final RedisClusterConfiguration getClusterConfiguration() {
if (this.clusterConfiguration != null) {
return this.clusterConfiguration;
}
if (this.properties.getCluster() == null) {
return null;
}
RedisProperties.Cluster clusterProperties = this.properties.getCluster();
RedisClusterConfiguration config = new RedisClusterConfiguration(
clusterProperties.getNodes());
if (clusterProperties.getMaxRedirects() != null) {
config.setMaxRedirects(clusterProperties.getMaxRedirects());
}
if (this.properties.getPassword() != null) {
config.setPassword(RedisPassword.of(this.properties.getPassword()));
}
return config;
} | Create a {@link RedisClusterConfiguration} if necessary.
@return {@literal null} if no cluster settings are set. |
private boolean hasLombokPublicAccessor(MetadataGenerationEnvironment env,
boolean getter) {
String annotation = (getter ? LOMBOK_GETTER_ANNOTATION
: LOMBOK_SETTER_ANNOTATION);
AnnotationMirror lombokMethodAnnotationOnField = env.getAnnotation(getField(),
annotation);
if (lombokMethodAnnotationOnField != null) {
return isAccessLevelPublic(env, lombokMethodAnnotationOnField);
}
AnnotationMirror lombokMethodAnnotationOnElement = env
.getAnnotation(getOwnerElement(), annotation);
if (lombokMethodAnnotationOnElement != null) {
return isAccessLevelPublic(env, lombokMethodAnnotationOnElement);
}
return (env.getAnnotation(getOwnerElement(), LOMBOK_DATA_ANNOTATION) != null);
} | Determine if the current {@link #getField() field} defines a public accessor using
lombok annotations.
@param env the {@link MetadataGenerationEnvironment}
@param getter {@code true} to look for the read accessor, {@code false} for the
write accessor
@return {@code true} if this field has a public accessor of the specified type |
public MultipartConfigElement createMultipartConfig() {
MultipartConfigFactory factory = new MultipartConfigFactory();
PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
map.from(this.fileSizeThreshold).to(factory::setFileSizeThreshold);
map.from(this.location).whenHasText().to(factory::setLocation);
map.from(this.maxRequestSize).to(factory::setMaxRequestSize);
map.from(this.maxFileSize).to(factory::setMaxFileSize);
return factory.createMultipartConfig();
} | Create a new {@link MultipartConfigElement} using the properties.
@return a new {@link MultipartConfigElement} configured using there properties |
public static List<RepositoryConfiguration> createDefaultRepositoryConfiguration() {
MavenSettings mavenSettings = new MavenSettingsReader().readSettings();
List<RepositoryConfiguration> repositoryConfiguration = new ArrayList<>();
repositoryConfiguration.add(MAVEN_CENTRAL);
if (!Boolean.getBoolean("disableSpringSnapshotRepos")) {
repositoryConfiguration.add(SPRING_MILESTONE);
repositoryConfiguration.add(SPRING_SNAPSHOT);
}
addDefaultCacheAsRepository(mavenSettings.getLocalRepository(),
repositoryConfiguration);
addActiveProfileRepositories(mavenSettings.getActiveProfiles(),
repositoryConfiguration);
return repositoryConfiguration;
} | Create a new default repository configuration.
@return the newly-created default repository configuration |
protected AutoConfigurationEntry getAutoConfigurationEntry(
AutoConfigurationMetadata autoConfigurationMetadata,
AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
}
AnnotationAttributes attributes = getAttributes(annotationMetadata);
List<String> configurations = getCandidateConfigurations(annotationMetadata,
attributes);
configurations = removeDuplicates(configurations);
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = filter(configurations, autoConfigurationMetadata);
fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationEntry(configurations, exclusions);
} | Return the {@link AutoConfigurationEntry} based on the {@link AnnotationMetadata}
of the importing {@link Configuration @Configuration} class.
@param autoConfigurationMetadata the auto-configuration metadata
@param annotationMetadata the annotation metadata of the configuration class
@return the auto-configurations that should be imported |
protected AnnotationAttributes getAttributes(AnnotationMetadata metadata) {
String name = getAnnotationClass().getName();
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(metadata.getAnnotationAttributes(name, true));
Assert.notNull(attributes,
() -> "No auto-configuration attributes found. Is "
+ metadata.getClassName() + " annotated with "
+ ClassUtils.getShortName(name) + "?");
return attributes;
} | Return the appropriate {@link AnnotationAttributes} from the
{@link AnnotationMetadata}. By default this method will return attributes for
{@link #getAnnotationClass()}.
@param metadata the annotation metadata
@return annotation attributes |
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
Assert.notEmpty(configurations,
"No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
} | Return the auto-configuration class names that should be considered. By default
this method will load candidates using {@link SpringFactoriesLoader} with
{@link #getSpringFactoriesLoaderFactoryClass()}.
@param metadata the source metadata
@param attributes the {@link #getAttributes(AnnotationMetadata) annotation
attributes}
@return a list of candidate configurations |
protected void handleInvalidExcludes(List<String> invalidExcludes) {
StringBuilder message = new StringBuilder();
for (String exclude : invalidExcludes) {
message.append("\t- ").append(exclude).append(String.format("%n"));
}
throw new IllegalStateException(String
.format("The following classes could not be excluded because they are"
+ " not auto-configuration classes:%n%s", message));
} | Handle any invalid excludes that have been specified.
@param invalidExcludes the list of invalid excludes (will always have at least one
element) |
protected Set<String> getExclusions(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
Set<String> excluded = new LinkedHashSet<>();
excluded.addAll(asList(attributes, "exclude"));
excluded.addAll(Arrays.asList(attributes.getStringArray("excludeName")));
excluded.addAll(getExcludeAutoConfigurationsProperty());
return excluded;
} | Return any exclusions that limit the candidate configurations.
@param metadata the source metadata
@param attributes the {@link #getAttributes(AnnotationMetadata) annotation
attributes}
@return exclusions or an empty set |
protected Configurations merge(Configurations other) {
Set<Class<?>> mergedClasses = new LinkedHashSet<>(getClasses());
mergedClasses.addAll(other.getClasses());
return merge(mergedClasses);
} | Merge configurations from another source of the same type.
@param other the other {@link Configurations} (must be of the same type as this
instance)
@return a new configurations instance (must be of the same type as this instance) |
public static Class<?>[] getClasses(Collection<Configurations> configurations) {
List<Configurations> ordered = new ArrayList<>(configurations);
ordered.sort(COMPARATOR);
List<Configurations> collated = collate(ordered);
LinkedHashSet<Class<?>> classes = collated.stream()
.flatMap(Configurations::streamClasses)
.collect(Collectors.toCollection(LinkedHashSet::new));
return ClassUtils.toClassArray(classes);
} | Return the classes from all the specified configurations in the order that they
would be registered.
@param configurations the source configuration
@return configuration classes in registration order |
public Map<String, Link> resolveLinks(String requestUrl) {
String normalizedUrl = normalizeRequestUrl(requestUrl);
Map<String, Link> links = new LinkedHashMap<>();
links.put("self", new Link(normalizedUrl));
for (ExposableEndpoint<?> endpoint : this.endpoints) {
if (endpoint instanceof ExposableWebEndpoint) {
collectLinks(links, (ExposableWebEndpoint) endpoint, normalizedUrl);
}
else if (endpoint instanceof PathMappedEndpoint) {
String rootPath = ((PathMappedEndpoint) endpoint).getRootPath();
Link link = createLink(normalizedUrl, rootPath);
links.put(endpoint.getEndpointId().toLowerCaseString(), link);
}
}
return links;
} | Resolves links to the known endpoints based on a request with the given
{@code requestUrl}.
@param requestUrl the url of the request for the endpoint links
@return the links |
static void addToRootFileCache(File sourceFile, JarFile jarFile) {
Map<File, JarFile> cache = rootFileCache.get();
if (cache == null) {
cache = new ConcurrentHashMap<>();
rootFileCache = new SoftReference<>(cache);
}
cache.put(sourceFile, jarFile);
} | Add the given {@link JarFile} to the root file cache.
@param sourceFile the source file to add
@param jarFile the jar file. |
protected UndertowServletWebServer getUndertowWebServer(Builder builder,
DeploymentManager manager, int port) {
return new UndertowServletWebServer(builder, manager, getContextPath(),
isUseForwardHeaders(), port >= 0, getCompression(), getServerHeader());
} | Factory method called to create the {@link UndertowServletWebServer}. Subclasses
can override this method to return a different {@link UndertowServletWebServer} or
apply additional processing to the {@link Builder} and {@link DeploymentManager}
used to bootstrap Undertow
@param builder the builder
@param manager the deployment manager
@param port the port that Undertow should listen on
@return a new {@link UndertowServletWebServer} instance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.