Skip to content

Commit

Permalink
Merge pull request #50 from brianjmiller/jetty9
Browse files Browse the repository at this point in the history
Target JDK8, update to Jetty 9, improve RemoteLRS HTTP Client interface
  • Loading branch information
brianjmiller committed May 19, 2016
2 parents cf7b27b + 872b6a4 commit 9cc0eb3
Show file tree
Hide file tree
Showing 5 changed files with 106 additions and 133 deletions.
3 changes: 2 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
sudo: false
language: java
jdk: openjdk7
jdk: oraclejdk8
before_script: cp src/test/resources/travis-ci.properties src/test/resources/lrs.properties
10 changes: 5 additions & 5 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerVersion>1.6</compilerVersion>
<source>1.6</source>
<target>1.6</target>
<compilerVersion>1.8</compilerVersion>
<source>1.8</source>
<target>1.8</target>
</configuration>
<version>3.0</version>
<version>3.3</version>
</plugin>
<!--<plugin>
<groupId>org.projectlombok</groupId>
Expand Down Expand Up @@ -161,7 +161,7 @@
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-client</artifactId>
<version>8.1.9.v20130131</version>
<version>9.3.6.v20151106</version>
</dependency>
</dependencies>

Expand Down
185 changes: 99 additions & 86 deletions src/main/java/com/rusticisoftware/tincan/RemoteLRS.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,30 @@
*/
package com.rusticisoftware.tincan;

import org.apache.commons.codec.binary.Base64;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.rusticisoftware.tincan.documents.ActivityProfileDocument;
import com.rusticisoftware.tincan.documents.AgentProfileDocument;
import com.rusticisoftware.tincan.documents.Document;
import com.rusticisoftware.tincan.documents.StateDocument;
import com.rusticisoftware.tincan.exceptions.*;
import com.rusticisoftware.tincan.lrsresponses.*;
import com.rusticisoftware.tincan.http.HTTPRequest;
import com.rusticisoftware.tincan.http.HTTPResponse;
import com.rusticisoftware.tincan.lrsresponses.*;

import com.rusticisoftware.tincan.json.Mapper;
import com.rusticisoftware.tincan.json.StringOfJSON;
import com.rusticisoftware.tincan.v10x.StatementsQuery;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.util.BytesContentProvider;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.util.HttpCookieStore;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import lombok.Data;
import lombok.NoArgsConstructor;

Expand All @@ -36,49 +49,65 @@
import java.net.URLEncoder;
import java.util.*;

import org.apache.commons.codec.binary.Base64;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpExchange;
import org.eclipse.jetty.http.HttpMethods;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.ByteArrayBuffer;

import com.rusticisoftware.tincan.exceptions.*;
import com.rusticisoftware.tincan.json.Mapper;
import com.rusticisoftware.tincan.json.StringOfJSON;
import com.rusticisoftware.tincan.v10x.StatementsQuery;

import static org.eclipse.jetty.client.HttpClient.CONNECTOR_SELECT_CHANNEL;

