Skip to content
This repository has been archived by the owner on Sep 13, 2024. It is now read-only.

Commit

Permalink
Merge branch 'release/0.3.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Wegener committed Apr 6, 2017
2 parents d2faf4e + 0d8d190 commit 44db5b0
Show file tree
Hide file tree
Showing 37 changed files with 1,094 additions and 93 deletions.
2 changes: 0 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
language: java
jdk:
- oraclejdk8
- oraclejdk7
- openjdk7
after_success:
- mvn clean -DTRAVIS_JOB_ID=$TRAVIS_JOB_ID cobertura:cobertura coveralls:report
32 changes: 16 additions & 16 deletions gdk-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ The only must, when it comes to configuration overwrites, is the **graviton.base
Let's say we want to execute a GET request and have an endpoint /person/customer where the gdk-maven-plugin created a matching Customer class.

```java
Graviton graviton = new Graviton();
GravitonApi gravitonApi = new GravitonApi();
try {
GravitonResponse response1 = graviton.get("123", Customer.class).execute();
GravitonResponse response1 = gravitonApi.get("123", Customer.class).execute();
Customer customer1 = response1.getBodyItem(Customer.class);
} catch (CommunicationException e) {
// Unable to obtain customer1
Expand All @@ -28,15 +28,15 @@ try {
Customer customer2 = new Customer();
customer2.setId("123");
try {
GravitonResponse response2 = graviton.get(customer).execute();
GravitonResponse response2 = gravitonApi.get(customer).execute();
customer2 = response2.getBodyItem(Customer.class);
} catch (CommunicationException e) {
// Unable to obtain customer2
}

// or even
try {
GravitonResponse response3 = graviton.get("https://graviton-base-url/person/customer/123").execute();
GravitonResponse response3 = gravitonApi.get("https://graviton-base-url/person/customer/123").execute();
Customer customer3 = response3.getBodyItem(Customer.class);
} catch (CommunicationException e) {
// Unable to obtain customer3
Expand All @@ -46,28 +46,28 @@ try {
From this point on, all the REST calls are really simple to handle

```java
Graviton graviton = new Graviton();
GravitonApi gravitonApi = new GravitonApi();

