-
Notifications
You must be signed in to change notification settings - Fork 988
Added application/x-www-form-urlencoded support to the Jakarta REST client backed by a collection of NameValuePair #844
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
arturobernalg
wants to merge
1
commit into
apache:master
Choose a base branch
from
arturobernalg:rest-form-urlencoded
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -33,7 +33,10 @@ | |
| import java.lang.reflect.Type; | ||
| import java.net.URI; | ||
| import java.net.URISyntaxException; | ||
| import java.nio.charset.Charset; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.ArrayList; | ||
| import java.util.Collection; | ||
| import java.util.HashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
|
|
@@ -73,6 +76,7 @@ | |
| import org.apache.hc.core5.jackson2.http.JsonObjectEntityProducer; | ||
| import org.apache.hc.core5.jackson2.http.JsonResponseConsumers; | ||
| import org.apache.hc.core5.net.URIBuilder; | ||
| import org.apache.hc.core5.net.WWWFormCodec; | ||
| import org.apache.hc.core5.util.Args; | ||
|
|
||
| /** | ||
|
|
@@ -162,19 +166,21 @@ private Object executeRequest(final ResourceMethod rm, | |
| for (final Header header : headers) { | ||
| request.addHeader(header); | ||
| } | ||
| final List<ContentType> consumesContentTypes = rm.getConsumesContentTypes(); | ||
| if (consumesContentTypes != null && !consumesContentTypes.isEmpty()) { | ||
| // @Produces declares the media type(s) the client accepts back (Accept header). | ||
| final List<ContentType> acceptTypes = rm.getProducesContentTypes(); | ||
| if (acceptTypes != null && !acceptTypes.isEmpty()) { | ||
| request.setHeader(MessageSupport.headerOfTokens( | ||
| HttpHeaders.ACCEPT, | ||
| consumesContentTypes.stream() | ||
| acceptTypes.stream() | ||
| .map(ContentType::getMimeType) | ||
| .collect(Collectors.toList()))); | ||
| } | ||
| // @Consumes declares the media type of the request body the client sends. | ||
| final AsyncEntityProducer entityProducer; | ||
| if (bodyParam != null) { | ||
| final List<ContentType> producesContentTypes = rm.getProducesContentTypes(); | ||
| final ContentType contentType = producesContentTypes != null && !producesContentTypes.isEmpty() ? | ||
| producesContentTypes.get(0) : null; | ||
| final List<ContentType> requestBodyTypes = rm.getConsumesContentTypes(); | ||
| final ContentType contentType = requestBodyTypes != null && !requestBodyTypes.isEmpty() ? | ||
| requestBodyTypes.get(0) : null; | ||
| entityProducer = createEntityProducer(bodyParam, contentType); | ||
| } else { | ||
| entityProducer = null; | ||
|
|
@@ -184,7 +190,7 @@ private Object executeRequest(final ResourceMethod rm, | |
|
|
||
| final boolean isAsync = isAsync(rm.getMethod()); | ||
| final Class<?> rawType = resolveResponseType(rm.getMethod(), isAsync); | ||
| final Future<?> future = dispatchAsync(rawType, requestProducer); | ||
| final Future<?> future = dispatchAsync(rm.getMethod(), isAsync, rawType, requestProducer); | ||
| if (isAsync) { | ||
| return future; | ||
| } | ||
|
|
@@ -216,7 +222,8 @@ private static Class<?> resolveResponseType(final Method method, final boolean a | |
| return Object.class; | ||
| } | ||
|
|
||
| private CompletableFuture<?> dispatchAsync(final Class<?> rawType, | ||
| private CompletableFuture<?> dispatchAsync(final Method method, final boolean async, | ||
| final Class<?> rawType, | ||
| final BasicRequestProducer requestProducer) { | ||
| if (rawType == Response.class) { | ||
| return submit(requestProducer, new BasicResponseConsumer<>(new RestContentConsumer(objectMapper))) | ||
|
|
@@ -244,6 +251,21 @@ private CompletableFuture<?> dispatchAsync(final Class<?> rawType, | |
| return result.getBody(); | ||
| }); | ||
| } | ||
| if (isNameValuePairCollection(method, async)) { | ||
| return submit(requestProducer, new RestResponseConsumer<>(objectMapper, StringAsyncEntityConsumer::new)) | ||
| .thenApply(result -> { | ||
| throwIfError(result); | ||
| final Header header = result.getHead().getFirstHeader(HttpHeaders.CONTENT_TYPE); | ||
| final ContentType contentType = header != null ? ContentType.parse(header.getValue()) : null; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @arturobernalg One small thing. Let's make ContentType parsing more efficient: |
||
| if (contentType != null && !ContentType.APPLICATION_FORM_URLENCODED.isSameMimeType(contentType)) { | ||
| throw new RestResourceException( | ||
| "Expected an application/x-www-form-urlencoded response but received: " + contentType.getMimeType()); | ||
| } | ||
| final Charset charset = ContentType.getCharset(contentType, StandardCharsets.UTF_8); | ||
| final String body = result.getBody(); | ||
| return WWWFormCodec.parse(body != null ? body : "", charset); | ||
| }); | ||
| } | ||
| @SuppressWarnings("unchecked") final Class<Object> objectType = (Class<Object>) rawType; | ||
| return submit(requestProducer, | ||
| JsonResponseConsumers.create(objectMapper, objectType, () -> new RestContentConsumer(objectMapper))) | ||
|
|
@@ -253,6 +275,23 @@ private CompletableFuture<?> dispatchAsync(final Class<?> rawType, | |
| }); | ||
| } | ||
|
|
||
| private static boolean isNameValuePairCollection(final Method method, final boolean async) { | ||
| Type type = method.getGenericReturnType(); | ||
| if (async && type instanceof ParameterizedType) { | ||
| type = ((ParameterizedType) type).getActualTypeArguments()[0]; | ||
| } | ||
| if (!(type instanceof ParameterizedType)) { | ||
| return false; | ||
| } | ||
| final ParameterizedType parameterizedType = (ParameterizedType) type; | ||
| final Type rawType = parameterizedType.getRawType(); | ||
| if (!(rawType instanceof Class) || !Collection.class.isAssignableFrom((Class<?>) rawType)) { | ||
| return false; | ||
| } | ||
| final Type[] typeArguments = parameterizedType.getActualTypeArguments(); | ||
| return typeArguments.length == 1 && typeArguments[0] == NameValuePair.class; | ||
| } | ||
|
|
||
| private <T> CompletableFuture<Message<HttpResponse, T>> submit( | ||
| final BasicRequestProducer requestProducer, | ||
| final AsyncResponseConsumer<Message<HttpResponse, T>> responseConsumer) { | ||
|
|
@@ -314,6 +353,23 @@ private AsyncEntityProducer createEntityProducer(final Object body, | |
| final ContentType ct = consumeType != null ? consumeType : ContentType.TEXT_PLAIN; | ||
| return new StringAsyncEntityProducer((CharSequence) body, ct); | ||
| } | ||
| if (body instanceof Collection) { | ||
| final Collection<?> items = (Collection<?>) body; | ||
| final boolean formByType = consumeType != null | ||
| && ContentType.APPLICATION_FORM_URLENCODED.isSameMimeType(consumeType); | ||
| final boolean formByContent = consumeType == null | ||
| && !items.isEmpty() | ||
| && items.stream().allMatch(e -> e instanceof NameValuePair); | ||
| if (formByType || formByContent) { | ||
| final ContentType ct = formByType ? consumeType : ContentType.APPLICATION_FORM_URLENCODED; | ||
| final Charset charset = ContentType.getCharset(ct, StandardCharsets.UTF_8); | ||
| final List<NameValuePair> pairs = new ArrayList<>(items.size()); | ||
| for (final Object e : items) { | ||
| pairs.add((NameValuePair) e); | ||
| } | ||
| return new StringAsyncEntityProducer(WWWFormCodec.format(pairs, charset), ct); | ||
| } | ||
| } | ||
| return new JsonObjectEntityProducer<>(body, objectMapper); | ||
| } | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@arturobernalg Indeed. It looks like I made a mistake here.
@Producesdeclares what the endpoint produces and what client can choose to accept. Good catch.