diff --git a/.travis.yml b/.travis.yml index 2cf7cfc..e0f9794 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,15 +1,13 @@ language: java - jdk: - - openjdk6 - - openjdk7 - - oraclejdk7 - - oraclejdk8 - +- openjdk6 +- openjdk7 +- oraclejdk7 +- oraclejdk8 install: mvn install -Dgpg.skip=true -DskipTests - notifications: email: on_success: never - + slack: + secure: LOJ5Om++3aQqHzKmEUeZL4TNvBlZ/v8MvSMcq7npfCV9hSb3IvmoNhBhAR9xYvNjEQb/okCMLLtxQe2m/QNMH84EM6wxq0+suZedwMY10zRkNV90d/nfHQPgZFvJJuD3Wm3kr0JB45lt8ClxN2njFYf7JDhGeyu8XeXti+9QZixrhhJfuxoZEmgUXLCfKMVUgvM4kfAduV2wvedXHx5RIz1dMrOK0JPUsbzPQZwt6Pb1hCPcVuhlOgo/F4Rer0jkdJ3tXrK5Xki2rRtax0LLqHgh+JFB+IpJovMPIMoAJ5/tZDMigQLqQvOWcS2zBXSv+mENXj7ZUknrna4aVQ8DGnUjk6bPPUjdRZIWGQNqI1LMUsf/SPB3OWUol2VaApdGH93D5L9BGN9mA3fH+4LijFs4ttbKt9DBMUlug6WOr7teuYlnq0v2O9XJpUh+vpeQCerho2j9fLGyoEj31S89SF/v/PsJtuVkETR8eu2qMJK5T3FL7jzqaYIXQFemtaOqqfsqm+Ju+tKIZN9aCsOAcnORggnMTebe5AzYfxkN4F0O746/nFLFDNeu6fNUYx2cXRDFB1pADYBZygbQ0yfDRq80W9CYuSPzqbbcvy1EJoRysc5lORFvK0xBqiOPR253WIP6hoRcBqLdK/k9tqyUAcMASJqpSJMk4yGmzCp0tiU= sudo: false diff --git a/README.md b/README.md index 4da12db..91274c7 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Add this dependency to your project's POM: ```xml - com.wia + io.wia wia-java 0.1.0 diff --git a/pom.xml b/pom.xml index b3592cc..d8cdbe7 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,6 @@ 4.0.0 - com.wia + io.wia wia-java jar 0.1.0 @@ -41,6 +41,16 @@ retrofit 2.0.2 + + log4j + log4j + 1.2.17 + + + org.eclipse.paho + org.eclipse.paho.client.mqttv3 + 1.0.2 + Wia Java SDK diff --git a/src/main/java/com/wia/Wia.java b/src/main/java/com/wia/Wia.java deleted file mode 100644 index 4ebe353..0000000 --- a/src/main/java/com/wia/Wia.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.wia; - -import java.net.PasswordAuthentication; -import java.net.Proxy; - -public abstract class Wia { - public static final String LIVE_REST_API_BASE = "https://api.wia.io"; - public static final String LIVE_MQTT_API_BASE = "mqtts://api.wia.io"; - public static final String VERSION = "0.1.0"; - public static volatile String apiKey; - public static volatile String apiVersion; - - private static volatile String restApiBase = LIVE_REST_API_BASE; - private static volatile String mqttApiBase = LIVE_MQTT_API_BASE; - - private static volatile Proxy connectionProxy = null; - private static volatile PasswordAuthentication proxyCredential = null; - - /** - * (FOR TESTING ONLY) If you'd like your Rest API requests to hit your own - * (mocked) server, you can set this up here by overriding the base api URL. - */ - public static void overrideRestApiBase(final String overriddenRestApiBase) { - restApiBase = overriddenRestApiBase; - } - - public static String getRestApiBase() { - return restApiBase; - } - - /** - * (FOR TESTING ONLY) If you'd like your MQTT API requests to hit your own - * (mocked) server, you can set this up here by overriding the base api URL. - */ - public static void overrideMqttApiBase(final String overriddenMqttApiBase) { - mqttApiBase = overriddenMqttApiBase; - } - - public static String getMqttApiBase() { - return mqttApiBase; - } - - /** - * Set proxy to tunnel all Stripe connections - * - * @param proxy proxy host and port setting - */ - public static void setConnectionProxy(final Proxy proxy) { - connectionProxy = proxy; - } - - public static Proxy getConnectionProxy() { - return connectionProxy; - } - - /** - * Provide credential for proxy authorization if required - * - * @param auth proxy required userName and password - */ - public static void setProxyCredential(final PasswordAuthentication auth) { - proxyCredential = auth; - } - - public static PasswordAuthentication getProxyCredential() { - return proxyCredential; - } - -} diff --git a/src/main/java/com/wia/model/Event.java b/src/main/java/com/wia/model/Event.java deleted file mode 100644 index c1a4ddc..0000000 --- a/src/main/java/com/wia/model/Event.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.wia.model; - -public class Event { - String id; - String name; - Long timestamp; - Long receivedTimestamp; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Long getTimestamp() { - return timestamp; - } - - public void setTimestamp(Long timestamp) { - this.timestamp = timestamp; - } - - public Long getReceivedTimestamp() { - return receivedTimestamp; - } - - public void setReceivedTimestamp(Long receivedTimestamp) { - this.receivedTimestamp = receivedTimestamp; - } -} diff --git a/src/main/java/io/wia/Wia.java b/src/main/java/io/wia/Wia.java new file mode 100644 index 0000000..a73ceae --- /dev/null +++ b/src/main/java/io/wia/Wia.java @@ -0,0 +1,81 @@ +package io.wia; + +import io.wia.exception.APIConnectionException; +import io.wia.exception.APIException; +import io.wia.exception.AuthenticationException; +import io.wia.exception.InvalidRequestException; +import io.wia.model.Whoami; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; +import org.eclipse.paho.client.mqttv3.MqttException; + +public abstract class Wia { + private static Logger logger = LogManager.getLogger(Wia.class); + + public static final String LIVE_REST_API_BASE = "https://api.wia.io"; + public static final String LIVE_STREAM_API_ENDPOINT = "tcp://api.wia.io:1883"; + + public static final String VERSION = "0.1.0"; + public static volatile String apiVersion; + + private static volatile String secretKey; + + private static volatile Whoami clientInfo; + + private static volatile String restApiBase = LIVE_REST_API_BASE; + private static volatile String streamApiEndpoint = LIVE_STREAM_API_ENDPOINT; + + public static void overrideRestApiBase(final String overriddenRestApiBase) { + restApiBase = overriddenRestApiBase; + } + + public static String getRestApiBase() { + return restApiBase; + } + + public static void overrideStreamApiEndpoint(final String overriddenStreamApiEndpoint) { + streamApiEndpoint = overriddenStreamApiEndpoint; + } + + public static String getStreamApiEndpoint() { + return streamApiEndpoint; + } + + public static void connectToStream() throws MqttException { + if (!WiaStreamClient.getInstance().isConnected()) { + WiaStreamClient.getInstance().connect(); + } + } + + public static void disconnectFromStream() throws MqttException { + WiaStreamClient.getInstance().disconnect(); + } + + public static boolean isConnectedToStream() { + return WiaStreamClient.getInstance().isConnected(); + } + + public static void setSecretKey(String s) { + secretKey = s; + + try { + clientInfo = Whoami.retrieve(); + } catch (AuthenticationException e) { + e.printStackTrace(); + } catch (InvalidRequestException e) { + e.printStackTrace(); + } catch (APIConnectionException e) { + e.printStackTrace(); + } catch (APIException e) { + e.printStackTrace(); + } + } + + public static String getSecretKey() { + return secretKey; + } + + public static Whoami getClientInfo() { + return clientInfo; + } +} diff --git a/src/main/java/io/wia/WiaClient.java b/src/main/java/io/wia/WiaClient.java new file mode 100644 index 0000000..a9105d6 --- /dev/null +++ b/src/main/java/io/wia/WiaClient.java @@ -0,0 +1,24 @@ +package io.wia; + +public class WiaClient { + private static WiaClient instance = null; + + protected WiaClient() { + + } + + public static WiaClient getInstance() { + if(instance == null) { + instance = new WiaClient(); + } + return instance; + } + + public void overrideRestApiBase(final String overriddenRestApiBase) { + Wia.overrideRestApiBase(overriddenRestApiBase); + } + + public void overrideStreamApiEndpoint(final String overriddenStreamApiEndpoint) { + Wia.overrideStreamApiEndpoint(overriddenStreamApiEndpoint); + } +} diff --git a/src/main/java/io/wia/WiaStreamClient.java b/src/main/java/io/wia/WiaStreamClient.java new file mode 100644 index 0000000..7241016 --- /dev/null +++ b/src/main/java/io/wia/WiaStreamClient.java @@ -0,0 +1,162 @@ +package io.wia; + +import com.google.gson.Gson; +import io.wia.model.Event; +import io.wia.model.Location; +import io.wia.model.Log; +import io.wia.model.Sensor; +import io.wia.net.*; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; +import org.eclipse.paho.client.mqttv3.*; +import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.HashMap; + +public class WiaStreamClient { + private static Logger logger = LogManager.getLogger(WiaStreamClient.class); + + private static WiaStreamClient instance = null; + + private static MemoryPersistence persistence = null; + private static MqttClient mqttClient = null; + + private final int MQTT_QOS = 0; + private final boolean MQTT_MESSAGE_RETAINED = false; + + private static HashMap subscribeCallbacks = + new HashMap(); + + protected WiaStreamClient() { + persistence = new MemoryPersistence(); + try { + mqttClient = new MqttClient(Wia.getStreamApiEndpoint(), MqttClient.generateClientId(), persistence); + } catch (MqttException e) { + e.printStackTrace(); + } + } + + public static WiaStreamClient getInstance() { + if (instance == null) { + instance = new WiaStreamClient(); + } + return instance; + } + + public void connect() throws MqttException { + MqttConnectOptions connOpts = new MqttConnectOptions(); + connOpts.setCleanSession(true); + connOpts.setUserName(Wia.getSecretKey()); + connOpts.setPassword(" ".toCharArray()); + + mqttClient.setCallback(new MqttCallback() { + @Override + public void connectionLost(Throwable throwable) { + logger.debug("connectionLost: " + throwable.getCause().getMessage()); + } + + @Override + public void messageArrived(String s, MqttMessage mqttMessage) throws Exception { + logger.debug("messageArrived for topic: " + s); + // Check for specific topic + if (subscribeCallbacks.containsKey(s)) { + logger.debug("Got specific callback!"); + + WiaSubscribeCallback callback = subscribeCallbacks.get(s); + Gson gson = new Gson(); + + if (s.contains("/events/")) { + Event event = gson.fromJson(new String(mqttMessage.getPayload()), Event.class); + ((WiaEventSubscribeCallback)callback).received(event); + } else if (s.contains("/logs/")) { + Log log = gson.fromJson(new String(mqttMessage.getPayload()), Log.class); + ((WiaLogSubscribeCallback)callback).received(log); + } else if (s.contains("/sensors/")) { + Sensor sensor = gson.fromJson(new String(mqttMessage.getPayload()), Sensor.class); + ((WiaSensorSubscribeCallback)callback).received(sensor); + } else if (s.contains("/locations")) { + Location location = gson.fromJson(new String(mqttMessage.getPayload()), Location.class); + ((WiaLocationSubscribeCallback)callback).received(location); + } + } + + // Check for wildcard topic + String[] topicSplit = s.split("/"); + if (topicSplit.length > 3) { + String wildcardTopic = topicSplit[0] + "/" + topicSplit[1] + "/" + topicSplit[2] + "/+"; + if (subscribeCallbacks.containsKey(wildcardTopic)) { + logger.debug("Got wildcard callback!"); + } + } + } + + @Override + public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { + logger.debug("deliveryComplete to topic: " + iMqttDeliveryToken.getTopics()[0]); + } + }); + + mqttClient.connect(connOpts); + } + + public void disconnect() throws MqttException { + if (mqttClient.isConnected()) { + mqttClient.disconnect(); + } + } + + public boolean isConnected() { + return mqttClient.isConnected(); + } + + public void publish(String topic, String content) { + MqttMessage message = new MqttMessage(content.getBytes()); + message.setQos(MQTT_QOS); + try { + mqttClient.publish(topic, content.getBytes(), MQTT_QOS, MQTT_MESSAGE_RETAINED); + } catch (MqttException e) { + e.printStackTrace(); + } + } + + public void subscribe(String topic, WiaSubscribeCallback callback) { + if (mqttClient.isConnected()) { + logger.debug("Is connected. Subscribing to topic: " + topic); + logger.debug(callback); + try { + mqttClient.subscribe(topic, MQTT_QOS); + subscribeCallbacks.put(topic, callback); + } catch (MqttException e) { + e.printStackTrace(); + } + } else { + logger.debug("Not connected. Will not subscribe to topic: " + topic); + } + } + + public void unsubscribe(String topic) { + try { + if (mqttClient.isConnected()) + mqttClient.unsubscribe(topic); + subscribeCallbacks.remove(topic); + } catch (MqttException e) { + e.printStackTrace(); + } + } + + public void unsubscribeFromAll() { + if (subscribeCallbacks != null) { + for (String key : subscribeCallbacks.keySet()) { + try { + if (mqttClient.isConnected()) + mqttClient.unsubscribe(key); + subscribeCallbacks.remove(key); + } catch (MqttException e) { + e.printStackTrace(); + } + } + } + } +} \ No newline at end of file diff --git a/src/main/java/com/wia/exception/APIConnectionException.java b/src/main/java/io/wia/exception/APIConnectionException.java similarity index 92% rename from src/main/java/com/wia/exception/APIConnectionException.java rename to src/main/java/io/wia/exception/APIConnectionException.java index eb141c3..acc7b33 100644 --- a/src/main/java/com/wia/exception/APIConnectionException.java +++ b/src/main/java/io/wia/exception/APIConnectionException.java @@ -1,4 +1,4 @@ -package com.wia.exception; +package io.wia.exception; public class APIConnectionException extends WiaException { diff --git a/src/main/java/com/wia/exception/APIException.java b/src/main/java/io/wia/exception/APIException.java similarity index 90% rename from src/main/java/com/wia/exception/APIException.java rename to src/main/java/io/wia/exception/APIException.java index 7198f6a..134592a 100644 --- a/src/main/java/com/wia/exception/APIException.java +++ b/src/main/java/io/wia/exception/APIException.java @@ -1,4 +1,4 @@ -package com.wia.exception; +package io.wia.exception; public class APIException extends WiaException { diff --git a/src/main/java/com/wia/exception/AuthenticationException.java b/src/main/java/io/wia/exception/AuthenticationException.java similarity index 90% rename from src/main/java/com/wia/exception/AuthenticationException.java rename to src/main/java/io/wia/exception/AuthenticationException.java index 4c151d1..6b4c6e6 100644 --- a/src/main/java/com/wia/exception/AuthenticationException.java +++ b/src/main/java/io/wia/exception/AuthenticationException.java @@ -1,4 +1,4 @@ -package com.wia.exception; +package io.wia.exception; public class AuthenticationException extends WiaException { diff --git a/src/main/java/com/wia/exception/InvalidRequestException.java b/src/main/java/io/wia/exception/InvalidRequestException.java similarity index 93% rename from src/main/java/com/wia/exception/InvalidRequestException.java rename to src/main/java/io/wia/exception/InvalidRequestException.java index dc83acb..b1eb247 100644 --- a/src/main/java/com/wia/exception/InvalidRequestException.java +++ b/src/main/java/io/wia/exception/InvalidRequestException.java @@ -1,4 +1,4 @@ -package com.wia.exception; +package io.wia.exception; public class InvalidRequestException extends WiaException { diff --git a/src/main/java/com/wia/exception/RateLimitException.java b/src/main/java/io/wia/exception/RateLimitException.java similarity index 90% rename from src/main/java/com/wia/exception/RateLimitException.java rename to src/main/java/io/wia/exception/RateLimitException.java index 5a2d0ea..110e26d 100644 --- a/src/main/java/com/wia/exception/RateLimitException.java +++ b/src/main/java/io/wia/exception/RateLimitException.java @@ -1,4 +1,4 @@ -package com.wia.exception; +package io.wia.exception; public class RateLimitException extends InvalidRequestException { diff --git a/src/main/java/com/wia/exception/WiaException.java b/src/main/java/io/wia/exception/WiaException.java similarity index 97% rename from src/main/java/com/wia/exception/WiaException.java rename to src/main/java/io/wia/exception/WiaException.java index 0636b0d..a9e3c05 100644 --- a/src/main/java/com/wia/exception/WiaException.java +++ b/src/main/java/io/wia/exception/WiaException.java @@ -1,4 +1,4 @@ -package com.wia.exception; +package io.wia.exception; public abstract class WiaException extends Exception { diff --git a/src/main/java/io/wia/model/AccessToken.java b/src/main/java/io/wia/model/AccessToken.java new file mode 100644 index 0000000..9f4d660 --- /dev/null +++ b/src/main/java/io/wia/model/AccessToken.java @@ -0,0 +1,70 @@ +package io.wia.model; + +import io.wia.exception.APIConnectionException; +import io.wia.exception.APIException; +import io.wia.exception.AuthenticationException; +import io.wia.exception.InvalidRequestException; +import io.wia.net.APIResource; +import io.wia.net.RequestOptions; + +import java.util.Map; + +public class AccessToken extends APIResource { + String accessToken; + String refreshToken; + String tokenType; + Long expiresIn; + String scope; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public String getRefreshToken() { + return refreshToken; + } + + public void setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + } + + public String getTokenType() { + return tokenType; + } + + public void setTokenType(String tokenType) { + this.tokenType = tokenType; + } + + public Long getExpiresIn() { + return expiresIn; + } + + public void setExpiresIn(Long expiresIn) { + this.expiresIn = expiresIn; + } + + public String getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } + + public static AccessToken generate(Map params) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return generate(params, null); + } + + public static AccessToken generate(Map params, RequestOptions options) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return request(RequestMethod.POST, stringURL("auth/token"), params, AccessToken.class, options); + } +} \ No newline at end of file diff --git a/src/main/java/com/wia/model/Device.java b/src/main/java/io/wia/model/Device.java similarity index 58% rename from src/main/java/com/wia/model/Device.java rename to src/main/java/io/wia/model/Device.java index 1b9ee7e..b7b932f 100644 --- a/src/main/java/com/wia/model/Device.java +++ b/src/main/java/io/wia/model/Device.java @@ -1,20 +1,20 @@ -package com.wia.model; +package io.wia.model; -import com.wia.exception.APIConnectionException; -import com.wia.exception.APIException; -import com.wia.exception.AuthenticationException; -import com.wia.exception.InvalidRequestException; -import com.wia.net.APIResource; -import com.wia.net.RequestOptions; +import io.wia.WiaClient; +import io.wia.exception.APIConnectionException; +import io.wia.exception.APIException; +import io.wia.exception.AuthenticationException; +import io.wia.exception.InvalidRequestException; +import io.wia.net.APIResource; +import io.wia.net.RequestOptions; import java.util.Map; -public class Device extends APIResource implements MetadataStore, HasId { +public class Device extends APIResource implements HasId { String id; String name; Long createdAt; Long updatedAt; - Map metadata; public String getId() { return id; @@ -48,26 +48,22 @@ public void setUpdatedAt(Long updatedAt) { this.updatedAt = updatedAt; } - public Map getMetadata() { - return metadata; - } - public static Device create(Map params) throws AuthenticationException, InvalidRequestException, APIConnectionException, APIException { return create(params, (RequestOptions) null); } - public static Device retrieve(String id) + public static Device create(Map params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, APIException { - return retrieve(id, (RequestOptions) null); + return request(RequestMethod.POST, classURL(Device.class), params, Device.class, options); } - public static Device create(Map params, RequestOptions options) + public static Device retrieve(String id) throws AuthenticationException, InvalidRequestException, APIConnectionException, APIException { - return request(RequestMethod.POST, classURL(Device.class), params, Device.class, options); + return retrieve(id, (RequestOptions) null); } public static Device retrieve(String id, RequestOptions options) @@ -85,7 +81,30 @@ public Device update(Map params) public Device update(Map params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, APIException { - return request(RequestMethod.POST, instanceURL(Device.class, this.id), params, Device.class, options); + return request(RequestMethod.PUT, instanceURL(Device.class, this.id), params, Device.class, options); } + public WiaDeletedObject delete() + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return delete((RequestOptions) null); + } + + public WiaDeletedObject delete(RequestOptions options) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return request(RequestMethod.DELETE, instanceURL(Device.class, this.id), null, WiaDeletedObject.class, options); + } + + public static DeviceCollection list(Map params) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return list(params, (RequestOptions) null); + } + + public static DeviceCollection list(Map params, + RequestOptions options) throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return requestCollection(classURL(Device.class), params, DeviceCollection.class, options); + } } \ No newline at end of file diff --git a/src/main/java/io/wia/model/DeviceCollection.java b/src/main/java/io/wia/model/DeviceCollection.java new file mode 100644 index 0000000..f19ec1d --- /dev/null +++ b/src/main/java/io/wia/model/DeviceCollection.java @@ -0,0 +1,42 @@ +package io.wia.model; + +import io.wia.net.RequestOptions; + +import java.util.List; +import java.util.Map; + +public class DeviceCollection implements WiaCollectionInterface { + List devices; + Integer count; + private RequestOptions requestOptions; + private Map requestParams; + + public List getDevices() { + return devices; + } + public void setDevices(List devices) { + this.devices = devices; + } + public Integer getCount() { + return count; + } + public void setCount(Integer count) { + this.count = count; + } + + public RequestOptions getRequestOptions() { + return this.requestOptions; + } + + public Map getRequestParams() { + return this.requestParams; + } + + public void setRequestOptions(RequestOptions requestOptions) { + this.requestOptions = requestOptions; + } + + public void setRequestParams(Map requestParams) { + this.requestParams = requestParams; + } +} diff --git a/src/main/java/io/wia/model/Event.java b/src/main/java/io/wia/model/Event.java new file mode 100644 index 0000000..2423e61 --- /dev/null +++ b/src/main/java/io/wia/model/Event.java @@ -0,0 +1,115 @@ +package io.wia.model; + +import com.google.gson.Gson; +import io.wia.Wia; +import io.wia.WiaStreamClient; +import io.wia.exception.APIConnectionException; +import io.wia.exception.APIException; +import io.wia.exception.AuthenticationException; +import io.wia.exception.InvalidRequestException; +import io.wia.net.APIResource; +import io.wia.net.RequestOptions; +import io.wia.net.WiaEventSubscribeCallback; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; + +import java.util.Map; + +public class Event extends APIResource implements HasId { + private static Logger logger = LogManager.getLogger(Event.class); + + String id; + String name; + Object data; + Long timestamp; + Long receivedTimestamp; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } + + public Long getTimestamp() { + return timestamp; + } + + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } + + public Long getReceivedTimestamp() { + return receivedTimestamp; + } + + public void setReceivedTimestamp(Long receivedTimestamp) { + this.receivedTimestamp = receivedTimestamp; + } + + public static Event publish(Map params) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return publish(params, (RequestOptions) null); + } + + public static Event publish(Map params, RequestOptions options) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + if (WiaStreamClient.getInstance().isConnected()) { + Gson gson = new Gson(); + String payload = gson.toJson(params); + String topic = "devices/" + Wia.getClientInfo().getDevice().getId() + "/events/" + params.get("name"); + WiaStreamClient.getInstance().publish(topic, payload); + return new Event(); + } else { + return request(APIResource.RequestMethod.POST, classURL(Event.class), params, Event.class, options); + } + } + + public static EventCollection list(Map params) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return list(params, (RequestOptions) null); + } + + public static EventCollection list(Map params, + RequestOptions options) throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return requestCollection(classURL(Event.class), params, EventCollection.class, options); + } + + public static void subscribe(String device, WiaEventSubscribeCallback callback) { + subscribe(device, "+", callback); + } + + public static void subscribe(String device, String eventName, WiaEventSubscribeCallback callback) { + logger.debug(callback); + WiaStreamClient.getInstance().subscribe("devices/" + device + "/events/" + eventName, callback); + } + + public static void unsubscribe(String device) { + unsubscribe(device, "+"); + } + + public static void unsubscribe(String device, String eventName) { + WiaStreamClient.getInstance().unsubscribe("devices/" + device + "/events/" + eventName); + } +} diff --git a/src/main/java/io/wia/model/EventCollection.java b/src/main/java/io/wia/model/EventCollection.java new file mode 100644 index 0000000..acbf347 --- /dev/null +++ b/src/main/java/io/wia/model/EventCollection.java @@ -0,0 +1,42 @@ +package io.wia.model; + +import io.wia.net.RequestOptions; + +import java.util.List; +import java.util.Map; + +public class EventCollection implements WiaCollectionInterface { + List events; + Integer count; + private RequestOptions requestOptions; + private Map requestParams; + + public List getEvents() { + return events; + } + public void setEvents(List events) { + this.events = events; + } + public Integer getCount() { + return count; + } + public void setCount(Integer count) { + this.count = count; + } + + public RequestOptions getRequestOptions() { + return this.requestOptions; + } + + public Map getRequestParams() { + return this.requestParams; + } + + public void setRequestOptions(RequestOptions requestOptions) { + this.requestOptions = requestOptions; + } + + public void setRequestParams(Map requestParams) { + this.requestParams = requestParams; + } +} diff --git a/src/main/java/com/wia/model/HasId.java b/src/main/java/io/wia/model/HasId.java similarity index 70% rename from src/main/java/com/wia/model/HasId.java rename to src/main/java/io/wia/model/HasId.java index 0edc39d..59a4765 100644 --- a/src/main/java/com/wia/model/HasId.java +++ b/src/main/java/io/wia/model/HasId.java @@ -1,4 +1,4 @@ -package com.wia.model; +package io.wia.model; public interface HasId { public String getId(); diff --git a/src/main/java/io/wia/model/Location.java b/src/main/java/io/wia/model/Location.java new file mode 100644 index 0000000..a933700 --- /dev/null +++ b/src/main/java/io/wia/model/Location.java @@ -0,0 +1,112 @@ +package io.wia.model; + +import com.google.gson.Gson; +import io.wia.Wia; +import io.wia.WiaStreamClient; +import io.wia.exception.APIConnectionException; +import io.wia.exception.APIException; +import io.wia.exception.AuthenticationException; +import io.wia.exception.InvalidRequestException; +import io.wia.net.APIResource; +import io.wia.net.RequestOptions; +import io.wia.net.WiaLocationSubscribeCallback; +import io.wia.net.WiaLogSubscribeCallback; + +import java.util.Map; + +public class Location extends APIResource implements HasId { + String id; + double latitude; + double longitude; + double altitude; + Long timestamp; + Long receivedTimestamp; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public double getLatitude() { + return latitude; + } + + public void setLatitude(double latitude) { + this.latitude = latitude; + } + + public double getLongitude() { + return longitude; + } + + public void setLongitude(double longitude) { + this.longitude = longitude; + } + + public double getAltitude() { + return altitude; + } + + public void setAltitude(double altitude) { + this.altitude = altitude; + } + + public Long getTimestamp() { + return timestamp; + } + + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } + + public Long getReceivedTimestamp() { + return receivedTimestamp; + } + + public void setReceivedTimestamp(Long receivedTimestamp) { + this.receivedTimestamp = receivedTimestamp; + } + + public static Location publish(Map params) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return publish(params, (RequestOptions) null); + } + + public static Location publish(Map params, RequestOptions options) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + if (WiaStreamClient.getInstance().isConnected()) { + Gson gson = new Gson(); + String payload = gson.toJson(params); + String topic = "devices/" + Wia.getClientInfo().getDevice().getId() + "/locations"; + WiaStreamClient.getInstance().publish(topic, payload); + return new Location(); + } else { + return request(APIResource.RequestMethod.POST, classURL(Location.class), params, Location.class, options); + } + } + + public static LocationCollection list(Map params) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return list(params, (RequestOptions) null); + } + + public static LocationCollection list(Map params, + RequestOptions options) throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return requestCollection(classURL(Location.class), params, LocationCollection.class, options); + } + + public static void subscribe(String device, WiaLocationSubscribeCallback callback) { + WiaStreamClient.getInstance().subscribe("devices/" + device + "/locations", callback); + } + + public static void unsubscribe(String device) { + WiaStreamClient.getInstance().unsubscribe("devices/" + device + "/locations"); + } +} diff --git a/src/main/java/io/wia/model/LocationCollection.java b/src/main/java/io/wia/model/LocationCollection.java new file mode 100644 index 0000000..1e693fa --- /dev/null +++ b/src/main/java/io/wia/model/LocationCollection.java @@ -0,0 +1,42 @@ +package io.wia.model; + +import io.wia.net.RequestOptions; + +import java.util.List; +import java.util.Map; + +public class LocationCollection implements WiaCollectionInterface { + List locations; + Integer count; + private RequestOptions requestOptions; + private Map requestParams; + + public List getLocations() { + return locations; + } + public void setLocations(List locations) { + this.locations = locations; + } + public Integer getCount() { + return count; + } + public void setCount(Integer count) { + this.count = count; + } + + public RequestOptions getRequestOptions() { + return this.requestOptions; + } + + public Map getRequestParams() { + return this.requestParams; + } + + public void setRequestOptions(RequestOptions requestOptions) { + this.requestOptions = requestOptions; + } + + public void setRequestParams(Map requestParams) { + this.requestParams = requestParams; + } +} diff --git a/src/main/java/io/wia/model/Log.java b/src/main/java/io/wia/model/Log.java new file mode 100644 index 0000000..5de875c --- /dev/null +++ b/src/main/java/io/wia/model/Log.java @@ -0,0 +1,121 @@ +package io.wia.model; + +import com.google.gson.Gson; +import io.wia.Wia; +import io.wia.WiaClient; +import io.wia.WiaStreamClient; +import io.wia.exception.APIConnectionException; +import io.wia.exception.APIException; +import io.wia.exception.AuthenticationException; +import io.wia.exception.InvalidRequestException; +import io.wia.net.APIResource; +import io.wia.net.RequestOptions; +import io.wia.net.WiaEventSubscribeCallback; +import io.wia.net.WiaLogSubscribeCallback; + +import java.util.Map; + +public class Log extends APIResource implements HasId { + String id; + String level; + String message; + Object data; + Long timestamp; + Long receivedTimestamp; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } + + public Long getTimestamp() { + return timestamp; + } + + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } + + public Long getReceivedTimestamp() { + return receivedTimestamp; + } + + public void setReceivedTimestamp(Long receivedTimestamp) { + this.receivedTimestamp = receivedTimestamp; + } + + public static Log publish(Map params) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return publish(params, (RequestOptions) null); + } + + public static Log publish(Map params, RequestOptions options) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + if (WiaStreamClient.getInstance().isConnected()) { + Gson gson = new Gson(); + String payload = gson.toJson(params); + String topic = "devices/" + Wia.getClientInfo().getDevice().getId() + "/logs/" + params.get("level"); + WiaStreamClient.getInstance().publish(topic, payload); + return new Log(); + } else { + return request(APIResource.RequestMethod.POST, classURL(Log.class), params, Log.class, options); + } + } + + public static LogCollection list(Map params) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return list(params, (RequestOptions) null); + } + + public static LogCollection list(Map params, + RequestOptions options) throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return requestCollection(classURL(Log.class), params, LogCollection.class, options); + } + + public static void subscribe(String device, WiaLogSubscribeCallback callback) { + subscribe(device, "+", callback); + } + + public static void subscribe(String device, String logLevel, WiaLogSubscribeCallback callback) { + WiaStreamClient.getInstance().subscribe("devices/" + device + "/logs/" + logLevel, callback); + } + + public static void unsubscribe(String device) { + unsubscribe(device, "+"); + } + + public static void unsubscribe(String device, String logLevel) { + WiaStreamClient.getInstance().unsubscribe("devices/" + device + "/logs/" + logLevel); + } +} diff --git a/src/main/java/io/wia/model/LogCollection.java b/src/main/java/io/wia/model/LogCollection.java new file mode 100644 index 0000000..0f49a41 --- /dev/null +++ b/src/main/java/io/wia/model/LogCollection.java @@ -0,0 +1,42 @@ +package io.wia.model; + +import io.wia.net.RequestOptions; + +import java.util.List; +import java.util.Map; + +public class LogCollection implements WiaCollectionInterface { + List logs; + Integer count; + private RequestOptions requestOptions; + private Map requestParams; + + public List getLogs() { + return logs; + } + public void setLogs(List logs) { + this.logs = logs; + } + public Integer getCount() { + return count; + } + public void setCount(Integer count) { + this.count = count; + } + + public RequestOptions getRequestOptions() { + return this.requestOptions; + } + + public Map getRequestParams() { + return this.requestParams; + } + + public void setRequestOptions(RequestOptions requestOptions) { + this.requestOptions = requestOptions; + } + + public void setRequestParams(Map requestParams) { + this.requestParams = requestParams; + } +} diff --git a/src/main/java/com/wia/model/MetadataStore.java b/src/main/java/io/wia/model/MetadataStore.java similarity index 68% rename from src/main/java/com/wia/model/MetadataStore.java rename to src/main/java/io/wia/model/MetadataStore.java index 5dc216d..08f4cbf 100644 --- a/src/main/java/com/wia/model/MetadataStore.java +++ b/src/main/java/io/wia/model/MetadataStore.java @@ -1,10 +1,10 @@ -package com.wia.model; +package io.wia.model; -import com.wia.exception.APIConnectionException; -import com.wia.exception.APIException; -import com.wia.exception.AuthenticationException; -import com.wia.exception.InvalidRequestException; -import com.wia.net.RequestOptions; +import io.wia.exception.APIConnectionException; +import io.wia.exception.APIException; +import io.wia.exception.AuthenticationException; +import io.wia.exception.InvalidRequestException; +import io.wia.net.RequestOptions; import java.util.Map; diff --git a/src/main/java/io/wia/model/Sensor.java b/src/main/java/io/wia/model/Sensor.java new file mode 100644 index 0000000..ebed683 --- /dev/null +++ b/src/main/java/io/wia/model/Sensor.java @@ -0,0 +1,111 @@ +package io.wia.model; + +import com.google.gson.Gson; +import io.wia.Wia; +import io.wia.WiaStreamClient; +import io.wia.exception.APIConnectionException; +import io.wia.exception.APIException; +import io.wia.exception.AuthenticationException; +import io.wia.exception.InvalidRequestException; +import io.wia.net.APIResource; +import io.wia.net.RequestOptions; +import io.wia.net.WiaEventSubscribeCallback; +import io.wia.net.WiaSensorSubscribeCallback; + +import java.util.Map; + +public class Sensor extends APIResource implements HasId { + String id; + String name; + Object data; + Long timestamp; + Long receivedTimestamp; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } + + public Long getTimestamp() { + return timestamp; + } + + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } + + public Long getReceivedTimestamp() { + return receivedTimestamp; + } + + public void setReceivedTimestamp(Long receivedTimestamp) { + this.receivedTimestamp = receivedTimestamp; + } + + public static Sensor publish(Map params) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return publish(params, (RequestOptions) null); + } + + public static Sensor publish(Map params, RequestOptions options) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + if (WiaStreamClient.getInstance().isConnected()) { + Gson gson = new Gson(); + String payload = gson.toJson(params); + String topic = "devices/" + Wia.getClientInfo().getDevice().getId() + "/sensors/" + params.get("name"); + WiaStreamClient.getInstance().publish(topic, payload); + return new Sensor(); + } else { + return request(APIResource.RequestMethod.POST, classURL(Sensor.class), params, Sensor.class, options); + } + } + + public static SensorCollection list(Map params) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return list(params, (RequestOptions) null); + } + + public static SensorCollection list(Map params, + RequestOptions options) throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return requestCollection(classURL(Sensor.class), params, SensorCollection.class, options); + } + + public static void subscribe(String device, WiaSensorSubscribeCallback callback) { + subscribe(device, "+", callback); + } + + public static void subscribe(String device, String sensorName, WiaSensorSubscribeCallback callback) { + WiaStreamClient.getInstance().subscribe("devices/" + device + "/sensors/" + sensorName, callback); + } + + public static void unsubscribe(String device) { + unsubscribe(device, "+"); + } + + public static void unsubscribe(String device, String sensorName) { + WiaStreamClient.getInstance().unsubscribe("devices/" + device + "/sensors/" + sensorName); + } +} diff --git a/src/main/java/io/wia/model/SensorCollection.java b/src/main/java/io/wia/model/SensorCollection.java new file mode 100644 index 0000000..af6e7f0 --- /dev/null +++ b/src/main/java/io/wia/model/SensorCollection.java @@ -0,0 +1,42 @@ +package io.wia.model; + +import io.wia.net.RequestOptions; + +import java.util.List; +import java.util.Map; + +public class SensorCollection implements WiaCollectionInterface { + List sensors; + Integer count; + private RequestOptions requestOptions; + private Map requestParams; + + public List getSensors() { + return sensors; + } + public void setSensors(List sensors) { + this.sensors = sensors; + } + public Integer getCount() { + return count; + } + public void setCount(Integer count) { + this.count = count; + } + + public RequestOptions getRequestOptions() { + return this.requestOptions; + } + + public Map getRequestParams() { + return this.requestParams; + } + + public void setRequestOptions(RequestOptions requestOptions) { + this.requestOptions = requestOptions; + } + + public void setRequestParams(Map requestParams) { + this.requestParams = requestParams; + } +} diff --git a/src/main/java/io/wia/model/User.java b/src/main/java/io/wia/model/User.java new file mode 100644 index 0000000..f54cc17 --- /dev/null +++ b/src/main/java/io/wia/model/User.java @@ -0,0 +1,122 @@ +package io.wia.model; + +import io.wia.exception.APIConnectionException; +import io.wia.exception.APIException; +import io.wia.exception.AuthenticationException; +import io.wia.exception.InvalidRequestException; +import io.wia.net.APIResource; +import io.wia.net.RequestOptions; + +import java.util.Map; + +public class User extends APIResource implements HasId { + String id; + String firstName; + String lastName; + String fullName; + String username; + String email; + Long createdAt; + Long updatedAt; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getUsername() { + return username; + } + + public void setUsername(String email) { + this.username = username; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Long getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Long createdAt) { + this.createdAt = createdAt; + } + + public Long getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Long updatedAt) { + this.updatedAt = updatedAt; + } + + public static User create(Map params) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return create(params, (RequestOptions) null); + } + + public static User retrieve(String id) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return retrieve(id, (RequestOptions) null); + } + + public static User create(Map params, RequestOptions options) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return request(RequestMethod.POST, classURL(User.class), params, User.class, options); + } + + public static User retrieve(String id, RequestOptions options) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return request(RequestMethod.GET, instanceURL(User.class, id), null, User.class, options); + } + + public User update(Map params) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return update(params, (RequestOptions) null); + } + + public User update(Map params, RequestOptions options) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return request(RequestMethod.POST, instanceURL(User.class, this.id), params, User.class, options); + } + +} \ No newline at end of file diff --git a/src/main/java/io/wia/model/Whoami.java b/src/main/java/io/wia/model/Whoami.java new file mode 100644 index 0000000..284aa7d --- /dev/null +++ b/src/main/java/io/wia/model/Whoami.java @@ -0,0 +1,50 @@ +package io.wia.model; + +import io.wia.exception.APIConnectionException; +import io.wia.exception.APIException; +import io.wia.exception.AuthenticationException; +import io.wia.exception.InvalidRequestException; +import io.wia.net.APIResource; +import io.wia.net.RequestOptions; + +public class Whoami extends APIResource { + String scope; + User user; + Device device; + + public String getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Device getDevice() { + return device; + } + + public void setDevice(Device device) { + this.device = device; + } + + public static Whoami retrieve() + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return retrieve((RequestOptions) null); + } + + public static Whoami retrieve(RequestOptions options) + throws AuthenticationException, InvalidRequestException, + APIConnectionException, APIException { + return request(RequestMethod.GET, stringURL("whoami"), null, Whoami.class, options); + } +} diff --git a/src/main/java/io/wia/model/WiaCollection.java b/src/main/java/io/wia/model/WiaCollection.java new file mode 100644 index 0000000..6c3e9b7 --- /dev/null +++ b/src/main/java/io/wia/model/WiaCollection.java @@ -0,0 +1,44 @@ +package io.wia.model; + +import io.wia.net.RequestOptions; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public abstract class WiaCollection implements WiaCollectionInterface { + List data; + Integer count; + Boolean hasMore; + private RequestOptions requestOptions; + private Map requestParams; + + public List getData() { + return data; + } + public void setData(List data) { + this.data = data; + } + public Integer getCount() { + return count; + } + public void setCount(Integer count) { + this.count = count; + } + + public RequestOptions getRequestOptions() { + return this.requestOptions; + } + + public Map getRequestParams() { + return this.requestParams; + } + + public void setRequestOptions(RequestOptions requestOptions) { + this.requestOptions = requestOptions; + } + + public void setRequestParams(Map requestParams) { + this.requestParams = requestParams; + } +} diff --git a/src/main/java/com/wia/model/WiaCollectionInterface.java b/src/main/java/io/wia/model/WiaCollectionInterface.java similarity index 82% rename from src/main/java/com/wia/model/WiaCollectionInterface.java rename to src/main/java/io/wia/model/WiaCollectionInterface.java index 217ea1b..f51c720 100644 --- a/src/main/java/com/wia/model/WiaCollectionInterface.java +++ b/src/main/java/io/wia/model/WiaCollectionInterface.java @@ -1,15 +1,12 @@ -package com.wia.model; +package io.wia.model; -import com.wia.net.RequestOptions; +import io.wia.net.RequestOptions; import java.util.List; import java.util.Map; public interface WiaCollectionInterface { - public List getData(); - public Boolean getHasMore(); - public Integer getTotalCount(); - public String getURL(); + public Integer getCount(); /** * Get request options that were used to fetch the collection. This is diff --git a/src/main/java/io/wia/model/WiaDeletedObject.java b/src/main/java/io/wia/model/WiaDeletedObject.java new file mode 100644 index 0000000..ec3628c --- /dev/null +++ b/src/main/java/io/wia/model/WiaDeletedObject.java @@ -0,0 +1,20 @@ +package io.wia.model; + +import com.sun.org.apache.xpath.internal.operations.Bool; + +public class WiaDeletedObject { + String id; + Boolean deleted; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Boolean getDeleted() { return deleted; } + + public void setDeleted(Boolean deleted) { this.deleted = deleted; } +} diff --git a/src/main/java/com/wia/model/WiaObject.java b/src/main/java/io/wia/model/WiaObject.java similarity index 98% rename from src/main/java/com/wia/model/WiaObject.java rename to src/main/java/io/wia/model/WiaObject.java index 8c2b524..41029b7 100644 --- a/src/main/java/com/wia/model/WiaObject.java +++ b/src/main/java/io/wia/model/WiaObject.java @@ -1,4 +1,4 @@ -package com.wia.model; +package io.wia.model; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; diff --git a/src/main/java/com/wia/model/WiaRawJsonObject.java b/src/main/java/io/wia/model/WiaRawJsonObject.java similarity index 89% rename from src/main/java/com/wia/model/WiaRawJsonObject.java rename to src/main/java/io/wia/model/WiaRawJsonObject.java index f5b6039..2d62452 100644 --- a/src/main/java/com/wia/model/WiaRawJsonObject.java +++ b/src/main/java/io/wia/model/WiaRawJsonObject.java @@ -1,4 +1,4 @@ -package com.wia.model; +package io.wia.model; import com.google.gson.JsonObject; diff --git a/src/main/java/com/wia/model/WiaRawJsonObjectDeserializer.java b/src/main/java/io/wia/model/WiaRawJsonObjectDeserializer.java similarity index 96% rename from src/main/java/com/wia/model/WiaRawJsonObjectDeserializer.java rename to src/main/java/io/wia/model/WiaRawJsonObjectDeserializer.java index fc237c7..5b97043 100644 --- a/src/main/java/com/wia/model/WiaRawJsonObjectDeserializer.java +++ b/src/main/java/io/wia/model/WiaRawJsonObjectDeserializer.java @@ -1,4 +1,4 @@ -package com.wia.model; +package io.wia.model; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; diff --git a/src/main/java/com/wia/net/APIResource.java b/src/main/java/io/wia/net/APIResource.java similarity index 85% rename from src/main/java/com/wia/net/APIResource.java rename to src/main/java/io/wia/net/APIResource.java index dc926a0..9d8dc7a 100644 --- a/src/main/java/com/wia/net/APIResource.java +++ b/src/main/java/io/wia/net/APIResource.java @@ -1,17 +1,16 @@ -package com.wia.net; +package io.wia.net; -import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.wia.Wia; -import com.wia.exception.APIConnectionException; -import com.wia.exception.APIException; -import com.wia.exception.AuthenticationException; -import com.wia.exception.InvalidRequestException; -import com.wia.model.WiaCollectionInterface; -import com.wia.model.WiaObject; -import com.wia.model.WiaRawJsonObject; -import com.wia.model.WiaRawJsonObjectDeserializer; +import io.wia.Wia; +import io.wia.exception.APIConnectionException; +import io.wia.exception.APIException; +import io.wia.exception.AuthenticationException; +import io.wia.exception.InvalidRequestException; +import io.wia.model.WiaCollectionInterface; +import io.wia.model.WiaObject; +import io.wia.model.WiaRawJsonObject; +import io.wia.model.WiaRawJsonObjectDeserializer; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; @@ -25,7 +24,7 @@ public static void setWiaResponseGetter(WiaResponseGetter srg) { } public static final Gson GSON = new GsonBuilder() - .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) +// .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .registerTypeAdapter(WiaRawJsonObject.class, new WiaRawJsonObjectDeserializer()) .create(); @@ -51,6 +50,10 @@ protected static String classURL(Class clazz, String apiBase) { return String.format("%ss", singleClassURL(clazz, apiBase)); } + protected static String stringURL(String appendStr) { + return String.format("%s/v1/%s", Wia.getRestApiBase(), appendStr); + } + protected static String instanceURL(Class clazz, String id) throws InvalidRequestException { return instanceURL(clazz, id, Wia.getRestApiBase()); @@ -63,7 +66,7 @@ protected static String instanceURL(Class clazz, String id, String apiBase) } catch (UnsupportedEncodingException e) { throw new InvalidRequestException("Unable to encode parameters to " + CHARSET - + ". Please contact support@stripe.com for assistance.", + + ". Please contact support@wia.io for assistance.", null, null, 0, e); } } @@ -71,7 +74,7 @@ protected static String instanceURL(Class clazz, String id, String apiBase) public static final String CHARSET = "UTF-8"; public enum RequestMethod { - GET, POST, DELETE + GET, POST, DELETE, PUT } public enum RequestType { diff --git a/src/main/java/com/wia/net/LiveWiaResponseGetter.java b/src/main/java/io/wia/net/LiveWiaResponseGetter.java similarity index 91% rename from src/main/java/com/wia/net/LiveWiaResponseGetter.java rename to src/main/java/io/wia/net/LiveWiaResponseGetter.java index 96d691b..90155e9 100644 --- a/src/main/java/com/wia/net/LiveWiaResponseGetter.java +++ b/src/main/java/io/wia/net/LiveWiaResponseGetter.java @@ -1,12 +1,13 @@ -package com.wia.net; +package io.wia.net; -import com.wia.Wia; -import com.wia.exception.APIConnectionException; -import com.wia.exception.APIException; -import com.wia.exception.AuthenticationException; -import com.wia.exception.RateLimitException; -import com.wia.exception.InvalidRequestException; -import com.wia.model.WiaCollectionInterface; +import com.google.gson.Gson; +import io.wia.Wia; +import io.wia.exception.APIConnectionException; +import io.wia.exception.APIException; +import io.wia.exception.AuthenticationException; +import io.wia.exception.RateLimitException; +import io.wia.exception.InvalidRequestException; +import io.wia.model.AccessToken; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSocketFactory; @@ -26,12 +27,13 @@ import java.net.URLStreamHandler; import java.util.HashMap; import java.util.Iterator; -import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Scanner; +import static io.wia.net.APIResource.RequestMethod.GET; + public class LiveWiaResponseGetter implements WiaResponseGetter { private static final String DNS_CACHE_TTL_PROPERTY_NAME = "networkaddress.cache.ttl"; @@ -55,7 +57,7 @@ public Parameter(String key, String value) { private static final SSLSocketFactory socketFactory = new WiaSSLSocketFactory(); public T request( - com.wia.net.APIResource.RequestMethod method, + APIResource.RequestMethod method, String url, Map params, Class clazz, @@ -77,7 +79,7 @@ static Map getHeaders(RequestOptions options) { headers.put("User-Agent", String.format("Wia/v1 JavaBindings/%s", Wia.VERSION)); - headers.put("Authorization", String.format("Bearer %s", options.getApiKey())); + headers.put("Authorization", String.format("Bearer %s", options.getSecretKey())); // debug headers String[] propertyNames = { "os.name", "os.version", "os.arch", @@ -130,17 +132,17 @@ private static java.net.HttpURLConnection createWiaConnection( wiaURL = new URL(url); } HttpURLConnection conn; - if (Wia.getConnectionProxy() != null) { - conn = (HttpURLConnection) wiaURL.openConnection(Wia.getConnectionProxy()); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return Wia.getProxyCredential(); - } - }); - } else { +// if (Wia.getConnectionProxy() != null) { +// conn = (HttpURLConnection) wiaURL.openConnection(Wia.getConnectionProxy()); +// Authenticator.setDefault(new Authenticator() { +// @Override +// protected PasswordAuthentication getPasswordAuthentication() { +// return Wia.getProxyCredential(); +// } +// }); +// } else { conn = (HttpURLConnection) wiaURL.openConnection(); - } +// } conn.setConnectTimeout(30 * 1000); conn.setReadTimeout(80 * 1000); conn.setUseCaches(false); @@ -180,7 +182,28 @@ private static java.net.HttpURLConnection createPostConnection( conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", String.format( - "application/x-www-form-urlencoded;charset=%s", APIResource.CHARSET)); + "application/json;charset=%s", APIResource.CHARSET)); + + OutputStream output = null; + try { + output = conn.getOutputStream(); + output.write(query.getBytes(APIResource.CHARSET)); + } finally { + if (output != null) { + output.close(); + } + } + return conn; + } + + private static java.net.HttpURLConnection createPutConnection( + String url, String query, RequestOptions options) throws IOException { + java.net.HttpURLConnection conn = createWiaConnection(url, options); + + conn.setDoOutput(true); + conn.setRequestMethod("PUT"); + conn.setRequestProperty("Content-Type", String.format( + "application/json;charset=%s", APIResource.CHARSET)); OutputStream output = null; try { @@ -320,7 +343,6 @@ private static String getResponseBody(InputStream responseStream) String rBody = new Scanner(responseStream, APIResource.CHARSET) .useDelimiter("\\A") .next(); // - responseStream.close(); return rBody; } @@ -337,6 +359,9 @@ private static WiaResponse makeURLConnectionRequest( case POST: conn = createPostConnection(url, query, options); break; + case PUT: + conn = createPutConnection(url, query, options); + break; case DELETE: conn = createDeleteConnection(url, query, options); break; @@ -397,10 +422,10 @@ private static T _request(APIResource.RequestMethod method, allowedToSetTTL = false; } - String apiKey = options.getApiKey(); - if (apiKey == null || apiKey.trim().isEmpty()) { + String apiKey = options.getSecretKey(); + if ((apiKey == null || apiKey.trim().isEmpty()) && !type.equals(AccessToken.class)) { throw new AuthenticationException( - "No API key provided. (HINT: set your API key using 'Wika.apiKey = '. " + "No Secret key provided. (HINT: set your Secret key using 'Wia.secretKey = '. " + "You can generate API keys from the Wia web interface. " + "See https://docs.wia.io for details or email support@wia.io if you have questions.", null, 0); @@ -460,13 +485,19 @@ private static WiaResponse getWiaResponse( throws InvalidRequestException, APIConnectionException, APIException { String query; - try { - query = createQuery(params); - } catch (UnsupportedEncodingException e) { - throw new InvalidRequestException("Unable to encode parameters to " - + APIResource.CHARSET - + ". Please contact support@wia.io for assistance.", - null, null, 0, e); + + if (method == GET) { + try { + query = createQuery(params); + } catch (UnsupportedEncodingException e) { + throw new InvalidRequestException("Unable to encode parameters to " + + APIResource.CHARSET + + ". Please contact support@wia.io for assistance.", + null, null, 0, e); + } + } else { + Gson gson = new Gson(); + query = gson.toJson(params); } try { @@ -578,6 +609,7 @@ private static void handleAPIError(String rBody, int rCode, String requestId) throws InvalidRequestException, AuthenticationException, APIException { LiveWiaResponseGetter.Error error = APIResource.GSON.fromJson(rBody, LiveWiaResponseGetter.ErrorContainer.class).error; + System.out.println("---------------rCode " + rCode); switch (rCode) { case 400: throw new InvalidRequestException(error.message, error.param, requestId, rCode, null); @@ -601,7 +633,7 @@ private static WiaResponse makeAppEngineRequest(APIResource.RequestMethod method String unknownErrorMessage = "Sorry, an unknown error occurred while trying to use the " + "Google App Engine runtime. Please contact support@wia.io for assistance."; try { - if (method == APIResource.RequestMethod.GET || method == APIResource.RequestMethod.DELETE) { + if (method == GET || method == APIResource.RequestMethod.DELETE) { url = String.format("%s?%s", url, query); } URL fetchURL = new URL(url); diff --git a/src/main/java/com/wia/net/MultipartProcessor.java b/src/main/java/io/wia/net/MultipartProcessor.java similarity index 99% rename from src/main/java/com/wia/net/MultipartProcessor.java rename to src/main/java/io/wia/net/MultipartProcessor.java index 612f278..c7da0df 100644 --- a/src/main/java/com/wia/net/MultipartProcessor.java +++ b/src/main/java/io/wia/net/MultipartProcessor.java @@ -1,4 +1,4 @@ -package com.wia.net; +package io.wia.net; import java.io.File; import java.io.FileInputStream; diff --git a/src/main/java/com/wia/net/RequestOptions.java b/src/main/java/io/wia/net/RequestOptions.java similarity index 66% rename from src/main/java/com/wia/net/RequestOptions.java rename to src/main/java/io/wia/net/RequestOptions.java index 7982613..4bcd277 100644 --- a/src/main/java/com/wia/net/RequestOptions.java +++ b/src/main/java/io/wia/net/RequestOptions.java @@ -1,23 +1,23 @@ -package com.wia.net; +package io.wia.net; -import com.wia.Wia; +import io.wia.Wia; public class RequestOptions { public static RequestOptions getDefault() { - return new RequestOptions(Wia.apiKey, Wia.apiVersion); + return new RequestOptions(Wia.getSecretKey(), Wia.apiVersion); } - private final String apiKey; + private final String secretKey; private final String wiaVersion; - private RequestOptions(String apiKey, String wiaVersion) { - this.apiKey = apiKey; + private RequestOptions(String secretKey, String wiaVersion) { + this.secretKey = secretKey; this.wiaVersion = wiaVersion; } - public String getApiKey() { - return apiKey; + public String getSecretKey() { + return secretKey; } public String getWiaVersion() { @@ -31,7 +31,7 @@ public boolean equals(Object o) { RequestOptions that = (RequestOptions) o; - if (apiKey != null ? !apiKey.equals(that.apiKey) : that.apiKey != null) { + if (secretKey != null ? !secretKey.equals(that.secretKey) : that.secretKey != null) { return false; } if (wiaVersion != null ? !wiaVersion.equals(that.wiaVersion) : that.wiaVersion != null) { @@ -43,7 +43,7 @@ public boolean equals(Object o) { @Override public int hashCode() { - int result = apiKey != null ? apiKey.hashCode() : 0; + int result = secretKey != null ? secretKey.hashCode() : 0; result = 31 * result + (wiaVersion != null ? wiaVersion.hashCode() : 0); return result; } @@ -53,29 +53,29 @@ public static RequestOptionsBuilder builder() { } public RequestOptionsBuilder toBuilder() { - return new RequestOptionsBuilder().setApiKey(this.apiKey).setWiaVersion(this.wiaVersion); + return new RequestOptionsBuilder().setSecretKey(this.secretKey).setWiaVersion(this.wiaVersion); } public static final class RequestOptionsBuilder { - private String apiKey; + private String secretKey; private String wiaVersion; public RequestOptionsBuilder() { - this.apiKey = Wia.apiKey; + this.secretKey = Wia.getSecretKey(); this.wiaVersion = Wia.apiVersion; } - public String getApiKey() { - return apiKey; + public String getSecretKey() { + return secretKey; } - public RequestOptionsBuilder setApiKey(String apiKey) { - this.apiKey = normalizeApiKey(apiKey); + public RequestOptionsBuilder setSecretKey(String secretKey) { + this.secretKey = normalizeSecretKey(secretKey); return this; } - public RequestOptionsBuilder clearApiKey() { - this.apiKey = null; + public RequestOptionsBuilder clearSecretKey() { + this.secretKey = null; return this; } @@ -91,19 +91,19 @@ public RequestOptionsBuilder clearWiaVersion() { public RequestOptions build() { return new RequestOptions( - normalizeApiKey(this.apiKey), + normalizeSecretKey(this.secretKey), normalizeWiaVersion(this.wiaVersion)); } } - private static String normalizeApiKey(String apiKey) { + private static String normalizeSecretKey(String secretKey) { // null apiKeys are considered "valid" - if (apiKey == null) { + if (secretKey == null) { return null; } - String normalized = apiKey.trim(); + String normalized = secretKey.trim(); if (normalized.isEmpty()) { - throw new InvalidRequestOptionsException("Empty API key specified!"); + throw new InvalidRequestOptionsException("Empty Secret Key specified!"); } return normalized; } diff --git a/src/main/java/io/wia/net/WiaEventSubscribeCallback.java b/src/main/java/io/wia/net/WiaEventSubscribeCallback.java new file mode 100644 index 0000000..a995687 --- /dev/null +++ b/src/main/java/io/wia/net/WiaEventSubscribeCallback.java @@ -0,0 +1,7 @@ +package io.wia.net; + +import io.wia.model.Event; + +public interface WiaEventSubscribeCallback extends WiaSubscribeCallback { + public void received(Event event); +} diff --git a/src/main/java/io/wia/net/WiaLocationSubscribeCallback.java b/src/main/java/io/wia/net/WiaLocationSubscribeCallback.java new file mode 100644 index 0000000..4180501 --- /dev/null +++ b/src/main/java/io/wia/net/WiaLocationSubscribeCallback.java @@ -0,0 +1,8 @@ +package io.wia.net; + +import io.wia.model.Location; +import io.wia.model.Log; + +public interface WiaLocationSubscribeCallback extends WiaSubscribeCallback { + public void received(Location location); +} diff --git a/src/main/java/io/wia/net/WiaLogSubscribeCallback.java b/src/main/java/io/wia/net/WiaLogSubscribeCallback.java new file mode 100644 index 0000000..1b7682c --- /dev/null +++ b/src/main/java/io/wia/net/WiaLogSubscribeCallback.java @@ -0,0 +1,7 @@ +package io.wia.net; + +import io.wia.model.Log; + +public interface WiaLogSubscribeCallback extends WiaSubscribeCallback { + public void received(Log log); +} diff --git a/src/main/java/com/wia/net/WiaResponse.java b/src/main/java/io/wia/net/WiaResponse.java similarity index 98% rename from src/main/java/com/wia/net/WiaResponse.java rename to src/main/java/io/wia/net/WiaResponse.java index 4aa75b0..08c3863 100644 --- a/src/main/java/com/wia/net/WiaResponse.java +++ b/src/main/java/io/wia/net/WiaResponse.java @@ -1,4 +1,4 @@ -package com.wia.net; +package io.wia.net; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/wia/net/WiaResponseGetter.java b/src/main/java/io/wia/net/WiaResponseGetter.java similarity index 62% rename from src/main/java/com/wia/net/WiaResponseGetter.java rename to src/main/java/io/wia/net/WiaResponseGetter.java index e898d9d..8b0be35 100644 --- a/src/main/java/com/wia/net/WiaResponseGetter.java +++ b/src/main/java/io/wia/net/WiaResponseGetter.java @@ -1,11 +1,10 @@ -package com.wia.net; +package io.wia.net; -import com.wia.exception.APIConnectionException; -import com.wia.exception.APIException; -import com.wia.exception.AuthenticationException; -import com.wia.exception.InvalidRequestException; +import io.wia.exception.APIConnectionException; +import io.wia.exception.APIException; +import io.wia.exception.AuthenticationException; +import io.wia.exception.InvalidRequestException; import java.util.Map; -import com.wia.net.APIResource; public interface WiaResponseGetter { public T request( diff --git a/src/main/java/com/wia/net/WiaSSLSocketFactory.java b/src/main/java/io/wia/net/WiaSSLSocketFactory.java similarity index 87% rename from src/main/java/com/wia/net/WiaSSLSocketFactory.java rename to src/main/java/io/wia/net/WiaSSLSocketFactory.java index 9f2ed57..aa9632d 100644 --- a/src/main/java/com/wia/net/WiaSSLSocketFactory.java +++ b/src/main/java/io/wia/net/WiaSSLSocketFactory.java @@ -1,4 +1,4 @@ -package com.wia.net; +package io.wia.net; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; @@ -18,15 +18,15 @@ */ public class WiaSSLSocketFactory extends SSLSocketFactory { private final SSLSocketFactory under; - private final boolean tlsv11Supported, tlsv12Supported; + private final boolean tlsv11Supported, tlsv12Supported, sslv3Supported; - private static final String TLSv11Proto = "TLSv1.1", TLSv12Proto = "TLSv1.2"; + private static final String TLSv11Proto = "TLSv1.1", TLSv12Proto = "TLSv1.2", SSLv3Proto = "SSLv3"; public WiaSSLSocketFactory() { this.under = HttpsURLConnection.getDefaultSSLSocketFactory(); // For sufficiently old Java, TLSv1.1 and TLSv1.2 might not be supported, so do some detection - boolean tlsv11Supported = false, tlsv12Supported = false; + boolean tlsv11Supported = false, tlsv12Supported = false, sslv3Supported = false; String[] supportedProtos = new String[0]; try { @@ -39,11 +39,14 @@ public WiaSSLSocketFactory() { tlsv11Supported = true; } else if (proto.equals(TLSv12Proto)) { tlsv12Supported = true; + } else if (proto.equals(SSLv3Proto)) { + sslv3Supported = true; } } this.tlsv11Supported = tlsv11Supported; this.tlsv12Supported = tlsv12Supported; + this.sslv3Supported = sslv3Supported; } private Socket fixupSocket(Socket sock) { @@ -60,11 +63,18 @@ private Socket fixupSocket(Socket sock) { if (tlsv12Supported) { protos.add(TLSv12Proto); } + if (sslv3Supported) { + protos.add(SSLv3Proto); + } + for (String s : protos) { + System.out.println(s); + } sslSock.setEnabledProtocols(protos.toArray(new String[0])); + return sslSock; } - +//DHE-RSA-AES256-SHA @Override public String[] getDefaultCipherSuites() { return this.under.getDefaultCipherSuites(); diff --git a/src/main/java/io/wia/net/WiaSensorSubscribeCallback.java b/src/main/java/io/wia/net/WiaSensorSubscribeCallback.java new file mode 100644 index 0000000..6f91b58 --- /dev/null +++ b/src/main/java/io/wia/net/WiaSensorSubscribeCallback.java @@ -0,0 +1,7 @@ +package io.wia.net; + +import io.wia.model.Sensor; + +public interface WiaSensorSubscribeCallback extends WiaSubscribeCallback { + public void received(Sensor sensor); +} diff --git a/src/main/java/io/wia/net/WiaSubscribeCallback.java b/src/main/java/io/wia/net/WiaSubscribeCallback.java new file mode 100644 index 0000000..9841336 --- /dev/null +++ b/src/main/java/io/wia/net/WiaSubscribeCallback.java @@ -0,0 +1,5 @@ +package io.wia.net; + +public interface WiaSubscribeCallback { + +} diff --git a/src/test/java/io/wia/WiaStreamTest.java b/src/test/java/io/wia/WiaStreamTest.java new file mode 100644 index 0000000..842d5be --- /dev/null +++ b/src/test/java/io/wia/WiaStreamTest.java @@ -0,0 +1,256 @@ +package io.wia; + +import io.wia.model.*; +import io.wia.net.*; +import io.wia.exception.*; + +import org.apache.log4j.BasicConfigurator; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.junit.After; +import org.junit.Test; + +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class WiaStreamTest { + private static Logger logger = LogManager.getLogger(WiaTest.class); + + static String getSecretKey() { + return System.getProperty("testusersecretkey") != null ? System.getProperty("testusersecretkey") : System.getenv("WIA_TEST_USER_SECRET_KEY"); + } + + static String getDeviceSecretKey() { + return System.getProperty("testdevicesecretkey") != null ? System.getProperty("testdevicesecretkey") : System.getenv("WIA_TEST_DEVICE_SECRET_KEY"); + } + + static String getDeviceId() { + return System.getProperty("testdeviceid") != null ? System.getProperty("testdeviceid") : System.getenv("WIA_TEST_DEVICE_ID"); + } + + static String getRestApiBase() { + return System.getenv("WIA_TEST_REST_API") != null ? System.getenv("WIA_TEST_REST_API") : "https://api.wia.io"; + } + + @Test + public void initTests() { + BasicConfigurator.configure(); + logger.debug("Starting tests."); + WiaClient.getInstance().overrideRestApiBase(getRestApiBase()); + } + + @After + public void disconnectFromStream() throws MqttException, InterruptedException { + WiaStreamClient.getInstance().unsubscribeFromAll(); + Wia.disconnectFromStream(); + logger.info("Disconnected from stream!"); + Thread.sleep(250); + } + + @Test + public void testUserConnectToStream() throws WiaException, InterruptedException, MqttException { + Wia.setSecretKey(getSecretKey()); + + Wia.connectToStream(); + Thread.sleep(250); + logger.info("Connected to stream!"); + } + + @Test + public void testUserIsConnectedToStream() throws WiaException, InterruptedException, MqttException { + Wia.setSecretKey(getSecretKey()); + + Wia.connectToStream(); + Thread.sleep(250); + assertTrue(Wia.isConnectedToStream()); + } + + @Test + public void testDeviceConnectToStream() throws WiaException, InterruptedException, MqttException { + Wia.setSecretKey(getDeviceSecretKey()); + + Wia.connectToStream(); + logger.info("Connected to stream!"); + Thread.sleep(750); + } + + @Test + public void testDeviceIsConnectedToStream() throws WiaException, InterruptedException, MqttException { + Wia.setSecretKey(getDeviceSecretKey()); + + Wia.connectToStream(); + Thread.sleep(250); + assertTrue(Wia.isConnectedToStream()); + } + + @Test + public void testUserSubscribeToEvents() throws WiaException, InterruptedException, MqttException { + Wia.setSecretKey(getSecretKey()); + + Wia.connectToStream(); + Thread.sleep(250); + assertTrue(Wia.isConnectedToStream()); + + final String eventName = "myFirstEvent"; + + Event.subscribe(getDeviceId(), eventName, new WiaEventSubscribeCallback() { + @Override + public void received(Event event) { + logger.debug("Got event. Timestamp: " + event.getTimestamp()); + assertEquals(eventName, event.getName()); + assertNotNull(event.getTimestamp()); + } + }); + Thread.sleep(2500); + Event.unsubscribe(getDeviceId(), eventName); + Thread.sleep(250); + } + + @Test + public void testUserSubscribeToLogs() throws WiaException, InterruptedException, MqttException { + Wia.setSecretKey(getSecretKey()); + + Wia.connectToStream(); + Thread.sleep(250); + assertTrue(Wia.isConnectedToStream()); + + final String logLevel = "info"; + + Log.subscribe(getDeviceId(), logLevel, new WiaLogSubscribeCallback() { + @Override + public void received(Log log) { + logger.debug("Got log. Timestamp: " + log.getTimestamp()); + assertEquals(logLevel, log.getLevel()); + assertNotNull(log.getTimestamp()); + } + }); + Thread.sleep(2500); + Log.unsubscribe(getDeviceId(), logLevel); + Thread.sleep(250); + } + + @Test + public void testUserSubscribeToLocations() throws WiaException, InterruptedException, MqttException { + Wia.setSecretKey(getSecretKey()); + + Wia.connectToStream(); + Thread.sleep(250); + assertTrue(Wia.isConnectedToStream()); + + Location.subscribe(getDeviceId(), new WiaLocationSubscribeCallback() { + @Override + public void received(Location location) { + logger.debug("Got location. Timestamp: " + location.getTimestamp() + " Latitude: " + location.getLatitude() + " Longitude: " + location.getLongitude()); + assertNotNull(location.getTimestamp()); + assertNotNull(location.getLatitude()); + assertNotNull(location.getLongitude()); + } + }); + Thread.sleep(2500); + Location.unsubscribe(getDeviceId()); + Thread.sleep(250); + } + + @Test + public void testUserSubscribeToSensors() throws WiaException, InterruptedException, MqttException { + Wia.setSecretKey(getSecretKey()); + + Wia.connectToStream(); + Thread.sleep(250); + assertTrue(Wia.isConnectedToStream()); + + Sensor.subscribe(getDeviceId(), new WiaSensorSubscribeCallback() { + @Override + public void received(Sensor sensor) { + logger.debug("Got sensor. Timestamp: " + sensor.getTimestamp()); + assertNotNull(sensor.getTimestamp()); + assertNotNull(sensor.getName()); + } + }); + Thread.sleep(2500); + Sensor.unsubscribe(getDeviceId()); + Thread.sleep(250); + } + + @Test + public void testDevicePublishEvents() throws WiaException, InterruptedException, MqttException { + Wia.setSecretKey(getDeviceSecretKey()); + + Wia.connectToStream(); + Thread.sleep(250); + assertTrue(Wia.isConnectedToStream()); + + Map eventParams = new HashMap(); + eventParams.put("name", "testEvent"); + eventParams.put("data", "data goes here"); + + int max = 20; + for (int i=0;i sensorParams = new HashMap(); + sensorParams.put("name", "temperature"); + sensorParams.put("data", 21.5); + + int max = 20; + for (int i=0;i logParams = new HashMap(); + logParams.put("level", "info"); + logParams.put("message", "this is a log message"); + + int max = 20; + for (int i=0;i locationParams = new HashMap(); + locationParams.put("latitude", 40.7144); + locationParams.put("longitude", -74.006); + + int max = 20; + for (int i=0;i getCreateDeviceParams() { + Map params = new HashMap(); + params.put("name", "Test Device"); + return params; + } + + @Test + public void initTests() { + BasicConfigurator.configure(); + logger.debug("Starting tests."); + WiaClient.getInstance().overrideRestApiBase(getRestApiBase()); + } + + @Test + public void testCreateDevice() throws WiaException { + Wia.setSecretKey(getSecretKey()); + + Device device = Device.create(getCreateDeviceParams()); + assertNotNull(device); + } + + @Test + public void testRetrieveDevice() throws WiaException { + Wia.setSecretKey(getSecretKey()); + + Device createdDevice = Device.create(getCreateDeviceParams()); + assertNotNull(createdDevice); + Device retrievedDevice = Device.retrieve(createdDevice.getId()); + assertNotNull(retrievedDevice); + } + + @Test + public void testUpdateDevice() throws WiaException { + Wia.setSecretKey(getSecretKey()); + + Map createParams = new HashMap(); + createParams.put("name", "Old device name"); + + Device createdDevice = Device.create(createParams); + assertNotNull(createdDevice); + + Device retrievedDevice = Device.retrieve(createdDevice.getId()); + assertNotNull(retrievedDevice); + + Map updateParams = new HashMap(); + updateParams.put("name", "New device name"); + + retrievedDevice.update(updateParams); + } + + @Test + public void testDeleteDevice() throws WiaException { + Wia.setSecretKey(getSecretKey()); + + Map createParams = new HashMap(); + createParams.put("name", "Device name"); + + Device createdDevice = Device.create(createParams); + assertNotNull(createdDevice); + + WiaDeletedObject deletedDevice = createdDevice.delete(); + assertEquals(createdDevice.getId(), deletedDevice.getId()); + } + + @Test + public void testListDevices() throws WiaException { + Wia.setSecretKey(getSecretKey()); + + DeviceCollection devicesCollection = Device.list(null); + System.out.println("Device count: " + devicesCollection.getCount()); + assertNotNull(devicesCollection); + } + + @Test + public void testListDevicesWithParams() throws WiaException { + Wia.setSecretKey(getSecretKey()); + + Map params = new HashMap(); + params.put("limit", 10); + + DeviceCollection devicesCollection = Device.list(params); + System.out.println("Device count: " + devicesCollection.getCount()); + assertNotNull(devicesCollection); + } + + @Test + public void testPublishEvent() throws WiaException { + Wia.setSecretKey(getDeviceSecretKey()); + + Map params = new HashMap(); + params.put("name", "testEvent"); + + Event event = Event.publish(params); + assertNotNull(event); + } + + @Test + public void testPublishEventWithData() throws WiaException { + Wia.setSecretKey(getDeviceSecretKey()); + + Map params = new HashMap(); + params.put("name", "testEventNumber"); + params.put("data", 213.545); + + Event event = Event.publish(params); + assertNotNull(event); + } + + @Test + public void testPublishEventWithDataObject() throws WiaException { + Wia.setSecretKey(getDeviceSecretKey()); + + Map dataObj = new HashMap(); + dataObj.put("x", 12.45); + dataObj.put("y", 456.74); + dataObj.put("z", 2.56); + + Map params = new HashMap(); + params.put("name", "testEventObj"); + params.put("data", dataObj); + + Event event = Event.publish(params); + assertNotNull(event); + } + + @Test + public void testListEvents() throws WiaException { + Wia.setSecretKey(getSecretKey()); + + Map createParams = new HashMap(); + createParams.put("name", "Device name"); + + Device createdDevice = Device.create(createParams); + assertNotNull(createdDevice); + + logger.debug("Getting events for device: " + createdDevice.getId()); + + Map listParams = new HashMap(); + listParams.put("device", createdDevice.getId()); + + EventCollection eventsCollection = Event.list(listParams); + assertNotNull(eventsCollection); + assertNotNull(eventsCollection.getEvents()); + assertNotNull(eventsCollection.getCount()); + } + + @Test + public void testPublishLocation() throws WiaException { + Wia.setSecretKey(getDeviceSecretKey()); + + Map params = new HashMap(); + params.put("latitude", 40.7144); + params.put("longitude", -74.006); + + Location location = Location.publish(params); + assertNotNull(location); + } + + @Test + public void testListLocations() throws WiaException { + Wia.setSecretKey(getSecretKey()); + + Map createParams = new HashMap(); + createParams.put("name", "testListLocations"); + + Device createdDevice = Device.create(createParams); + assertNotNull(createdDevice); + + Map listParams = new HashMap(); + listParams.put("device", createdDevice.getId()); + + LocationCollection locationsCollection = Location.list(listParams); + assertNotNull(locationsCollection); + assertNotNull(locationsCollection.getLocations()); + assertNotNull(locationsCollection.getCount()); + } + + @Test + public void testPublishLog() throws WiaException { + Wia.setSecretKey(getDeviceSecretKey()); + + Map params = new HashMap(); + params.put("level", "info"); + params.put("message", "This is a log message"); + + Log log = Log.publish(params); + assertNotNull(log); + } + + @Test + public void testListLogs() throws WiaException { + Wia.setSecretKey(getSecretKey()); + + Map createParams = new HashMap(); + createParams.put("name", "testListLogs"); + + Device createdDevice = Device.create(createParams); + assertNotNull(createdDevice); + + Map listParams = new HashMap(); + listParams.put("device", createdDevice.getId()); + + LogCollection logCollection = Log.list(listParams); + assertNotNull(logCollection); + assertNotNull(logCollection.getLogs()); + assertNotNull(logCollection.getCount()); + } + + + @Test + public void testPublishSensor() throws WiaException { + Wia.setSecretKey(getDeviceSecretKey()); + + Map params = new HashMap(); + params.put("name", "temperature"); + params.put("data", 21.453); + + Sensor sensor = Sensor.publish(params); + assertNotNull(sensor); + } + + @Test + public void testListSensors() throws WiaException { + Wia.setSecretKey(getSecretKey()); + + Map createParams = new HashMap(); + createParams.put("name", "testListSensors"); + + Device createdDevice = Device.create(createParams); + assertNotNull(createdDevice); + + Map listParams = new HashMap(); + listParams.put("device", createdDevice.getId()); + + SensorCollection sensorCollection = Sensor.list(listParams); + assertNotNull(sensorCollection); + assertNotNull(sensorCollection.getSensors()); + assertNotNull(sensorCollection.getCount()); + } +} \ No newline at end of file