updatee the azure web adapter

This commit is contained in:
Christian Tzolov
2023-03-10 08:04:23 +01:00
parent 78f20ddf67
commit 0d91490875
12 changed files with 27 additions and 2532 deletions

View File

@@ -17,8 +17,6 @@
<modules>
<module>spring-cloud-function-adapter-aws</module>
<module>spring-cloud-function-adapter-aws-web</module>
<module>spring-cloud-function-adapter-azure-web</module>
<module>spring-cloud-function-adapter-azure-web/sample/pet-store</module>
<module>spring-cloud-function-adapter-azure</module>
<module>spring-cloud-function-adapter-gcp</module>
@@ -26,6 +24,7 @@
<module>spring-cloud-function-grpc-cloudevent-ext</module>
<module>spring-cloud-function-serverless-web</module>
<module>spring-cloud-function-adapter-aws-web</module>
<module>spring-cloud-function-adapter-azure-web</module>
</modules>
</project>

View File

@@ -9,7 +9,7 @@
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-adapter-parent</artifactId>
<version>3.2.9-SNAPSHOT</version>
<version>3.2.10-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@@ -24,6 +24,10 @@
<artifactId>annotations</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-serverless-web</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.azure.functions</groupId>
<artifactId>azure-functions-java-library</artifactId>

View File

@@ -48,7 +48,7 @@
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-adapter-azure-web</artifactId>
<version>3.2.9-SNAPSHOT</version>
<version>3.2.10-SNAPSHOT</version>
</dependency>
<!--
the Spring Context Indexer run an annotation processor at compile time and generates

View File