try {
// POST request
Customer customer = new Customer();
customer.setFirstName("John");
customer.setLastName("Smith");

GravitonResponse response = graviton.post(customer).execute();
GravitonResponse response = gravitonApi.post(customer).execute();
// What is the link to the newly created customer?
String targetLink = response.getHeaders().getLink(LinkHeader.SELF);

// GET request
response = graviton.get(targetLink).execute();
response = gravitonApi.get(targetLink).execute();
Customer existingCustomer = response.getBodyItem(Customer.class);

// PATCH request
existingCustomer.setLastName("Fletcher");
graviton.patch(existingCustomer).execute();
gravitonApi.patch(existingCustomer).execute();

// DELETE request
graviton.delete(existingCustomer).execute();
gravitonApi.delete(existingCustomer).execute();
} catch (CommunicationException e) {
// Unable to complete example
}
Expand All @@ -80,31 +80,31 @@ try {
The file service endpoint behaves a little bit different from the other endpoints, since it allows us to retrieve the file itself or the file metadata via the same endpoint. Therefore the file service handling receives its own little helper, the **GravitonFile** class. In this case the **File** class is part of the generated POJOs

```java
GravitonFile gravitonFile = new GravitonFile();
GravitonFileEndpoint gravitonFileEndpoint = new GravitonFileEndpoint();

try {
// GET the metadata
File fileResource = new File();
fileResource.setId("987");
GravitonResponse response = gravitonFile.getMetadata(fileResource).execute();
GravitonResponse response = gravitonFileEndpoint.getMetadata(fileResource).execute();
File metadata = response.getBody(File.class);

// modify the metadata
metadata.getMetadata().setFilename(System.currentTimeMillis() + ".txt");
gravitonFile.patch(metadata).execute();
gravitonFileEndpoint.patch(metadata).execute();

// GET the file itself
response = gravitonFile.getFile(fileResource).execute();
response = gravitonFileEndpoint.getFile(fileResource).execute();
String data = response.getBodyItem();

// create a new file via POST
response = gravitonFile.post(data, metadata).execute();
response = gravitonFileEndpoint.post(data, metadata).execute();
String targetLink = response.getHeaders().getLink(LinkHeader.SELF);

// DELETE the newly created file
response = gravitonFile.getMetadata(targetLink).execute();
response = gravitonFileEndpoint.getMetadata(targetLink).execute();
metadata = response.getBodyItem(File.class);
gravitonFile.delete(metadata).execute();
gravitonFileEndpoint.delete(metadata).execute();
} catch (CommunicationException e) {
// Unable to complete example
}
Expand Down
6 changes: 3 additions & 3 deletions gdk-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<parent>
<groupId>com.github.libgraviton</groupId>
<artifactId>gdk</artifactId>
<version>0.2.2</version>
<version>0.2.3-SNAPSHOT</version>
</parent>
<artifactId>gdk-core</artifactId>
<name>gdk-core</name>
Expand Down
47 changes: 32 additions & 15 deletions gdk-core/src/main/java/com/github/libgraviton/gdk/GravitonApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,22 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.libgraviton.gdk.api.NoopRequest;
import com.github.libgraviton.gdk.api.Request;
import com.github.libgraviton.gdk.api.endpoint.EndpointManager;
import com.github.libgraviton.gdk.api.endpoint.GeneratedEndpointManager;
import com.github.libgraviton.gdk.api.endpoint.exception.UnableToLoadEndpointAssociationsException;
import com.github.libgraviton.gdk.api.header.HeaderBag;
import com.github.libgraviton.gdk.api.query.rql.Rql;
import com.github.libgraviton.gdk.data.GravitonBase;
import com.github.libgraviton.gdk.exception.SerializationException;
import com.github.libgraviton.gdk.serialization.JsonPatcher;
import com.github.libgraviton.gdk.serialization.mapper.GravitonObjectMapper;
import com.github.libgraviton.gdk.serialization.mapper.RqlObjectMapper;
import com.github.libgraviton.gdk.util.PropertiesLoader;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.TimeZone;

/**
* This is the base class used for Graviton API calls.
Expand Down Expand Up @@ -69,7 +71,7 @@ protected void setup() {
} catch (IOException e) {
throw new IllegalStateException("Unable to load properties files.", e);
}
this.objectMapper = initObjectMapper();
this.objectMapper = new GravitonObjectMapper(properties);
this.executor = new RequestExecutor(objectMapper);
}

Expand Down Expand Up @@ -144,6 +146,18 @@ public Request.Builder get(String id, Class clazz) {
.addParam("id", id);
}

/**
* GET request with a URL query. The response will result in a list of items,
* even if there is only 1 matching item to the query.
*
* @param resource payload
* @return request builder
*/
public Request.Builder query(GravitonBase resource) {
return get(endpointManager.getEndpoint(resource.getClass().getName()).getUrl())
.setQuery(new Rql.Builder().setResource(resource, new RqlObjectMapper(properties)).build());
}

public Request.Builder delete(String url) {
return request().setUrl(url).delete();
}
Expand All @@ -166,10 +180,19 @@ public Request.Builder put(GravitonBase resource) throws SerializationException

public Request.Builder patch(GravitonBase resource) throws SerializationException {
JsonNode jsonNode = getObjectMapper().convertValue(resource, JsonNode.class);
return request()
String data = serializeResource(JsonPatcher.getPatch(resource, jsonNode));

Request.Builder builder;
if(data == null || data.isEmpty() || "[]".equals(data)) {
builder = new NoopRequest.Builder("PATCH body is empty. Nothing changed.");
} else {
builder = request();
}

return builder
.setUrl(endpointManager.getEndpoint(resource.getClass().getName()).getItemUrl())
.addParam("id", extractId(resource))
.patch(serializeResource(JsonPatcher.getPatch(resource, jsonNode)));
.patch(data);
}

public Request.Builder post(GravitonBase resource) throws SerializationException {
Expand All @@ -191,6 +214,10 @@ protected String extractId(GravitonBase data) {
}

protected String serializeResource(Object data) throws SerializationException {
if (data == null) {
return "";
}

try {
return getObjectMapper().writeValueAsString(data);
} catch (JsonProcessingException e) {
Expand All @@ -201,12 +228,6 @@ protected String serializeResource(Object data) throws SerializationException {
}
}

protected ObjectMapper initObjectMapper() {
SimpleDateFormat dateFormat = new SimpleDateFormat(properties.getProperty("graviton.date.format"));
dateFormat.setTimeZone(TimeZone.getTimeZone(properties.getProperty("graviton.timezone")));
return new ObjectMapper().setDateFormat(dateFormat);
}

public ObjectMapper getObjectMapper() {
return objectMapper;
}
Expand All @@ -218,8 +239,4 @@ protected HeaderBag getDefaultHeaders() {
.set("Accept", "application/json")
.build();
}

public void setRequestExecutor(RequestExecutor executor) {
this.executor = executor;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.github.libgraviton.gdk.api;

import com.github.libgraviton.gdk.exception.CommunicationException;
import com.github.libgraviton.gdk.exception.UnsuccessfulRequestException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.MalformedURLException;

public class NoopRequest extends Request {

private static final Logger LOG = LoggerFactory.getLogger(NoopRequest.class);

protected String reason;

protected NoopRequest(Builder builder) throws MalformedURLException {
super(builder);
this.reason = builder.reason;
}

public String getReason() {
return reason;
}

public static class Builder extends Request.Builder {

private String reason;

public Builder(String reason) {
this.reason = reason;
}

public NoopRequest build() throws MalformedURLException {
return new NoopRequest(this);
}

public NoopResponse execute() throws CommunicationException {
NoopRequest request;
try {
request = build();
} catch (MalformedURLException e) {
throw new UnsuccessfulRequestException(String.format("'%s' to '%s' failed due to malformed url.", method, url),
e);
}
LOG.info(request.getMethod() + " request to '" + request.getUrl() + "' not executed due to '" + request.getReason() + "'.");
return new NoopResponse(request);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.github.libgraviton.gdk.api;

import com.github.libgraviton.gdk.api.header.HeaderBag;

/**
* Graviton response wrapper with additional functionality and simplified interface.
*
* @author List of contributors {@literal <https://github.com/libgraviton/gdk-java/graphs/contributors>}
* @see <a href="http://swisscom.ch">http://swisscom.ch</a>
* @version $Id: $Id
*/
public class NoopResponse extends Response {

public NoopResponse(NoopRequest request) {
this.request = request;
this.code = -1;
this.isSuccessful = true;
this.message = "This is not the response you are looking for";
this.body = null;
this.headers = new HeaderBag.Builder().build();
}
}
40 changes: 27 additions & 13 deletions gdk-core/src/main/java/com/github/libgraviton/gdk/api/Request.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.github.libgraviton.gdk.RequestExecutor;
import com.github.libgraviton.gdk.api.header.HeaderBag;
import com.github.libgraviton.gdk.api.multipart.Part;
import com.github.libgraviton.gdk.api.query.Query;
import com.github.libgraviton.gdk.exception.CommunicationException;
import com.github.libgraviton.gdk.exception.UnsuccessfulRequestException;

Expand All @@ -15,15 +16,15 @@

public class Request {

private URL url;
protected URL url;

private HttpMethod method;
protected HttpMethod method;

private HeaderBag headers;
protected HeaderBag headers;

private byte[] body;
protected byte[] body;

private List<Part> parts;
protected List<Part> parts;

protected Request() {
}
Expand Down Expand Up @@ -66,19 +67,21 @@ public boolean isMultipartRequest() {

public static class Builder {

private String url;
protected String url;

private Map<String, String> params = new HashMap<>();
protected Map<String, String> params = new HashMap<>();

private HttpMethod method = HttpMethod.GET;
protected HttpMethod method = HttpMethod.GET;

private HeaderBag.Builder headerBuilder = new HeaderBag.Builder();
protected HeaderBag.Builder headerBuilder = new HeaderBag.Builder();

private byte[] body;
protected Query query;

private List<Part> parts = new ArrayList<>();
protected byte[] body;

private RequestExecutor executor;
protected List<Part> parts = new ArrayList<>();

protected RequestExecutor executor;

public Builder() {
this.executor = new RequestExecutor();
Expand Down Expand Up @@ -126,6 +129,16 @@ public Builder setHeaders(HeaderBag headerBag) {
return this;
}

public Builder setQuery(Query query) {
if(this.query == null) {
this.query = query;
} else {
this.query.addStatements(query.getStatements());
}

return this;
}

public Builder setBody(String body) {
this.body = body.getBytes();
return this;
Expand Down Expand Up @@ -204,7 +217,8 @@ public Response execute() throws CommunicationException {
}

protected URL buildUrl() throws MalformedURLException {
String url = this.url;
String generatedQuery = query != null ? query.generate() : "";
String url = this.url + generatedQuery;
for (Map.Entry<String, String> param : params.entrySet()) {
url = url.replace(String.format("{%s}", param.getKey()), param.getValue());
}
Expand Down
Loading

0 comments on commit 44db5b0

Please sign in to comment.