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

[http-client] Adds Moshi Body Adapter #424

Merged
merged 3 commits into from
Apr 21, 2024
Merged
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
4 changes: 2 additions & 2 deletions http-client-gson-adapter/src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

exports io.avaje.http.client.gson;

requires io.avaje.http.client;
requires com.google.gson;
requires transitive io.avaje.http.client;
requires transitive com.google.gson;
}
37 changes: 37 additions & 0 deletions http-client-moshi-adapter/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.avaje</groupId>
<artifactId>avaje-http-parent</artifactId>
<version>2.4</version>
</parent>
<artifactId>avaje-http-client-moshi</artifactId>

<dependencies>

<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi</artifactId>
<version>1.15.1</version>
<optional>true</optional>
</dependency>

<dependency>
<groupId>io.avaje</groupId>
<artifactId>avaje-http-client</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>

<!-- test dependencies -->

<dependency>
<groupId>io.avaje</groupId>
<artifactId>junit</artifactId>
<version>1.4</version>
<scope>test</scope>
</dependency>

</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
package io.avaje.http.client.moshi;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;

import io.avaje.http.client.BodyAdapter;
import io.avaje.http.client.BodyContent;
import io.avaje.http.client.BodyReader;
import io.avaje.http.client.BodyWriter;

/**
* Moshi BodyAdapter to read and write beans as JSON.
*
* <pre>{@code
* HttpClient.builder()
* .baseUrl(baseUrl)
* .bodyAdapter(new MoshiBodyAdapter())
* .build();
*
* }</pre>
*/
public final class MoshiBodyAdapter implements BodyAdapter {

private final Moshi moshi;
private final ConcurrentHashMap<Type, BodyWriter<?>> beanWriterCache = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Type, BodyReader<?>> beanReaderCache = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Type, BodyReader<?>> listReaderCache = new ConcurrentHashMap<>();

/**
* Create passing the Moshi to use.
*/
public MoshiBodyAdapter(Moshi moshi) {
this.moshi = moshi;
}

/**
* Create with a default Moshi that allows unknown properties.
*/
public MoshiBodyAdapter() {
this(new Moshi.Builder().build());
}

@SuppressWarnings("unchecked")
@Override
public <T> BodyWriter<T> beanWriter(Class<?> cls) {
return (BodyWriter<T>) beanWriterCache.computeIfAbsent(cls, aClass -> new JWriter<>(moshi.adapter(cls)));
}

@SuppressWarnings("unchecked")
@Override
public <T> BodyWriter<T> beanWriter(Type type) {
return (BodyWriter<T>) beanWriterCache.computeIfAbsent(type, aClass -> new JWriter<>(moshi.adapter(type)));
}

@SuppressWarnings("unchecked")
@Override
public <T> BodyReader<T> beanReader(Class<T> cls) {
return (BodyReader<T>) beanReaderCache.computeIfAbsent(cls, aClass -> new JReader<>(moshi.adapter(cls)));
}

@SuppressWarnings("unchecked")
@Override
public <T> BodyReader<T> beanReader(Type type) {
return (BodyReader<T>) beanReaderCache.computeIfAbsent(type, aClass -> new JReader<>(moshi.adapter(type)));
}

@SuppressWarnings("unchecked")
@Override
public <T> BodyReader<List<T>> listReader(Type type) {
return (BodyReader<List<T>>)
listReaderCache.computeIfAbsent(
type,
aClass -> new JReader<>(moshi.adapter(Types.newParameterizedType(List.class, type))));
}

@SuppressWarnings("unchecked")
@Override
public <T> BodyReader<List<T>> listReader(Class<T> cls) {
return (BodyReader<List<T>>)
listReaderCache.computeIfAbsent(
cls,
aClass -> new JReader<>(moshi.adapter(Types.newParameterizedType(List.class, cls))));
}

private static class JReader<T> implements BodyReader<T> {

private final JsonAdapter<T> reader;

JReader(JsonAdapter<T> reader) {
this.reader = reader;
}

@Override
public T readBody(String content) {
try {
return reader.fromJson(content);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

@Override
public T read(BodyContent bodyContent) {
try {
return reader.fromJson(bodyContent.contentAsUtf8());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}

private static class JWriter<T> implements BodyWriter<T> {

private final JsonAdapter<T> writer;

public JWriter(JsonAdapter<T> writer) {
this.writer = writer;
}

@Override
public BodyContent write(T bean, String contentType) {
// ignoring the requested contentType and always
// writing the body as json content
return write(bean);
}

@Override
public BodyContent write(T bean) {
return BodyContent.of(writer.toJson(bean));
}
}
}
7 changes: 7 additions & 0 deletions http-client-moshi-adapter/src/main/java/module-info.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module io.avaje.http.client.gson {

exports io.avaje.http.client.moshi;

requires transitive io.avaje.http.client;
requires transitive com.squareup.moshi;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package io.avaje.http.client.moshi;

public class Foo {

public long id;

public String name;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package io.avaje.http.client.moshi;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.nio.charset.StandardCharsets;
import java.util.List;

import org.junit.jupiter.api.Test;

import io.avaje.http.client.BodyContent;
import io.avaje.http.client.BodyReader;
import io.avaje.http.client.BodyWriter;

class MoshiBodyAdapterTest {

private final MoshiBodyAdapter adapter = new MoshiBodyAdapter();

@Test
void beanWriter() {

final Foo foo = new Foo();
foo.id = 42;
foo.name = "bar";

final BodyWriter writer = adapter.beanWriter(Foo.class);
final BodyContent content = writer.write(foo);

final String json = new String(content.content(), StandardCharsets.UTF_8);
assertEquals("{\"id\":42,\"name\":\"bar\"}", json);
}

@Test
void beanReader() {

final BodyReader<Foo> reader = adapter.beanReader(Foo.class);

final Foo read = reader.read(content("{\"id\":42, \"name\":\"bar\"}"));
assertEquals(42, read.id);
assertEquals("bar", read.name);
}

@Test
void listReader() {

final BodyReader<List<Foo>> reader = adapter.listReader(Foo.class);

final List<Foo> read =
reader.read(content("[{\"id\":42, \"name\":\"bar\"},{\"id\":43, \"name\":\"baz\"}]"));

assertEquals(2, read.size());
assertEquals(42, read.get(0).id);
assertEquals(43, read.get(1).id);
}

BodyContent content(String raw) {
return BodyContent.of(raw.getBytes());
}
}
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
<module>http-api-javalin</module>
<module>http-client</module>
<module>http-client-gson-adapter</module>
<module>http-client-moshi-adapter</module>
<module>http-inject-plugin</module>
<module>http-generator-core</module>
<module>http-generator-javalin</module>
Expand Down