@@ -16,19 +16,13 @@
package org.springframework.cloud.function.adapter.azure.web;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map.Entry;
import java.util.Optional;
import javax.servlet.Filter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.azure.functions.ExecutionContext;
import com.microsoft.azure.functions.HttpMethod;
import com.microsoft.azure.functions.HttpRequestMessage;
@@ -42,14 +36,11 @@ import com.microsoft.azure.functions.spi.inject.FunctionInstanceInjector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.function.serverless.web.ProxyHttpServletRequest;
import org.springframework.cloud.function.serverless.web.ProxyHttpServletResponse;
import org.springframework.cloud.function.serverless.web.ProxyMvc;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.ProxyHttpServletRequest;
import org.springframework.web.client.ProxyHttpServletResponse;
import org.springframework.web.client.ProxyMvc;
import org.springframework.web.client.ProxyServletContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
*
@@ -61,15 +52,17 @@ public class AzureWebProxyInvoker implements FunctionInstanceInjector {
private static Log logger = LogFactory.getLog(AzureWebProxyInvoker.class);
private static final String AZURE_WEB_ADAPTER_NAME = "AzureWebAdapter";
private static final String AZURE_WEB_ADAPTER_ROUTE = AZURE_WEB_ADAPTER_NAME
+ "/{e?}/{e2?}/{e3?}/{e4?}/{e5?}/{e6?}/{e7?}/{e8?}/{e9?}/{e10?}/{e11?}/{e12?}/{e13?}/{e14?}/{e15?}";
private ProxyMvc mvc;
private ServletContext servletContext;
ObjectMapper mapper = new ObjectMapper();
@Override
public <T> T getInstance(Class<T> functionClass) throws Exception {
// System.setProperty("MAIN_CLASS", "oz.spring.petstore.PetStoreSpringAppConfig");
// System.setProperty("MAIN_CLASS", "oz.spring.petstore.PetStoreSpringAppConfig");
this.initialize();
return (T) this;
}
@@ -81,31 +74,19 @@ public class AzureWebProxyInvoker implements FunctionInstanceInjector {
*/
private void initialize() throws ServletException {
synchronized (AzureWebProxyInvoker.class.getName()) {
if (this.servletContext == null) {
if (mvc == null) {
Class<?> startClass = FunctionClassUtils.getStartClass();
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.register(startClass);
this.servletContext = new ProxyServletContext();
ServletConfig servletConfig = new ProxyServletConfig(this.servletContext);
DispatcherServlet servlet = new DispatcherServlet(applicationContext);
servlet.init(servletConfig);
this.mvc = new ProxyMvc(servlet,
applicationContext.getBeansOfType(Filter.class).values().toArray(new Filter[0]));
this.mvc = ProxyMvc.INSTANCE(startClass);
}
}
}
private HttpServletRequest prepareRequest(HttpRequestMessage<Optional<String>> request) {
// Note: Currently this is the only way to pass the the application
// route (e.g. the execution REST url)
String path = request.getQueryParameters().get("path");
int pathOffset = request.getUri().getPath().indexOf(AZURE_WEB_ADAPTER_NAME) + AZURE_WEB_ADAPTER_NAME.length();
String path = request.getUri().getPath().substring(pathOffset);
if (!StringUtils.hasText(path)) {
throw new IllegalStateException("Missing path parameter");
}
ProxyHttpServletRequest httpRequest = new ProxyHttpServletRequest(servletContext,
request.getHttpMethod().toString(), path);
@@ -126,10 +107,10 @@ public class AzureWebProxyInvoker implements FunctionInstanceInjector {
return httpRequest;
}
@FunctionName("AzureWebAdapter")
@FunctionName(AZURE_WEB_ADAPTER_NAME)
public HttpResponseMessage execute(
@HttpTrigger(name = "req", methods = { HttpMethod.GET,
HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS, route = AZURE_WEB_ADAPTER_ROUTE) HttpRequestMessage<Optional<String>> request,
ExecutionContext context) {
context.getLogger().info("Request body is: " + request.getBody().orElse("[empty]"));
@@ -138,7 +119,7 @@ public class AzureWebProxyInvoker implements FunctionInstanceInjector {
ProxyHttpServletResponse httpResponse = new ProxyHttpServletResponse();
try {
this.mvc.perform(httpRequest, httpResponse);
this.mvc.service(httpRequest, httpResponse);
Builder responseBuilder = request.createResponseBuilder(HttpStatus.OK);
for (String headerName : httpResponse.getHeaderNames()) {
@@ -161,33 +142,4 @@ public class AzureWebProxyInvoker implements FunctionInstanceInjector {
}
}
private static class ProxyServletConfig implements ServletConfig {
private final ServletContext servletContext;
ProxyServletConfig(ServletContext servletContext) {
this.servletContext = servletContext;
}
@Override
public String getServletName() {
return "serverless-proxy";
}
@Override
public ServletContext getServletContext() {
return this.servletContext;
}
@Override
public Enumeration<String> getInitParameterNames() {
return Collections.enumeration(new ArrayList<String>());
}
@Override
public String getInitParameter(String name) {
return null;
}
}
}

View File

@@ -1,78 +0,0 @@
/*
* Copyright 2023-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.client;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
class HeaderValueHolder {
private final List<Object> values = new LinkedList<>();
void setValue(@Nullable Object value) {
this.values.clear();
if (value != null) {
this.values.add(value);
}
}
void addValue(Object value) {
this.values.add(value);
}
void addValues(Collection<?> values) {
this.values.addAll(values);
}
void addValueArray(Object values) {
CollectionUtils.mergeArrayIntoCollection(values, this.values);
}
List<Object> getValues() {
return Collections.unmodifiableList(this.values);
}
List<String> getStringValues() {
List<String> stringList = new ArrayList<>(this.values.size());
for (Object value : this.values) {
stringList.add(value.toString());
}
return Collections.unmodifiableList(stringList);
}
@Nullable
Object getValue() {
return (!this.values.isEmpty() ? this.values.get(0) : null);
}
@Nullable
String getStringValue() {
return (!this.values.isEmpty() ? String.valueOf(this.values.get(0)) : null);
}
@Override
public String toString() {
return this.values.toString();
}
}

View File

@@ -1,601 +0,0 @@
/*
* Copyright 2023-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.client;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.springframework.web.util.WebUtils;
public class ProxyHttpServletResponse implements HttpServletResponse {
private static final String CHARSET_PREFIX = "charset=";
private static final String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";
private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
// ---------------------------------------------------------------------
// ServletResponse properties
// ---------------------------------------------------------------------
private boolean outputStreamAccessAllowed = true;
private String defaultCharacterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING;
private String characterEncoding = this.defaultCharacterEncoding;
/**
* {@code true} if the character encoding has been explicitly set through
* {@link HttpServletResponse} methods or through a {@code charset} parameter on
* the {@code Content-Type}.
*/
private boolean characterEncodingSet = false;
private final ByteArrayOutputStream content = new ByteArrayOutputStream(1024);
private final ServletOutputStream outputStream = new ResponseServletOutputStream();
private long contentLength = 0;
private String contentType;
private int bufferSize = 4096;
private boolean committed;
private Locale locale = Locale.getDefault();
// ---------------------------------------------------------------------
// HttpServletResponse properties
// ---------------------------------------------------------------------
private final List<Cookie> cookies = new ArrayList<>();
private final Map<String, HeaderValueHolder> headers = new LinkedCaseInsensitiveMap<>();
private int status = HttpServletResponse.SC_OK;
@Nullable
private String errorMessage;
// ---------------------------------------------------------------------
// ServletResponse interface
// ---------------------------------------------------------------------
@Override
public void setCharacterEncoding(String characterEncoding) {
setExplicitCharacterEncoding(characterEncoding);
updateContentTypePropertyAndHeader();
}
private void setExplicitCharacterEncoding(String characterEncoding) {
Assert.notNull(characterEncoding, "'characterEncoding' must not be null");
this.characterEncoding = characterEncoding;
this.characterEncodingSet = true;
}
private void updateContentTypePropertyAndHeader() {
if (this.contentType != null) {
String value = this.contentType;
if (this.characterEncodingSet && !value.toLowerCase().contains(CHARSET_PREFIX)) {
value += ';' + CHARSET_PREFIX + getCharacterEncoding();
this.contentType = value;
}
doAddHeaderValue(HttpHeaders.CONTENT_TYPE, value, true);
}
}
@Override
public String getCharacterEncoding() {
return this.characterEncoding;
}
@Override
public ServletOutputStream getOutputStream() {
Assert.state(this.outputStreamAccessAllowed, "OutputStream access not allowed");
return this.outputStream;
}
@Override
public PrintWriter getWriter() throws UnsupportedEncodingException {
throw new UnsupportedOperationException();
}
public byte[] getContentAsByteArray() {
return this.content.toByteArray();
}
/**
* Get the content of the response body as a {@code String}, using the charset
* specified for the response by the application, either through
* {@link HttpServletResponse} methods or through a charset parameter on the
* {@code Content-Type}. If no charset has been explicitly defined, the
* {@linkplain #setDefaultCharacterEncoding(String) default character encoding}
* will be used.
*
* @return the content as a {@code String}
* @throws UnsupportedEncodingException if the character encoding is not
* supported
* @see #getContentAsString(Charset)
* @see #setCharacterEncoding(String)
* @see #setContentType(String)
*/
public String getContentAsString() throws UnsupportedEncodingException {
return this.content.toString(getCharacterEncoding());
}
/**
* Get the content of the response body as a {@code String}, using the provided
* {@code fallbackCharset} if no charset has been explicitly defined and
* otherwise using the charset specified for the response by the application,
* either through {@link HttpServletResponse} methods or through a charset
* parameter on the {@code Content-Type}.
*
* @return the content as a {@code String}
* @throws UnsupportedEncodingException if the character encoding is not
* supported
* @since 5.2
* @see #getContentAsString()
* @see #setCharacterEncoding(String)
* @see #setContentType(String)
*/
public String getContentAsString(Charset fallbackCharset) throws UnsupportedEncodingException {
String charsetName = (this.characterEncodingSet ? getCharacterEncoding() : fallbackCharset.name());
return this.content.toString(charsetName);
}
@Override
public void setContentLength(int contentLength) {
throw new UnsupportedOperationException();
}
@Override
public void setContentLengthLong(long len) {
throw new UnsupportedOperationException();
}
@Override
public void setContentType(@Nullable String contentType) {
this.contentType = contentType;
}
@Override
@Nullable
public String getContentType() {
return this.contentType;
}
@Override
public void setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
}
@Override
public int getBufferSize() {
return this.bufferSize;
}
@Override
public void flushBuffer() {
}
@Override
public void resetBuffer() {
Assert.state(!isCommitted(), "Cannot reset buffer - response is already committed");
this.content.reset();
}
public void setCommitted(boolean committed) {
this.committed = committed;
}
@Override
public boolean isCommitted() {
return this.committed;
}
@Override
public void reset() {
resetBuffer();
this.characterEncoding = this.defaultCharacterEncoding;
this.characterEncodingSet = false;
this.contentLength = 0;
this.contentType = null;
this.locale = Locale.getDefault();
this.cookies.clear();
this.headers.clear();
this.status = HttpServletResponse.SC_OK;
this.errorMessage = null;
}
@Override
public void setLocale(@Nullable Locale locale) {
// Although the Javadoc for javax.servlet.ServletResponse.setLocale(Locale) does
// not
// state how a null value for the supplied Locale should be handled, both Tomcat
// and
// Jetty simply ignore a null value. So we do the same here.
if (locale == null) {
return;
}
this.locale = locale;
doAddHeaderValue(HttpHeaders.CONTENT_LANGUAGE, locale.toLanguageTag(), true);
}
@Override
public Locale getLocale() {
return this.locale;
}
// ---------------------------------------------------------------------
// HttpServletResponse interface
// ---------------------------------------------------------------------
@Override
public void addCookie(Cookie cookie) {
throw new UnsupportedOperationException();
}
@Nullable
public Cookie getCookie(String name) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsHeader(String name) {
return this.headers.containsKey(name);
}
/**
* Return the names of all specified headers as a Set of Strings.
* <p>
* As of Servlet 3.0, this method is also defined in
* {@link HttpServletResponse}.
*
* @return the {@code Set} of header name {@code Strings}, or an empty
* {@code Set} if none
*/
@Override
public Collection<String> getHeaderNames() {
return this.headers.keySet();
}
/**
* Return the primary value for the given header as a String, if any. Will
* return the first value in case of multiple values.
* <p>
* As of Servlet 3.0, this method is also defined in
* {@link HttpServletResponse}. As of Spring 3.1, it returns a stringified value
* for Servlet 3.0 compatibility. Consider using {@link #getHeaderValue(String)}
* for raw Object access.
*
* @param name the name of the header
* @return the associated header value, or {@code null} if none
*/
@Override
@Nullable
public String getHeader(String name) {
HeaderValueHolder header = this.headers.get(name);
return (header != null ? header.getStringValue() : null);
}
/**
* Return all values for the given header as a List of Strings.
* <p>
* As of Servlet 3.0, this method is also defined in
* {@link HttpServletResponse}. As of Spring 3.1, it returns a List of
* stringified values for Servlet 3.0 compatibility. Consider using
* {@link #getHeaderValues(String)} for raw Object access.
*
* @param name the name of the header
* @return the associated header values, or an empty List if none
*/
@Override
public List<String> getHeaders(String name) {
HeaderValueHolder header = this.headers.get(name);
if (header != null) {
return header.getStringValues();
}
else {
return Collections.emptyList();
}
}
/**
* Return the primary value for the given header, if any.
* <p>
* Will return the first value in case of multiple values.
*
* @param name the name of the header
* @return the associated header value, or {@code null} if none
*/
@Nullable
public Object getHeaderValue(String name) {
HeaderValueHolder header = this.headers.get(name);
return (header != null ? header.getValue() : null);
}
/**
* Return all values for the given header as a List of value objects.
*
* @param name the name of the header
* @return the associated header values, or an empty List if none
*/
public List<Object> getHeaderValues(String name) {
HeaderValueHolder header = this.headers.get(name);
if (header != null) {
return header.getValues();
}
else {
return Collections.emptyList();
}
}
/**
* The default implementation returns the given URL String as-is.
* <p>
* Can be overridden in subclasses, appending a session id or the like.
*/
@Override
public String encodeURL(String url) {
return url;
}
/**
* The default implementation delegates to {@link #encodeURL}, returning the
* given URL String as-is.
* <p>
* Can be overridden in subclasses, appending a session id or the like in a
* redirect-specific fashion. For general URL encoding rules, override the
* common {@link #encodeURL} method instead, applying to redirect URLs as well
* as to general URLs.
*/
@Override
public String encodeRedirectURL(String url) {
return encodeURL(url);
}
@Override
@Deprecated
public String encodeUrl(String url) {
return encodeURL(url);
}
@Override
@Deprecated
public String encodeRedirectUrl(String url) {
return encodeRedirectURL(url);
}
@Override
public void sendError(int status, String errorMessage) throws IOException {
Assert.state(!isCommitted(), "Cannot set error status - response is already committed");
this.status = status;
this.errorMessage = errorMessage;
setCommitted(true);
}
@Override
public void sendError(int status) throws IOException {
Assert.state(!isCommitted(), "Cannot set error status - response is already committed");
this.status = status;
setCommitted(true);
}
@Override
public void sendRedirect(String url) throws IOException {
Assert.state(!isCommitted(), "Cannot send redirect - response is already committed");
Assert.notNull(url, "Redirect URL must not be null");
setHeader(HttpHeaders.LOCATION, url);
setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
setCommitted(true);
}
@Nullable
public String getRedirectedUrl() {
return getHeader(HttpHeaders.LOCATION);
}
@Override
public void setDateHeader(String name, long value) {
setHeaderValue(name, formatDate(value));
}
@Override
public void addDateHeader(String name, long value) {
addHeaderValue(name, formatDate(value));
}
public long getDateHeader(String name) {
String headerValue = getHeader(name);
if (headerValue == null) {
return -1;
}
try {
return newDateFormat().parse(getHeader(name)).getTime();
}
catch (ParseException ex) {
throw new IllegalArgumentException("Value for header '" + name + "' is not a valid Date: " + headerValue);
}
}
private String formatDate(long date) {
return newDateFormat().format(new Date(date));
}
private DateFormat newDateFormat() {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US);
dateFormat.setTimeZone(GMT);
return dateFormat;
}
@Override
public void setHeader(String name, @Nullable String value) {
setHeaderValue(name, value);
}
@Override
public void addHeader(String name, @Nullable String value) {
addHeaderValue(name, value);
}
@Override
public void setIntHeader(String name, int value) {
setHeaderValue(name, value);
}
@Override
public void addIntHeader(String name, int value) {
addHeaderValue(name, value);
}
private void setHeaderValue(String name, @Nullable Object value) {
if (value == null) {
return;
}
boolean replaceHeader = true;
doAddHeaderValue(name, value, replaceHeader);
}
private void addHeaderValue(String name, @Nullable Object value) {
if (value == null) {
return;
}
boolean replaceHeader = false;
doAddHeaderValue(name, value, replaceHeader);
}
private void doAddHeaderValue(String name, Object value, boolean replace) {
Assert.notNull(value, "Header value must not be null");
HeaderValueHolder header = this.headers.computeIfAbsent(name, key -> new HeaderValueHolder());
if (replace) {
header.setValue(value);
}
else {
header.addValue(value);
}
}
@Override
public void setStatus(int status) {
if (!this.isCommitted()) {
this.status = status;
}
}
@Override
@Deprecated
public void setStatus(int status, String errorMessage) {
throw new UnsupportedOperationException();
}
@Override
public int getStatus() {
return this.status;
}
@Nullable
public String getErrorMessage() {
return this.errorMessage;
}
// ---------------------------------------------------------------------
// Methods for MockRequestDispatcher
// ---------------------------------------------------------------------
@Nullable
public String getForwardedUrl() {
throw new UnsupportedOperationException();
}
@Nullable
public String getIncludedUrl() {
throw new UnsupportedOperationException();
}
/**
* Inner class that adapts the ServletOutputStream to mark the response as
* committed once the buffer size is exceeded.
*/
private class ResponseServletOutputStream extends ServletOutputStream {
private WriteListener listener;
@Override
public boolean isReady() {
return true;
}
@Override
public void setWriteListener(WriteListener writeListener) {
if (writeListener != null) {
try {
writeListener.onWritePossible();
}
catch (IOException e) {
// log.error("Output stream is not writable", e);
}
listener = writeListener;
}
}
@Override
public void write(int b) throws IOException {
try {
content.write(b);
}
catch (Exception e) {
if (listener != null) {
listener.onError(e);
}
}
}
@Override
public void close() throws IOException {
super.close();
flushBuffer();
}
}
}

View File

@@ -1,214 +0,0 @@
/*
* Copyright 2023-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.client;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.DispatcherServlet;
public class ProxyMvc {
static final String MVC_RESULT_ATTRIBUTE = ProxyMvc.class.getName().concat(".MVC_RESULT_ATTRIBUTE");
private final DispatcherServlet servlet;
private final Filter[] filters;
@Nullable
private Charset defaultResponseCharacterEncoding;
/**
* Private constructor, not for direct instantiation.
*
* @see org.springframework.test.web.servlet.setup.MockMvcBuilders
*/
public ProxyMvc(DispatcherServlet servlet, Filter... filters) {
Assert.notNull(servlet, "DispatcherServlet is required");
Assert.notNull(filters, "Filters cannot be null");
Assert.noNullElements(filters, "Filters cannot contain null values");
this.servlet = servlet;
this.filters = filters;
}
/**
* The default character encoding to be applied to every response.
*
* @see org.springframework.test.web.servlet.setup.ConfigurableMockMvcBuilder#defaultResponseCharacterEncoding(Charset)
*/
void setDefaultResponseCharacterEncoding(@Nullable Charset defaultResponseCharacterEncoding) {
this.defaultResponseCharacterEncoding = defaultResponseCharacterEncoding;
}
/**
* Return the underlying {@link DispatcherServlet} instance that this
* {@code MockMvc} was initialized with.
* <p>
* This is intended for use in custom request processing scenario where a
* request handling component happens to delegate to the
* {@code DispatcherServlet} at runtime and therefore needs to be injected with
* it.
* <p>
* For most processing scenarios, simply use {@link MockMvc#perform}, or if you
* need to configure the {@code DispatcherServlet}, provide a
* {@link DispatcherServletCustomizer} to the {@code MockMvcBuilder}.
*
* @since 5.1
*/
public DispatcherServlet getDispatcherServlet() {
return this.servlet;
}
/**
* Perform a request and return a type that allows chaining further actions,
* such as asserting expectations, on the result.
*
* @param requestBuilder used to prepare the request to execute; see static
* factory methods in
* {@link org.springframework.test.web.servlet.request.MockMvcRequestBuilders}
* @return an instance of {@link ResultActions} (never {@code null})
* @see org.springframework.test.web.servlet.request.MockMvcRequestBuilders
* @see org.springframework.test.web.servlet.result.MockMvcResultMatchers
*/
public void perform(HttpServletRequest request, HttpServletResponse response) throws Exception {
ProxyFilterChain filterChain = new ProxyFilterChain(this.servlet, this.filters);
filterChain.doFilter(request, response);
}
private static class ProxyFilterChain implements FilterChain {
@Nullable
private ServletRequest request;
@Nullable
private ServletResponse response;
private final List<Filter> filters;
@Nullable
private Iterator<Filter> iterator;
/**
* Create a {@code FilterChain} with Filter's and a Servlet.
*
* @param servlet the {@link Servlet} to invoke in this {@link FilterChain}
* @param filters the {@link Filter}'s to invoke in this {@link FilterChain}
* @since 3.2
*/
ProxyFilterChain(Servlet servlet, Filter... filters) {
Assert.notNull(filters, "filters cannot be null");
Assert.noNullElements(filters, "filters cannot contain null values");
this.filters = initFilterList(servlet, filters);
}
private static List<Filter> initFilterList(Servlet servlet, Filter... filters) {
Filter[] allFilters = ObjectUtils.addObjectToArray(filters, new ServletFilterProxy(servlet));
return Arrays.asList(allFilters);
}
/**
* Return the request that {@link #doFilter} has been called with.
*/
@Nullable
public ServletRequest getRequest() {
return this.request;
}
/**
* Return the response that {@link #doFilter} has been called with.
*/
@Nullable
public ServletResponse getResponse() {
return this.response;
}
/**
* Invoke registered {@link Filter Filters} and/or {@link Servlet} also saving
* the request and response.
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
Assert.notNull(request, "Request must not be null");
Assert.notNull(response, "Response must not be null");
Assert.state(this.request == null, "This FilterChain has already been called!");
if (this.iterator == null) {
this.iterator = this.filters.iterator();
}
if (this.iterator.hasNext()) {
Filter nextFilter = this.iterator.next();
nextFilter.doFilter(request, response, this);
}
this.request = request;
this.response = response;
}
/**
* A filter that simply delegates to a Servlet.
*/
private static final class ServletFilterProxy implements Filter {
private final Servlet delegateServlet;
private ServletFilterProxy(Servlet servlet) {
Assert.notNull(servlet, "servlet cannot be null");
this.delegateServlet = servlet;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
this.delegateServlet.service(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public String toString() {
return this.delegateServlet.toString();
}
}
}
}

View File

@@ -1,397 +0,0 @@
/*
* Copyright 2023-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.client;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.ServletRegistration.Dynamic;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;
import javax.servlet.descriptor.JspConfigDescriptor;
public class ProxyServletContext implements ServletContext {
@Override
public Enumeration<String> getInitParameterNames() {
List<String> arrlist = new ArrayList<String>();
return Collections.enumeration(arrlist);
}
@Override
public Enumeration<String> getAttributeNames() {
List<String> arrlist = new ArrayList<String>();
return Collections.enumeration(arrlist);
}
@Override
public String getContextPath() {
// TODO Auto-generated method stub
return null;
}
@Override
public ServletContext getContext(String uripath) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getMajorVersion() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getMinorVersion() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getEffectiveMajorVersion() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getEffectiveMinorVersion() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getMimeType(String file) {
// TODO Auto-generated method stub
return null;
}
@Override
public Set<String> getResourcePaths(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public URL getResource(String path) throws MalformedURLException {
// TODO Auto-generated method stub
return null;
}
@Override
public InputStream getResourceAsStream(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public RequestDispatcher getNamedDispatcher(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public Servlet getServlet(String name) throws ServletException {
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration<Servlet> getServlets() {
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration<String> getServletNames() {
// TODO Auto-generated method stub
return null;
}
@Override
public void log(String msg) {
// TODO Auto-generated method stub
}
@Override
public void log(Exception exception, String msg) {
// TODO Auto-generated method stub
}
@Override
public void log(String message, Throwable throwable) {
// TODO Auto-generated method stub
}
@Override
public String getRealPath(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServerInfo() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getInitParameter(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
// TODO Auto-generated method stub
return false;
}
@Override
public Object getAttribute(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public void setAttribute(String name, Object object) {
// TODO Auto-generated method stub
}
@Override
public void removeAttribute(String name) {
// TODO Auto-generated method stub
}
@Override
public String getServletContextName() {
// TODO Auto-generated method stub
return null;
}
@Override
public Dynamic addServlet(String servletName, String className) {
// TODO Auto-generated method stub
return null;
}
@Override
public Dynamic addServlet(String servletName, Servlet servlet) {
// TODO Auto-generated method stub
return null;
}
@Override
public Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) {
// TODO Auto-generated method stub
return null;
}
@Override
public Dynamic addJspFile(String jspName, String jspFile) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T extends Servlet> T createServlet(Class<T> c) throws ServletException {
// TODO Auto-generated method stub
return null;
}
@Override
public ServletRegistration getServletRegistration(String servletName) {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<String, ? extends ServletRegistration> getServletRegistrations() {
// TODO Auto-generated method stub
return null;
}
@Override
public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, String className) {
// TODO Auto-generated method stub
return null;
}
@Override
public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {
// TODO Auto-generated method stub
return null;
}
@Override
public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T extends Filter> T createFilter(Class<T> c) throws ServletException {
// TODO Auto-generated method stub
return null;
}
@Override
public FilterRegistration getFilterRegistration(String filterName) {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<String, ? extends FilterRegistration> getFilterRegistrations() {
// TODO Auto-generated method stub
return null;
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes) {
// TODO Auto-generated method stub
}
@Override
public Set<javax.servlet.SessionTrackingMode> getDefaultSessionTrackingModes() {
// TODO Auto-generated method stub
return null;
}
@Override
public Set<javax.servlet.SessionTrackingMode> getEffectiveSessionTrackingModes() {
// TODO Auto-generated method stub
return null;
}
@Override
public void addListener(String className) {
// TODO Auto-generated method stub
}
@Override
public <T extends EventListener> void addListener(T t) {
// TODO Auto-generated method stub
}
@Override
public void addListener(Class<? extends EventListener> listenerClass) {
// TODO Auto-generated method stub
}
@Override
public <T extends EventListener> T createListener(Class<T> c) throws ServletException {
// TODO Auto-generated method stub
return null;
}
@Override
public JspConfigDescriptor getJspConfigDescriptor() {
// TODO Auto-generated method stub
return null;
}
@Override
public ClassLoader getClassLoader() {
// TODO Auto-generated method stub
return null;
}
@Override
public void declareRoles(String... roleNames) {
// TODO Auto-generated method stub
}
@Override
public String getVirtualServerName() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getSessionTimeout() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setSessionTimeout(int sessionTimeout) {
// TODO Auto-generated method stub
}
@Override
public String getRequestCharacterEncoding() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setRequestCharacterEncoding(String encoding) {
// TODO Auto-generated method stub
}
@Override
public String getResponseCharacterEncoding() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setResponseCharacterEncoding(String encoding) {
// TODO Auto-generated method stub
}
}

View File

@@ -1,3 +0,0 @@
Classes in this package should ideally reside in spring-web somewhere as a light weight HTTP proxy, since they are independent of the
context of the execution (i.e., AWS or Azure or whatever).
In fact classes in these package is a slimed-down copy of similar classes in MockMVC.

View File

@@ -17,7 +17,6 @@
package org.springframework.cloud.function.adapter.azure.web;
import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
@@ -41,7 +40,9 @@ public class AzureWebProxyInvokerTests {
HttpRequestMessageStub<Optional<String>> request = new HttpRequestMessageStub<Optional<String>>();
request.setHttpMethod(HttpMethod.GET);
request.setQueryParameters(Collections.singletonMap("path", "/pets"));
request.setUri(new URI(
"http://localhost:7072/api/AzureWebAdapter/pets"));
request.setBody(Optional.of("{\"id\":\"535932f1-d18b-488a-ad8f-8d50b9678492\"" +
"\"breed\":\"Beagle\",\"name\":\"Murphy\",\"dateOfBirth\":1591682824313}"));

View File

@@ -32,7 +32,7 @@ import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
//@SpringBootApplication
@Configuration
@Import({ PetsController.class })
public class PetStoreSpringAppConfig {