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
Changes from 1 commit
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
Next Next commit
BodySerDe#formUrlEncodingSerializer
iamdanfox committed Apr 22, 2020
commit 094d99851b85d741985934ea9f7586251c3c1ed3
Original file line number Diff line number Diff line change
@@ -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;
@@ -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;
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* (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.google.common.base.CharMatcher;
import com.palantir.dialogue.RequestBody;
import com.palantir.dialogue.Serializer;
import com.palantir.logsafe.Preconditions;
import com.palantir.logsafe.UnsafeArg;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
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(FormUrlEncoder.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(FormUrlEncoder.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 class FormUrlEncoder {
private static final CharMatcher DIGIT = CharMatcher.inRange('0', '9');
private static final CharMatcher ALPHA = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'));
private static final CharMatcher PRESERVE = DIGIT.or(ALPHA).or(CharMatcher.anyOf("*-._"));

// percent-encodes every byte in the source string with it's percent-encoded representation, except for
// bytes that (in their unsigned char sense) are matched by charactersToKeep
static String encode(String source) {
byte[] bytes = source.getBytes(StandardCharsets.UTF_8);
ByteArrayOutputStream bos = new ByteArrayOutputStream(source.length()); // approx sizing
boolean wasChanged = false;
for (byte b : bytes) {
if (PRESERVE.matches(toChar(b))) {
bos.write(b);
} else if (b == ' ') {
bos.write('+');
} else {
bos.write('%');
char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16));
char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16));
bos.write(hex1);
bos.write(hex2);
wasChanged = true;
}
}
return wasChanged ? new String(bos.toByteArray(), StandardCharsets.UTF_8) : source;
}

// converts the given (signed) byte into an (unsigned) char
private static char toChar(byte theByte) {
if (theByte < 0) {
return (char) (256 + theByte);
} else {
return (char) theByte;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* (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 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
@@ -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. */
@@ -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();
}