Skip to content

Commit

Permalink
Reviewed resources closing.
Browse files Browse the repository at this point in the history
  • Loading branch information
kausandr committed Nov 18, 2019
1 parent d0023f6 commit 7a497dc
Show file tree
Hide file tree
Showing 15 changed files with 91 additions and 70 deletions.
30 changes: 20 additions & 10 deletions src/main/java/com/jkoolcloud/client/api/service/JKQuery.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,16 @@
*/
package com.jkoolcloud.client.api.service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.TimeZone;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/**
Expand All @@ -33,7 +34,7 @@
* @author albert
*/
public class JKQuery extends JKService {
HttpClient httpClient = HttpClients.createDefault();
CloseableHttpClient httpClient = HttpClients.createDefault();

boolean trace = false;
String repoId = "";
Expand Down Expand Up @@ -201,7 +202,7 @@ public Response call(JKStatement query) throws JKStreamException {
* @throws JKStreamException
* if error occurs during a call
*/
public HttpResponse get(String query) throws JKStreamException {
public CloseableHttpResponse get(String query) throws JKStreamException {
return get(query, DEFAULT_MAX_ROWS);
}

Expand All @@ -214,7 +215,7 @@ public HttpResponse get(String query) throws JKStreamException {
* @throws JKStreamException
* if error occurs during a call
*/
public HttpResponse get(JKStatement query) throws JKStreamException {
public CloseableHttpResponse get(JKStatement query) throws JKStreamException {
return get(query.getQuery(), query.getMaxRows());
}

Expand Down Expand Up @@ -264,9 +265,9 @@ public Response call(String _query, String _token, String _repo, String _tz, Str
.queryParam(JK_TRACE_KEY, _trace) //
.queryParam(JK_MAX_ROWS_KEY, _maxRows);

return target.request(MediaType.APPLICATION_JSON)
.header(X_API_KEY, _token)
.header(X_API_TOKEN, _token)
return target.request(MediaType.APPLICATION_JSON) //
.header(X_API_KEY, _token) //
.header(X_API_TOKEN, _token) //
.get();
}

Expand All @@ -281,7 +282,7 @@ public Response call(String _query, String _token, String _repo, String _tz, Str
* @throws JKStreamException
* if error occurs during a call
*/
public HttpResponse get(String query, int maxRows) throws JKStreamException {
public CloseableHttpResponse get(String query, int maxRows) throws JKStreamException {
try {
String urlQuery = JK_QUERY_KEY + "=" + URLEncoder.encode(query, "UTF-8") //
+ "&" + JK_TOKEN_KEY + "=" + getToken() //
Expand All @@ -295,10 +296,19 @@ public HttpResponse get(String query, int maxRows) throws JKStreamException {
request.addHeader(X_API_KEY, getToken());
request.addHeader(X_API_TOKEN, getToken());
request.addHeader(CONTENT_TYPE, MediaType.APPLICATION_JSON);
HttpResponse response = httpClient.execute(request);
CloseableHttpResponse response = httpClient.execute(request);
return response;
} catch (Throwable e) {
throw new JKStreamException(300, "Failed: path=" + getServiceUrl() + ", query=" + query, e);
}
}

@Override
public void close() throws IOException {
if (httpClient != null) {
httpClient.close();
}

super.close();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
*/
package com.jkoolcloud.client.api.service;

import java.io.Closeable;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
Expand All @@ -35,7 +34,7 @@
*
* @author albert
*/
public class JKQueryAsync extends JKQuery implements Closeable {
public class JKQueryAsync extends JKQuery {
private static final String DEFAULT_QUERY = "SUBSCRIBE TO ORPHANS"; // dummy query associated with default response
// handler
private final ConcurrentMap<String, JKQueryHandle> SUBID_MAP = new ConcurrentHashMap<>();
Expand Down Expand Up @@ -276,8 +275,9 @@ public synchronized JKQueryAsync connect() throws IOException {
public synchronized void close() throws IOException {
if (socket != null) {
socket.disconnect();
socket = null;
}
socket = null;
super.close();
}

/**
Expand Down Expand Up @@ -362,7 +362,7 @@ public JKQueryHandle callAsync(String query, int maxRows, JKQueryCallback callba
throw new IllegalArgumentException("callback can not be null");
}
JKQueryHandle qHandle = createQueryHandle(query, getTimeZone(), getDateRange(), getRepoId(), callback)
.setMaxRows(maxRows).setTrace(this.isTrace());
.setMaxRows(maxRows).setTrace(isTrace());
return callAsync(qHandle);
}

Expand Down Expand Up @@ -465,15 +465,16 @@ public JKQueryAsync callAsync(String query, String id, int maxRows) throws IOExc
/**
* Send JSON query via a websocket
*
* @param jsonQuery json query
* @param jsonQuery
* json query
* @return websocket client
* @throws IOException
* on error during IO
*/
private JKWSClient sendJsonQuery(JsonObject jsonQuery) throws IOException {
return socket.sendMessageAsync(jsonQuery.toString());
}

/**
* Cancel all active subscriptions
*
Expand Down Expand Up @@ -643,7 +644,6 @@ private void cleanHandlers(String callName, JKQueryHandle qhandle) {

@Override
public String toString() {
return getClass().getSimpleName() + " {" //
+ "\", uri: \"" + webSockUri + "\"}";
return getClass().getSimpleName() + " {" + "\", uri: \"" + webSockUri + "\"}";
}
}
16 changes: 15 additions & 1 deletion src/main/java/com/jkoolcloud/client/api/service/JKService.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
*/
package com.jkoolcloud.client.api.service;

import java.io.Closeable;
import java.io.IOException;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
Expand All @@ -27,7 +30,7 @@
*
* @author albert
*/
abstract public class JKService implements JKQIConstants {
abstract public class JKService implements JKQIConstants, Closeable {

String token;
String basePath;
Expand Down Expand Up @@ -104,4 +107,15 @@ public String getServiceUrl() {
public String serialize(Object obj) throws JKStreamException {
return JKUtils.serialize(mapper, obj);
}

@Override
public void close() throws IOException {
if (rsClient != null) {
try {
rsClient.close();
} catch (Throwable t) {
throw new IOException("Failed to close JAX-RS client", t);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package com.jkoolcloud.client.api.service;

import java.io.IOException;
import java.io.StringReader;

import javax.json.Json;
Expand Down Expand Up @@ -53,6 +54,11 @@ public void onMessage(JKWSClient client, String message) {

@Override
public void onClose(JKWSClient client, Session userSession, CloseReason reason) {
try {
jkagent.close();
} catch (IOException e) {
}

synchronized (jkagent.conHandlers) {
for (JKConnectionHandler ch : jkagent.conHandlers) {
ch.close(jkagent, reason);
Expand Down
22 changes: 10 additions & 12 deletions src/main/java/com/jkoolcloud/client/api/utils/JKQLCmd.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,26 +28,24 @@ public static void main(String[] args) {
}
options.print();
JKTraceQueryCallback callback = new JKTraceQueryCallback(System.out, options.json_path, options.trace);
try {

try (JKQueryAsync jkQueryAsync = new JKQueryAsync(System.getProperty("jk.ws.uri", options.uri),
System.getProperty("jk.access.token", options.token))) {
// setup jKool WebSocket connection and connect
JKQueryAsync jkQueryAsync = new JKQueryAsync(System.getProperty("jk.ws.uri", options.uri),
System.getProperty("jk.access.token", options.token));
if (options.retryTimeMs > 0) {
jkQueryAsync.addConnectionHandler(new JKRetryConnectionHandler(options.retryTimeMs, TimeUnit.MILLISECONDS));
jkQueryAsync
.addConnectionHandler(new JKRetryConnectionHandler(options.retryTimeMs, TimeUnit.MILLISECONDS));
}
jkQueryAsync.setTimeZone(options.timezone)
.setDateFilter(options.daterange)
.setRepoId(options.reponame)
.setTrace(options.trace);
jkQueryAsync.setTimeZone(options.timezone).setDateFilter(options.daterange).setRepoId(options.reponame)
.setTrace(options.trace);

jkQueryAsync.addConnectionHandler(new JKTraceConnectionHandler(System.out, options.trace));
jkQueryAsync.addDefaultCallbackHandler(callback);
jkQueryAsync.connect();

// run query in async mode with a callback
JKQueryHandle qhandle = jkQueryAsync.callAsync(options.query, options.maxRows, callback);
System.out.println("Running query=\"" + qhandle.getQuery() + "\", id=" + qhandle.getId() + ", trace=" + options.trace);
System.out.println(
"Running query=\"" + qhandle.getQuery() + "\", id=" + qhandle.getId() + ", trace=" + options.trace);
if (!qhandle.isSubscribeQuery()) {
// standard query only one response expected
qhandle.awaitOnDone(options.waitTimeMs, TimeUnit.MILLISECONDS);
Expand All @@ -60,12 +58,12 @@ public static void main(String[] args) {
qhandle.awaitOnDone(options.waitTimeMs, TimeUnit.MILLISECONDS);
}
}
jkQueryAsync.close();
} catch (Throwable e) {
System.err.println("Failed to execute: " + options.toString());
e.printStackTrace();
} finally {
System.out.println("Stats: msg.recvd=" + callback.getMsgCount() + ", err.count=" + callback.getErrorCount());
System.out
.println("Stats: msg.recvd=" + callback.getMsgCount() + ", err.count=" + callback.getErrorCount());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,7 @@
public class RestSample1 {

public static void main(String[] args) {
try {

JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"));
try (JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"))) {

// Create the first event which is a message received event
// representing a message received in a
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@
public class RestSample2 {

public static void main(String[] args) {
try {
JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"));
try (JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"))) {

// Create the first event which is a message received event
// representing a message received in a
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@
public class RestSample3 {

public static void main(String[] args) {
try {
JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"));
try (JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"))) {

// Create the first event which is a message received event
// representing a message received in a
Expand Down
20 changes: 10 additions & 10 deletions src/main/java/com/jkoolcloud/client/samples/query/CallExample.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,16 @@

public class CallExample {
public static void main(String[] args) throws ProcessingException {
try {
Properties props = new Properties();
props.setProperty(JKCmdOptions.PROP_URI, JKQuery.JKOOL_QUERY_URL);
JKCmdOptions options = new JKCmdOptions(CallExample.class, args, props);
if (options.usage != null) {
System.out.println(options.usage);
System.exit(-1);
}
options.print();
JKQuery jkQuery = new JKQuery(options.token);
Properties props = new Properties();
props.setProperty(JKCmdOptions.PROP_URI, JKQuery.JKOOL_QUERY_URL);
JKCmdOptions options = new JKCmdOptions(CallExample.class, args, props);
if (options.usage != null) {
System.out.println(options.usage);
System.exit(-1);
}
options.print();

try (JKQuery jkQuery = new JKQuery(options.token)) {
Response res = jkQuery.call(options.query);

int status = res.getStatus();
Expand Down
26 changes: 14 additions & 12 deletions src/main/java/com/jkoolcloud/client/samples/query/GetExample.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import java.util.Properties;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

import com.jkoolcloud.client.api.service.JKQuery;
Expand All @@ -29,18 +29,20 @@

public class GetExample {
public static void main(String[] args) {
try {
Properties props = new Properties();
props.setProperty(JKCmdOptions.PROP_URI, JKQuery.JKOOL_QUERY_URL);
JKCmdOptions options = new JKCmdOptions(GetExample.class, args, props);
if (options.usage != null) {
System.out.println(options.usage);
System.exit(-1);
}
options.print();
JKQuery jkQuery = new JKQuery(options.token);
HttpResponse response = jkQuery.get(options.query);
Properties props = new Properties();
props.setProperty(JKCmdOptions.PROP_URI, JKQuery.JKOOL_QUERY_URL);
JKCmdOptions options = new JKCmdOptions(GetExample.class, args, props);
if (options.usage != null) {
System.out.println(options.usage);
System.exit(-1);
}
options.print();

try (JKQuery jkQuery = new JKQuery(options.token)) {
CloseableHttpResponse response = jkQuery.get(options.query);
System.out.println(EntityUtils.toString(response.getEntity()));
EntityUtils.consumeQuietly(response.getEntity());
response.close();
} catch (Throwable e) {
e.printStackTrace();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@
public class MovieEvent1 {

public static void main(String[] args) {
try {
JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"));
try (JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"))) {

// Create the Event
// Attach it's properties
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@
public class MovieEvents2 {

public static void main(String[] args) {
try {
JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"));
try (JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"))) {

// Create some custom fields
Property propertyName = new Property("MovieName", "Casablanca");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@
public class MovieEvents3 {

public static void main(String[] args) {
try {
JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"));
try (JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"))) {

// Create the activity that the events will be attached to
Activity activity = new Activity();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@
public class MovieEvents4 {

public static void main(String[] args) {
try {
JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"));
try (JKStream jkSend = new JKStream(System.getProperty("jk.access.token", "access-token"))) {

// Create the activity that the events will be attached to
Activity activity = new Activity();
Expand Down
Loading

0 comments on commit 7a497dc

Please sign in to comment.