/**
* Class used to communicate with a TCAPI endpoint synchronously
*/
// TODO: handle extended on all requests
@Data
@NoArgsConstructor
public class RemoteLRS implements LRS {
private static int TIMEOUT_CONNECT = 5 * 1000;
private static long TIMEOUT_CONNECT = 5 * 1000;

private static Boolean _ourClient = false;
private static HttpClient _httpClient;
private static HttpClient httpClient() throws Exception {
if (_httpClient == null ) {
_httpClient = new HttpClient();
_httpClient.setConnectorType(CONNECTOR_SELECT_CHANNEL);
_httpClient = new HttpClient(new SslContextFactory());
_httpClient.setConnectTimeout(TIMEOUT_CONNECT);
_httpClient.setFollowRedirects(false);
_httpClient.setCookieStore(new HttpCookieStore.Empty());
_httpClient.start();

_ourClient = true;
}

return _httpClient;
}

public static int getHTTPClientConnectTimeout() {
/**
* Get the connect timeout value for the default HTTP client
*
* @return
* @deprecated set your own HTTP client using {@link #setHttpClient()}
*/
@Deprecated
public static long getHTTPClientConnectTimeout() {
return _httpClient.getConnectTimeout();
}
public static void setHTTPClientConnectTimeout(int timeout) {

/**
* Set the connect timeout value for the default HTTP client
*
* @deprecated set your own HTTP client using {@link #setHttpClient()}
*/
@Deprecated
public static void setHTTPClientConnectTimeout(long timeout) {
_httpClient.setConnectTimeout(timeout);
}

public static void setHttpClient(HttpClient client) throws Exception {
if (_httpClient != null && _ourClient) {
_httpClient.stop();
_httpClient.destroy();
}
_ourClient = false;
_httpClient = client;
}

public static void destroy() throws Exception {
setHttpClient(null);
}

private URL endpoint;
private TCAPIVersion version = this.getVersion();
private String username;
Expand Down Expand Up @@ -167,63 +196,47 @@ private HTTPResponse makeSyncRequest(HTTPRequest req) {
//Overload some of an ContentExchange object's functions with anonymous inner functions
//Access the HTTPResponse variable via a closure
final HTTPResponse response = new HTTPResponse();
ContentExchange webReq = new ContentExchange() {
protected void onResponseStatus(Buffer version, int status, Buffer reason) throws IOException {
super.onResponseStatus(version, status, reason);
response.setStatus(status);
response.setStatusMsg(reason.toString());
}

@Override
protected void onResponseHeader(Buffer name, Buffer value) throws IOException {
super.onResponseHeader(name, value);

response.setHeader(name.toString(), value.toString());
try {
final Request webReq = httpClient().
newRequest(url).
method(HttpMethod.fromString(req.getMethod())).
header("X-Experience-API-Version", this.version.toString()).
onResponseHeaders(new Response.HeadersListener() {
@Override
public void onHeaders(Response webResp) {
response.setStatus(webResp.getStatus());
response.setStatusMsg(webResp.getReason());
for(HttpField header: webResp.getHeaders()) {
response.setHeader(header.getName(), header.getValue());
}
}
});

if (this.auth != null) {
webReq.header("Authorization", this.auth);
}

@Override
protected void onResponseComplete() throws IOException {
super.onResponseComplete();

response.setContentBytes(this.getResponseContentBytes());
if (req.getHeaders() != null) {
Iterator it = req.getHeaders().entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
webReq.header(entry.getKey().toString(), entry.getValue().toString());
}
}
};

webReq.setURL(url);
webReq.setMethod(req.getMethod());

webReq.addRequestHeader("X-Experience-API-Version", this.version.toString());
if (this.auth != null) {
webReq.addRequestHeader("Authorization", this.auth);
}
if (req.getHeaders() != null) {
Iterator it = req.getHeaders().entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
webReq.addRequestHeader(entry.getKey().toString(), entry.getValue().toString());
if (req.getContentType() != null) {
webReq.header("Content-Type", req.getContentType());
}
else {
webReq.header("Content-Type", "application/octet-stream");
}
}

if (req.getContentType() != null) {
webReq.setRequestContentType(req.getContentType());
}
else {
webReq.setRequestContentType("application/octet-stream");
}

if (req.getContent() != null) {
webReq.setRequestContent(new ByteArrayBuffer(req.getContent()));
}

try {
httpClient().send(webReq);

// Waits until the exchange is terminated
int exchangeState = webReq.waitForDone();

if (exchangeState != HttpExchange.STATUS_COMPLETED) {
throw new FailedHTTPExchange(exchangeState);
if (req.getContent() != null) {
webReq.content(new BytesContentProvider(req.getContent()));
}

final ContentResponse webResp = webReq.send();
response.setContentBytes(webResp.getContent());
} catch (Exception ex) {
response.setStatus(400);
response.setStatusMsg("Exception in RemoteLRS.makeSyncRequest(): " + ex);
Expand All @@ -234,7 +247,7 @@ protected void onResponseComplete() throws IOException {

private StatementLRSResponse getStatement(String id, String paramName) {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethods.GET);
request.setMethod(HttpMethod.GET.asString());
request.setResource("statements");
request.setQueryParams(new HashMap<String, String>());
request.getQueryParams().put(paramName, id);
Expand Down Expand Up @@ -262,7 +275,7 @@ private StatementLRSResponse getStatement(String id, String paramName) {

private LRSResponse getDocument(String resource, Map<String, String> queryParams, Document document) {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethods.GET);
request.setMethod(HttpMethod.GET.asString());
request.setResource(resource);
request.setQueryParams(queryParams);

Expand Down Expand Up @@ -290,7 +303,7 @@ else if (response.getStatus() == 404) {
private LRSResponse deleteDocument(String resource, Map<String, String> queryParams) {
HTTPRequest request = new HTTPRequest();

request.setMethod(HttpMethods.DELETE);
request.setMethod(HttpMethod.DELETE.asString());
request.setResource(resource);
request.setQueryParams(queryParams);

Expand All @@ -310,7 +323,7 @@ private LRSResponse deleteDocument(String resource, Map<String, String> queryPar

private LRSResponse saveDocument(String resource, Map<String, String> queryParams, Document document) {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethods.PUT);
request.setMethod(HttpMethod.PUT.asString());
request.setResource(resource);
request.setQueryParams(queryParams);
request.setContentType(document.getContentType());
Expand All @@ -336,7 +349,7 @@ private LRSResponse saveDocument(String resource, Map<String, String> queryParam

private LRSResponse updateDocument(String resource, Map<String, String> queryParams, Document document) {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethods.POST);
request.setMethod(HttpMethod.POST.asString());
request.setResource(resource);
request.setQueryParams(queryParams);
request.setContentType(document.getContentType());
Expand All @@ -362,7 +375,7 @@ private LRSResponse updateDocument(String resource, Map<String, String> queryPar

private ProfileKeysLRSResponse getProfileKeys(String resource, HashMap<String, String> queryParams) {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethods.GET);
request.setMethod(HttpMethod.GET.asString());
request.setResource(resource);
request.setQueryParams(queryParams);

Expand Down Expand Up @@ -394,7 +407,7 @@ private ProfileKeysLRSResponse getProfileKeys(String resource, HashMap<String, S
@Override
public AboutLRSResponse about() {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethods.GET);
request.setMethod(HttpMethod.GET.asString());
request.setResource("about");

HTTPResponse response = makeSyncRequest(request);
Expand Down Expand Up @@ -434,10 +447,10 @@ public StatementLRSResponse saveStatement(Statement statement) {
}

if (statement.getId() == null) {
lrsResponse.getRequest().setMethod(HttpMethods.POST);
lrsResponse.getRequest().setMethod(HttpMethod.POST.asString());
}
else {
lrsResponse.getRequest().setMethod(HttpMethods.PUT);
lrsResponse.getRequest().setMethod(HttpMethod.PUT.asString());
lrsResponse.getRequest().setQueryParams(new HashMap<String, String>());
lrsResponse.getRequest().getQueryParams().put("statementId", statement.getId().toString());
}
Expand Down Expand Up @@ -483,7 +496,7 @@ public StatementsResultLRSResponse saveStatements(List<Statement> statements) {

lrsResponse.setRequest(new HTTPRequest());
lrsResponse.getRequest().setResource("statements");
lrsResponse.getRequest().setMethod(HttpMethods.POST);
lrsResponse.getRequest().setMethod(HttpMethod.POST.asString());
lrsResponse.getRequest().setContentType("application/json");
try {
lrsResponse.getRequest().setContent(Mapper.getWriter(this.usePrettyJSON()).writeValueAsBytes(rootNode));
Expand Down Expand Up @@ -548,7 +561,7 @@ public StatementsResultLRSResponse queryStatements(StatementsQueryInterface quer
StatementsResultLRSResponse lrsResponse = new StatementsResultLRSResponse();

lrsResponse.setRequest(new HTTPRequest());
lrsResponse.getRequest().setMethod(HttpMethods.GET);
lrsResponse.getRequest().setMethod(HttpMethod.GET.asString());
lrsResponse.getRequest().setResource("statements");

try {
Expand Down Expand Up @@ -590,7 +603,7 @@ public StatementsResultLRSResponse moreStatements(String moreURL) {

HTTPRequest request = new HTTPRequest();
request.setResource(url);
request.setMethod(HttpMethods.GET);
request.setMethod(HttpMethod.GET.asString());
HTTPResponse response = makeSyncRequest(request);

StatementsResultLRSResponse lrsResponse = new StatementsResultLRSResponse(request, response);
Expand Down Expand Up @@ -699,7 +712,7 @@ public LRSResponse clearState(Activity activity, Agent agent, UUID registration)
@Override
public ActivityLRSResponse retrieveActivity(Activity activity) {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethods.GET);
request.setMethod(HttpMethod.GET.asString());
request.setResource("activities");
request.setQueryParams(new HashMap<String, String>());
request.getQueryParams().put("activityId", activity.getId().toString());
Expand Down Expand Up @@ -787,7 +800,7 @@ public LRSResponse deleteActivityProfile(ActivityProfileDocument profile) {
@Override
public PersonLRSResponse retrievePerson(Agent agent) {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethods.GET);
request.setMethod(HttpMethod.GET.asString());
request.setResource("agents");
request.setQueryParams(new HashMap<String, String>());
request.getQueryParams().put("agent", agent.toJSON(this.getVersion(), this.usePrettyJSON()));
Expand Down
Loading

0 comments on commit 9cc0eb3

Please sign in to comment.