Skip to content
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

Support form url encoding #666

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .palantir/revapi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -252,3 +252,9 @@ acceptedBreaks:
old: null
new: "method void com.palantir.dialogue.RequestBody::close()"
justification: "internal interface not for extension"
"1.26.0":
com.palantir.dialogue:dialogue-target:
- code: "java.method.addedToInterface"
new: "method com.palantir.dialogue.Serializer<java.util.Map<java.lang.String,\
\ java.lang.String>> com.palantir.dialogue.BodySerDe::formUrlEncodingSerializer()"
justification: "No known external implementations of BodySerDe yet"
6 changes: 6 additions & 0 deletions changelog/@unreleased/pr-666.v2.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
type: feature
feature:
description: The `BodySerDe#formUrlEncodingSerializer` can be used to send `application/x-www-form-urlencoded`
data (e.g. for OAuth2 endpoints).
links:
- https://github.com/palantir/dialogue/pull/666
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.ws.rs.core.HttpHeaders;
Expand Down Expand Up @@ -156,6 +157,11 @@ public void close() {
};
}

@Override
public Serializer<Map<String, String>> formUrlEncodingSerializer() {
return FormUrlEncodingSerializer.INSTANCE;
}

private static final class EncodingSerializerRegistry<T> implements Serializer<T> {

private final EncodingSerializerContainer<T> encoding;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* (c) Copyright 2020 Palantir Technologies Inc. All rights reserved.
*
* 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
*
* http://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 com.palantir.conjure.java.dialogue.serde;

import com.palantir.dialogue.RequestBody;
import com.palantir.dialogue.Serializer;
import com.palantir.logsafe.Preconditions;
import com.palantir.logsafe.UnsafeArg;
import com.palantir.logsafe.exceptions.SafeRuntimeException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

enum FormUrlEncodingSerializer implements Serializer<Map<String, String>> {
INSTANCE;

@Override
public RequestBody serialize(Map<String, String> value) {
return new RequestBody() {
@Override
public void writeTo(OutputStream output) throws IOException {
boolean first = true;
for (Map.Entry<String, String> entry : value.entrySet()) {
if (first) {
first = false;
} else {
output.write('&');
}

String key = Preconditions.checkNotNull(entry.getKey(), "key must not be null");
output.write(encode(key).getBytes(StandardCharsets.UTF_8));
output.write('=');

String value = Preconditions.checkNotNull(
entry.getValue(), "value must not be null", UnsafeArg.of("key", key));
output.write(encode(value).getBytes(StandardCharsets.UTF_8));
}
}

@Override
public String contentType() {
return "application/x-www-form-urlencoded";
}

@Override
public boolean repeatable() {
return true;
}

@Override
public void close() {}
};
}

/** As per https://url.spec.whatwg.org/#urlencoded-serializing. */
private static String encode(String source) {
try {
return URLEncoder.encode(source, StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException e) {
throw new SafeRuntimeException("Unable to encode string", e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* (c) Copyright 2020 Palantir Technologies Inc. All rights reserved.
*
* 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
*
* http://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 com.palantir.conjure.java.dialogue.serde;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import com.google.common.collect.ImmutableMap;
import com.palantir.dialogue.RequestBody;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;

class FormUrlEncodingSerializerTest {

@Test
void basic_key_value_pairs() throws IOException {
RequestBody body = FormUrlEncodingSerializer.INSTANCE.serialize(
ImmutableMap.of("token", "foo", "TOKEN2", "bar", "", "", "empty", ""));
assertThat(asString(body)).isEqualTo("token=foo&TOKEN2=bar&=&empty=");
}

@Test
void percent_encodes_some_common_special_characters() throws IOException {
RequestBody body = FormUrlEncodingSerializer.INSTANCE.serialize(
ImmutableMap.of("key!@#$%^&*()_+-= ", "value!@#$%^&*()_+-= "));
assertThat(asString(body))
.isEqualTo("key%21%40%23%24%25%5E%26*%28%29_%2B-%3D+=value%21%40%23%24%25%5E%26*%28%29_%2B-%3D+");
}

@Test
void percent_encodes_silly_characters() throws IOException {
RequestBody body = FormUrlEncodingSerializer.INSTANCE.serialize(ImmutableMap.of("key", sillyBytes(50)));
assertThat(asString(body))
.isEqualTo("key=%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15"
+ "%16%17%18%19%1A%1B%1C%1D%1E%1F+%21%22%23%24%25%26%27%28%29*%2B%2C-.%2F01");
}

@Test
void percent_emoji() throws IOException {
RequestBody body = FormUrlEncodingSerializer.INSTANCE.serialize(ImmutableMap.of("key", "🚀"));
assertThat(asString(body)).isEqualTo("key=%F0%9F%9A%80");
}

@Test
void handles_null() throws IOException {
Map<String, String> map = new HashMap<>();
map.put("foo", null);
RequestBody body = FormUrlEncodingSerializer.INSTANCE.serialize(map);
assertThatThrownBy(() -> asString(body)).hasMessage("value must not be null: {key=foo}");
}

private static String sillyBytes(int count) {
byte[] silly = new byte[count];
for (int i = 0; i < silly.length; i++) {
silly[i] = (byte) i;
}
return new String(silly, StandardCharsets.UTF_8);
}

private static String asString(RequestBody body) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
body.writeTo(baos);
return new String(baos.toByteArray(), StandardCharsets.UTF_8);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.palantir.dialogue;

import java.io.InputStream;
import java.util.Map;
import java.util.Optional;

/** Request and response Deserialization and Serialization functionality used by generated code. */
Expand Down Expand Up @@ -46,4 +47,7 @@ public interface BodySerDe {

/** Serializes a {@link BinaryRequestBody} to <pre>application/octet-stream</pre>. */
RequestBody serialize(BinaryRequestBody value);

/** Serializes key-value tuples according to https://url.spec.whatwg.org/#urlencoded-serializing. */
Serializer<Map<String, String>> formUrlEncodingSerializer();
}