1515*/
1616package com .rusticisoftware .tincan ;
1717
18+ import org .apache .commons .codec .binary .Base64 ;
1819import com .fasterxml .jackson .core .JsonProcessingException ;
1920import com .fasterxml .jackson .databind .JsonNode ;
2021import com .fasterxml .jackson .databind .node .ArrayNode ;
2122import com .rusticisoftware .tincan .documents .ActivityProfileDocument ;
2223import com .rusticisoftware .tincan .documents .AgentProfileDocument ;
2324import com .rusticisoftware .tincan .documents .Document ;
2425import com .rusticisoftware .tincan .documents .StateDocument ;
26+ import com .rusticisoftware .tincan .exceptions .*;
27+ import com .rusticisoftware .tincan .lrsresponses .*;
2528import com .rusticisoftware .tincan .http .HTTPRequest ;
2629import com .rusticisoftware .tincan .http .HTTPResponse ;
27- import com .rusticisoftware .tincan .lrsresponses .*;
28-
30+ import com .rusticisoftware .tincan .json .Mapper ;
31+ import com .rusticisoftware .tincan .json .StringOfJSON ;
32+ import com .rusticisoftware .tincan .v10x .StatementsQuery ;
33+ import org .eclipse .jetty .client .api .ContentResponse ;
34+ import org .eclipse .jetty .client .api .Request ;
35+ import org .eclipse .jetty .client .api .Response ;
36+ import org .eclipse .jetty .client .HttpClient ;
37+ import org .eclipse .jetty .client .util .BytesContentProvider ;
38+ import org .eclipse .jetty .http .HttpField ;
39+ import org .eclipse .jetty .http .HttpMethod ;
40+ import org .eclipse .jetty .util .HttpCookieStore ;
41+ import org .eclipse .jetty .util .ssl .SslContextFactory ;
2942import lombok .Data ;
3043import lombok .NoArgsConstructor ;
3144
3649import java .net .URLEncoder ;
3750import java .util .*;
3851
39- import org .apache .commons .codec .binary .Base64 ;
40- import org .eclipse .jetty .client .ContentExchange ;
41- import org .eclipse .jetty .client .HttpClient ;
42- import org .eclipse .jetty .client .HttpExchange ;
43- import org .eclipse .jetty .http .HttpMethods ;
44- import org .eclipse .jetty .io .Buffer ;
45- import org .eclipse .jetty .io .ByteArrayBuffer ;
46-
47- import com .rusticisoftware .tincan .exceptions .*;
48- import com .rusticisoftware .tincan .json .Mapper ;
49- import com .rusticisoftware .tincan .json .StringOfJSON ;
50- import com .rusticisoftware .tincan .v10x .StatementsQuery ;
51-
52- import static org .eclipse .jetty .client .HttpClient .CONNECTOR_SELECT_CHANNEL ;
53-
5452/**
5553 * Class used to communicate with a TCAPI endpoint synchronously
5654 */
5755// TODO: handle extended on all requests
5856@ Data
5957@ NoArgsConstructor
6058public class RemoteLRS implements LRS {
61- private static int TIMEOUT_CONNECT = 5 * 1000 ;
59+ private static long TIMEOUT_CONNECT = 5 * 1000 ;
6260
61+ private static Boolean _ourClient = false ;
6362 private static HttpClient _httpClient ;
6463 private static HttpClient httpClient () throws Exception {
6564 if (_httpClient == null ) {
66- _httpClient = new HttpClient ();
67- _httpClient .setConnectorType (CONNECTOR_SELECT_CHANNEL );
65+ _httpClient = new HttpClient (new SslContextFactory ());
6866 _httpClient .setConnectTimeout (TIMEOUT_CONNECT );
67+ _httpClient .setFollowRedirects (false );
68+ _httpClient .setCookieStore (new HttpCookieStore .Empty ());
6969 _httpClient .start ();
70+
71+ _ourClient = true ;
7072 }
7173
7274 return _httpClient ;
7375 }
7476
75- public static int getHTTPClientConnectTimeout () {
77+ /**
78+ * Get the connect timeout value for the default HTTP client
79+ *
80+ * @return
81+ * @deprecated set your own HTTP client using {@link #setHttpClient()}
82+ */
83+ @ Deprecated
84+ public static long getHTTPClientConnectTimeout () {
7685 return _httpClient .getConnectTimeout ();
7786 }
78- public static void setHTTPClientConnectTimeout (int timeout ) {
87+
88+ /**
89+ * Set the connect timeout value for the default HTTP client
90+ *
91+ * @deprecated set your own HTTP client using {@link #setHttpClient()}
92+ */
93+ @ Deprecated
94+ public static void setHTTPClientConnectTimeout (long timeout ) {
7995 _httpClient .setConnectTimeout (timeout );
8096 }
8197
98+ public static void setHttpClient (HttpClient client ) throws Exception {
99+ if (_httpClient != null && _ourClient ) {
100+ _httpClient .stop ();
101+ _httpClient .destroy ();
102+ }
103+ _ourClient = false ;
104+ _httpClient = client ;
105+ }
106+
107+ public static void destroy () throws Exception {
108+ setHttpClient (null );
109+ }
110+
82111 private URL endpoint ;
83112 private TCAPIVersion version = this .getVersion ();
84113 private String username ;
@@ -167,63 +196,47 @@ private HTTPResponse makeSyncRequest(HTTPRequest req) {
167196 //Overload some of an ContentExchange object's functions with anonymous inner functions
168197 //Access the HTTPResponse variable via a closure
169198 final HTTPResponse response = new HTTPResponse ();
170- ContentExchange webReq = new ContentExchange () {
171- protected void onResponseStatus (Buffer version , int status , Buffer reason ) throws IOException {
172- super .onResponseStatus (version , status , reason );
173- response .setStatus (status );
174- response .setStatusMsg (reason .toString ());
175- }
176199
177- @ Override
178- protected void onResponseHeader (Buffer name , Buffer value ) throws IOException {
179- super .onResponseHeader (name , value );
180-
181- response .setHeader (name .toString (), value .toString ());
200+ try {
201+ final Request webReq = httpClient ().
202+ newRequest (url ).
203+ method (HttpMethod .fromString (req .getMethod ())).
204+ header ("X-Experience-API-Version" , this .version .toString ()).
205+ onResponseHeaders (new Response .HeadersListener () {
206+ @ Override
207+ public void onHeaders (Response webResp ) {
208+ response .setStatus (webResp .getStatus ());
209+ response .setStatusMsg (webResp .getReason ());
210+ for (HttpField header : webResp .getHeaders ()) {
211+ response .setHeader (header .getName (), header .getValue ());
212+ }
213+ }
214+ });
215+
216+ if (this .auth != null ) {
217+ webReq .header ("Authorization" , this .auth );
182218 }
183-
184- @ Override
185- protected void onResponseComplete () throws IOException {
186- super . onResponseComplete ();
187-
188- response . setContentBytes ( this . getResponseContentBytes ());
219+ if ( req . getHeaders () != null ) {
220+ Iterator it = req . getHeaders (). entrySet (). iterator ();
221+ while ( it . hasNext ()) {
222+ Map . Entry entry = ( Map . Entry ) it . next ();
223+ webReq . header ( entry . getKey (). toString (), entry . getValue (). toString ());
224+ }
189225 }
190- };
191226
192- webReq .setURL (url );
193- webReq .setMethod (req .getMethod ());
194-
195- webReq .addRequestHeader ("X-Experience-API-Version" , this .version .toString ());
196- if (this .auth != null ) {
197- webReq .addRequestHeader ("Authorization" , this .auth );
198- }
199- if (req .getHeaders () != null ) {
200- Iterator it = req .getHeaders ().entrySet ().iterator ();
201- while (it .hasNext ()) {
202- Map .Entry entry = (Map .Entry ) it .next ();
203- webReq .addRequestHeader (entry .getKey ().toString (), entry .getValue ().toString ());
227+ if (req .getContentType () != null ) {
228+ webReq .header ("Content-Type" , req .getContentType ());
229+ }
230+ else {
231+ webReq .header ("Content-Type" , "application/octet-stream" );
204232 }
205- }
206-
207- if (req .getContentType () != null ) {
208- webReq .setRequestContentType (req .getContentType ());
209- }
210- else {
211- webReq .setRequestContentType ("application/octet-stream" );
212- }
213-
214- if (req .getContent () != null ) {
215- webReq .setRequestContent (new ByteArrayBuffer (req .getContent ()));
216- }
217-
218- try {
219- httpClient ().send (webReq );
220-
221- // Waits until the exchange is terminated
222- int exchangeState = webReq .waitForDone ();
223233
224- if (exchangeState != HttpExchange . STATUS_COMPLETED ) {
225- throw new FailedHTTPExchange ( exchangeState );
234+ if (req . getContent () != null ) {
235+ webReq . content ( new BytesContentProvider ( req . getContent ()) );
226236 }
237+
238+ final ContentResponse webResp = webReq .send ();
239+ response .setContentBytes (webResp .getContent ());
227240 } catch (Exception ex ) {
228241 response .setStatus (400 );
229242 response .setStatusMsg ("Exception in RemoteLRS.makeSyncRequest(): " + ex );
@@ -234,7 +247,7 @@ protected void onResponseComplete() throws IOException {
234247
235248 private StatementLRSResponse getStatement (String id , String paramName ) {
236249 HTTPRequest request = new HTTPRequest ();
237- request .setMethod (HttpMethods .GET );
250+ request .setMethod (HttpMethod .GET . asString () );
238251 request .setResource ("statements" );
239252 request .setQueryParams (new HashMap <String , String >());
240253 request .getQueryParams ().put (paramName , id );
@@ -262,7 +275,7 @@ private StatementLRSResponse getStatement(String id, String paramName) {
262275
263276 private LRSResponse getDocument (String resource , Map <String , String > queryParams , Document document ) {
264277 HTTPRequest request = new HTTPRequest ();
265- request .setMethod (HttpMethods .GET );
278+ request .setMethod (HttpMethod .GET . asString () );
266279 request .setResource (resource );
267280 request .setQueryParams (queryParams );
268281
@@ -290,7 +303,7 @@ else if (response.getStatus() == 404) {
290303 private LRSResponse deleteDocument (String resource , Map <String , String > queryParams ) {
291304 HTTPRequest request = new HTTPRequest ();
292305
293- request .setMethod (HttpMethods .DELETE );
306+ request .setMethod (HttpMethod .DELETE . asString () );
294307 request .setResource (resource );
295308 request .setQueryParams (queryParams );
296309
@@ -310,7 +323,7 @@ private LRSResponse deleteDocument(String resource, Map<String, String> queryPar
310323
311324 private LRSResponse saveDocument (String resource , Map <String , String > queryParams , Document document ) {
312325 HTTPRequest request = new HTTPRequest ();
313- request .setMethod (HttpMethods .PUT );
326+ request .setMethod (HttpMethod .PUT . asString () );
314327 request .setResource (resource );
315328 request .setQueryParams (queryParams );
316329 request .setContentType (document .getContentType ());
@@ -336,7 +349,7 @@ private LRSResponse saveDocument(String resource, Map<String, String> queryParam
336349
337350 private LRSResponse updateDocument (String resource , Map <String , String > queryParams , Document document ) {
338351 HTTPRequest request = new HTTPRequest ();
339- request .setMethod (HttpMethods .POST );
352+ request .setMethod (HttpMethod .POST . asString () );
340353 request .setResource (resource );
341354 request .setQueryParams (queryParams );
342355 request .setContentType (document .getContentType ());
@@ -362,7 +375,7 @@ private LRSResponse updateDocument(String resource, Map<String, String> queryPar
362375
363376 private ProfileKeysLRSResponse getProfileKeys (String resource , HashMap <String , String > queryParams ) {
364377 HTTPRequest request = new HTTPRequest ();
365- request .setMethod (HttpMethods .GET );
378+ request .setMethod (HttpMethod .GET . asString () );
366379 request .setResource (resource );
367380 request .setQueryParams (queryParams );
368381
@@ -394,7 +407,7 @@ private ProfileKeysLRSResponse getProfileKeys(String resource, HashMap<String, S
394407 @ Override
395408 public AboutLRSResponse about () {
396409 HTTPRequest request = new HTTPRequest ();
397- request .setMethod (HttpMethods .GET );
410+ request .setMethod (HttpMethod .GET . asString () );
398411 request .setResource ("about" );
399412
400413 HTTPResponse response = makeSyncRequest (request );
@@ -434,10 +447,10 @@ public StatementLRSResponse saveStatement(Statement statement) {
434447 }
435448
436449 if (statement .getId () == null ) {
437- lrsResponse .getRequest ().setMethod (HttpMethods .POST );
450+ lrsResponse .getRequest ().setMethod (HttpMethod .POST . asString () );
438451 }
439452 else {
440- lrsResponse .getRequest ().setMethod (HttpMethods .PUT );
453+ lrsResponse .getRequest ().setMethod (HttpMethod .PUT . asString () );
441454 lrsResponse .getRequest ().setQueryParams (new HashMap <String , String >());
442455 lrsResponse .getRequest ().getQueryParams ().put ("statementId" , statement .getId ().toString ());
443456 }
@@ -483,7 +496,7 @@ public StatementsResultLRSResponse saveStatements(List<Statement> statements) {
483496
484497 lrsResponse .setRequest (new HTTPRequest ());
485498 lrsResponse .getRequest ().setResource ("statements" );
486- lrsResponse .getRequest ().setMethod (HttpMethods .POST );
499+ lrsResponse .getRequest ().setMethod (HttpMethod .POST . asString () );
487500 lrsResponse .getRequest ().setContentType ("application/json" );
488501 try {
489502 lrsResponse .getRequest ().setContent (Mapper .getWriter (this .usePrettyJSON ()).writeValueAsBytes (rootNode ));
@@ -548,7 +561,7 @@ public StatementsResultLRSResponse queryStatements(StatementsQueryInterface quer
548561 StatementsResultLRSResponse lrsResponse = new StatementsResultLRSResponse ();
549562
550563 lrsResponse .setRequest (new HTTPRequest ());
551- lrsResponse .getRequest ().setMethod (HttpMethods .GET );
564+ lrsResponse .getRequest ().setMethod (HttpMethod .GET . asString () );
552565 lrsResponse .getRequest ().setResource ("statements" );
553566
554567 try {
@@ -590,7 +603,7 @@ public StatementsResultLRSResponse moreStatements(String moreURL) {
590603
591604 HTTPRequest request = new HTTPRequest ();
592605 request .setResource (url );
593- request .setMethod (HttpMethods .GET );
606+ request .setMethod (HttpMethod .GET . asString () );
594607 HTTPResponse response = makeSyncRequest (request );
595608
596609 StatementsResultLRSResponse lrsResponse = new StatementsResultLRSResponse (request , response );
@@ -699,7 +712,7 @@ public LRSResponse clearState(Activity activity, Agent agent, UUID registration)
699712 @ Override
700713 public ActivityLRSResponse retrieveActivity (Activity activity ) {
701714 HTTPRequest request = new HTTPRequest ();
702- request .setMethod (HttpMethods .GET );
715+ request .setMethod (HttpMethod .GET . asString () );
703716 request .setResource ("activities" );
704717 request .setQueryParams (new HashMap <String , String >());
705718 request .getQueryParams ().put ("activityId" , activity .getId ().toString ());
@@ -787,7 +800,7 @@ public LRSResponse deleteActivityProfile(ActivityProfileDocument profile) {
787800 @ Override
788801 public PersonLRSResponse retrievePerson (Agent agent ) {
789802 HTTPRequest request = new HTTPRequest ();
790- request .setMethod (HttpMethods .GET );
803+ request .setMethod (HttpMethod .GET . asString () );
791804 request .setResource ("agents" );
792805 request .setQueryParams (new HashMap <String , String >());
793806 request .getQueryParams ().put ("agent" , agent .toJSON (this .getVersion (), this .usePrettyJSON ()));
0 commit comments