The Vantiq API provides an API for interacting with the Vantiq server.
This document defines the Vantiq Client SDK. Please refer to the Vantiq Reference Guides for details on the how to use the Vantiq system.
The Vantiq object provides the main API for the Vantiq Java SDK. This SDK follows the Vantiq REST API resources model.
Each of the SDK API methods corresponds to a specific REST API operation on a specific resource. For example,
select performs a query against a given resource. select("system.types", ...) queries against defined data types.
select("system.procedures", ...) queries against defined procedures.
The available system resources are defined in the Vantiq.SystemResources enum and include the following:
| Enum Name | Resource Name | Type Name | Description |
|---|---|---|---|
| ANALYTICS_MODELS | analyticsmodels | ArsAnalyticsModel | Analytics Models defined in the Vantiq system |
| CONFIGURATIONS | configurations | ArsRuleConfiguration | Configurations of Vantiq artifacts |
| DOCUMENTS | documents | ArsDocument | Unstructured documents stored in the Vantiq system |
| NAMESPACES | namespaces | ArsNamespace | Namespaces defined in the Vantiq system |
| NODES | nodes | ArsPeerNode | Node defined in the Vantiq system to support federation |
| PROCEDURES | procedures | ArsComponent | Procedures defined in the Vantiq system |
| PROFILES | profiles | ArsProfile | Vantiq user permission profiles |
| RULES | rules | ArsRuleSet | Rules defined in the Vantiq system |
| SCALARS | scalars | ArsScalar | User-defined property type definitions |
| SERVICES | services | ArsSource | Data sources defined in the Vantiq system |
| SOURCES | sources | ArsSource | Data sources defined in the Vantiq system |
| TOPICS | topics | ArsTopic | User-defined topics in the Vantiq system |
| TYPES | types | ArsType | Data types defined in the Vantiq system |
| USERS | users | ArsUser | Vantiq user accounts |
| IMAGES | images | ArsImages | Images stored in the Vantiq system |
| VIDEOS | videos | ArsVideos | Videos stored in the Vantiq system |
Data types defined in the Vantiq system can also be used as resources. For example, if you define data
type MyNewType, then MyNewType is now a legal resource name that can be used in the API methods.
- authenticate
- select
- selectOne
- count
- insert
- update
- upsert
- delete
- deleteOne
- publish
- execute
- evaluate
- query
- subscribe
- unsubscribeAll
- upload
- download
All Vantiq SDK methods have both an asynchronous form and a synchronous form. The asynchronous form requires a response handler that is executed when the response from the Vantiq server arrives,
vantiq.method(arg1, arg2, ..., responseHandler);The synchronous form blocks until the response from the Vantiq server arrives and returns the response as the return value,
VantiqResponse response = vantiq.method(arg1, arg2, ...);The Vantiq constructor creates a new instance of the Vantiq SDK object.
The SDK expects that the first operation is to authenticate onto the
specified Vantiq server. After successfully authenticated, the client
is free to issue any requests to the Vantiq server.
This class exposes the Vantiq REST API
Vantiq vantiq = new Vantiq(String server[, int apiVersion, [Authenticator proxyAuthentcator]])| Name | Type | Required | Description |
|---|---|---|---|
| server | String | Yes | The Vantiq server URL to connect to, e.g. https://dev.vantiq.com |
| apiVersion | int | No | The version of the API to use. Defaults to the latest. |
| proxyAuthenticator | okhttp3.Authenticator | No | An Authenticator to use when an http proxy requires authentication. This is required only when BASIC user/password authentication is insufficient. The SDK will provide a built-in authenticator using the scheme.proxyUser and scheme.proxyPassword (where scheme is the scheme from the server URL (http or https)). |
An instance of the Vantiq object
Vantiq vantiq = new Vantiq("https://dev.vantiq.com");The authenticate method connects to the Vantiq server with the given
authentication credentials used to authorize the user. Upon success,
an access token is provided to the client for use in subsequent API
calls to the Vantiq server. The username and password credentials
are not stored.
void vantiq.authenticate(String username, String password, ResponseHandler handler)
VantiqResponse vantiq.authenticate(String username, String password)| Name | Type | Required | Description |
|---|---|---|---|
| username | String | Yes | The username to provide access to the Vantiq server |
| password | String | Yes | The password to provide access to the Vantiq server |
| handler | ResponseHandler | Yes | A ResponseHandler that is called upon success or failure |
The authenticate method returns a Boolean body indicating if the authentication was successful.
vantiq.authenticate("joe@user", "my-secr3t-passw0rd!#!", new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("Authenticated!");
}
@Override public void onError(List<VantiqError> errors, Response response) {
super.onError(errors, response);
System.out.println("Errors: " + errors);
}
});The select method issues a query to select all matching records for a given
resource.
void vantiq.select(String resource,
List<String> props,
Object where,
SortSpec sort,
ResponseHandler handler)
VantiqResponse vantiq.select(String resource,
List<String> props,
Object where,
SortSpec sort)| Name | Type | Required | Description |
|---|---|---|---|
| resource | String | Yes | The name of the resource type to query. Must be either SystemResources.TOPICS.value(), SystemResources.SOURCES.value() or SystemResources.TYPES.value(). |
| props | List | No | Specifies the desired properties to be returned in each record. An empty list or null value means all properties will be returned. |
| where | Object | No | Specifies constraints to filter the data. Null means all records will be returned. This object uses Gson to convert to a JSON value for the REST API. |
| sort | SortSpec | No | Specifies the desired sort for the result set |
| handler | ResponseHandler | Yes | Listener that is called upon success or failure |
The props is an list of property names indciating which properties should be returned.
The where is an object with supported operations defined in API operations that will be converted to JSON using Gson.
The sort is a SortSpec object that indicate the property to sort by and the direction of the sort (i.e. ascending or descending).
The select method returns a body of type List<JsonObject> providing the list of matching records.
Select the name property for all available types.
vantiq.select(Vantiq.SystemResources.TYPES.value(),
Collections.singletonList("name"),
null,
null,
new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
for(JsonObject obj : (List<JsonObject>) body) {
System.out.println(obj.get("name").getAsString());
}
}
});Selects all properties filtering to only return types with the TestType name.
JsonObject where = new JsonObject();
where.addProperty("name", "TestType");
vantiq.select(Vantiq.SystemResources.TYPES.value(),
null,
where,
null,
new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
for(JsonObject obj : (List<JsonObject>) body) {
System.out.println(obj);
}
}
});Selects all records for the TestType type returning only the key and value properties and sorting the results by the key in descending order.
vantiq.select(Vantiq.SystemResources.TYPES.value(),
Arrays.asList("key", "value"),
null,
new SortSpec("key", true),
new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
for(JsonObject obj : (List<JsonObject>) body) {
System.out.println(obj);
}
}
});The selectOne method issues a query to return the single record identified
by the given identifier.
void vantiq.selectOne(String resouce, String id, ResponseHandler handler)
VantiqResponse vantiq.selectOne(String resouce, String id)| Name | Type | Required | Description |
|---|---|---|---|
| resource | String | Yes | The name of the resource type to query. Must be either SystemResources.TOPICS.value(), SystemResources.SOURCES.value() or SystemResources.TYPES.value().SystemResources.TYPES.value(). |
| id | String | Yes | The unique identifier for the given record ("_id" for user defined Types) |
| handler | ResponseHandler | Yes | Listener that is called upon success or failure |
The selectOne method returns a body of type JsonObject providing the matching record.
Select the TestType definition from the types resource.
vantiq.selectOne(Vantiq.SystemResources.TYPES.value(), "TestType", new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println((JsonObject) obj);
}
});Selects a TestType record with _id equal to 23425231ad31f.
vantiq.selectOne("TestType", "23425231ad31f", new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println((JsonObject) obj);
}
});The count method is similar to the select method except it returns only the
number of records rather than returning the records themselves.
void vantiq.count(String resource, Object where, ResponseHandler handler)
VantiqResponse vantiq.count(String resource, Object where)| Name | Type | Required | Description |
|---|---|---|---|
| resource | String | Yes | The name of the resource type to query. Must be either SystemResources.TOPICS.value(), SystemResources.SOURCES.value() or SystemResources.TYPES.value().SystemResources.TYPES.value(). |
| where | Object | No | Specifies constraints to filter the data. Null means all records will be returned. |
| handler | ResponseHandler | Yes | Listener that is called upon success or failure |
The where is an object with supported operations defined in API operations that will be converted to JSON using Gson.
The count method returns a body of type Integer providing the
count of the matching records.
Counts the number of TestType records.
vantiq.count("TestType", null, new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("TestType has " + (Integer) body + " records");
}
});Counts the number of TestType with a value greater than 10.
JsonObject where = new JsonObject();
JsonObject gt = new JsonObject();
gt.addProperty("$gt", 10);
where.add("value", gt);
vantiq.count("TestType", where, new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("TestType has " + (Integer) body + " records with value > 10");
}
});The insert method creates a new record of a given resource.
void vantiq.insert(String resource, Object object, ResponseHandler handler)
VantiqResponse vantiq.insert(String resource, Object object)| Name | Type | Required | Description |
|---|---|---|---|
| resource | String | Yes | The name of the resource type to query. Must be either SystemResources.TOPICS.value(), SystemResources.SOURCES.value() or SystemResources.TYPES.value().SystemResources.TYPES.value(). |
| object | Object | Yes | The object to insert. |
| handler | ResponseHandler | Yes | Listener that is called upon success or failure |
The insert method returns a JsonObject object containing the object just inserted.
Inserts an object of type TestType.
JsonObject objToInsert = new JsonObject();
objToInsert.addProperty("key", "SomeKey");
objToInsert.addProperty("value", 42);
vantiq.insert("TestType", objToInsert, new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println((JsonObject) obj);
}
});
The update method updates an existing record of a given resource. This method
supports partial updates meaning that only the properties provided are updated.
Any properties not specified are not changed in the underlying record.
void vantiq.update(String resource, String id, Object object, ResponseHandler handler)
VantiqResponse vantiq.update(String resource, String id, Object object)| Name | Type | Required | Description |
|---|---|---|---|
| resource | String | Yes | The name of the resource type to query. Must be either SystemResources.TOPICS.value(), SystemResources.SOURCES.value() or SystemResources.TYPES.value(). |
| id | String | Yes | The unique identifer for the record ("_id" for user defined Types) |
| props | Object | Yes | The properties to update in the record. |
| handler | ResponseHandler | Yes | Listener that is called upon success or failure |
The update method returns a JsonObject object containing the object just updated.
Updates a given TestType record
String _id = "56f4c52120eb8b5dee4898fd";
JsonObject propsToUpdate = new JsonObject();
propsToUpdate.addProperty("value", 13);
vantiq.update("TestType", _id, propsToUpdate, new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println((JsonObject) obj);
}
});The upsert method either creates or updates a record in the database depending
if the record already exists. The method tests for existence by looking at the
natural keys defined on the resource.
void vantiq.upsert(String resource, Object object, ResponseHandler response)
VantiqResponse vantiq.upsert(String resource, Object object)| Name | Type | Required | Description |
|---|---|---|---|
| resource | String | Yes | The name of the resource type to query. Must be either SystemResources.TOPICS.value(), SystemResources.SOURCES.value() or SystemResources.TYPES.value(), or SystemResources.TYPES.value(). |
| object | Object | Yes | The object to upsert. |
| handler | ResponseHandler | Yes | Listener that is called upon success or failure |
The upsert method return a JsonObject object containing the object just inserted or created.
Inserts an object of type TestType.
JsonObject objToUpsert = new JsonObject();
objToUpsert.addProperty("key", "SomeKey");
objToUpsert.addProperty("value", 42);
vantiq.upsert("TestType", objToUpsert, new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println((JsonObject) obj);
}
});The delete method removes records from the system for a given resource. Deletes always
require a constraint indicating which records to remove.
void vantiq.delete(String resource, Object where, ResponseHandler handler)
VantiqResponse vantiq.delete(String resource, Object where)| Name | Type | Required | Description |
|---|---|---|---|
| resource | String | Yes | The name of the resource type to query. Must be either SystemResources.TOPICS.value(), SystemResources.SOURCES.value() or SystemResources.TYPES.value(). |
| where | Object | Yes | Specifies which records to remove. |
| handler | ResponseHandler | Yes | Listener that is called upon success or failure |
The where is an object with supported operations defined in API operations that will be converted to JSON using Gson.
The delete method returns a boolean indicating the removal succeeded.
Removes the record with the given key.
JsonObject where = new JsonObject();
where.addProperty("key", "SomeKey");
vantiq.delete("TestType", where, new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("Delete succeeded.");
}
});Removes all records of TestType with a value greater than 10.
JsonObject where = new JsonObject();
JsonObject gt = new JsonObject();
gt.addProperty("$gt", 10);
where.add("value", gt);
vantiq.delete("TestType", where, new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("Deleted all records with value > 10.");
}
});The deleteOne method removes a single record specified by the given identifier.
void vantiq.deleteOne(String resource, String id, ResponseHandler response)
VantiqResponse vantiq.deleteOne(String resource, String id)| Name | Type | Required | Description |
|---|---|---|---|
| resource | String | Yes | The name of the resource type to query. |
Must be either `SystemResources.TOPICS.value()`, `SystemResources.SOURCES.value()` or `SystemResources.TYPES.value()`.
id | String | Yes | The unique identifier for the record ("_id" for user defined Types) handler | ResponseHandler | Yes | Listener that is called upon success or failure
The deleteOne method returns a boolean indicating the removal succeeded.
Removes the TestType definition from the types resource.
vantiq.deleteOne(Vantiq.SystemResources.TYPES.value(), "TestType", new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("Delete succeeded.");
}
});Removes the TestType record with _id equal to 23425231ad31f.
vantiq.deleteOne("TestType", "23425231ad31f", new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("Delete succeeded.");
}
});The publish method supports publishing to a topic or a source.
Publishing a message to a given topic allows for rules to be defined
that trigger based on the publish event. Topics are slash-delimited strings,
such as '/test/topic'. Vantiq reserves /type, /property, /system, and
/source as system topic namespaces and should not be published to. The
payload is the message to be sent.
Calling publish on a source performs a publish (asynchronous call) on the
specified source. The payload is the parameters required to issue the
publish operation on the source.
void vantiq.publish(String resource, String id, Object payload, ResponseHandler response)
VantiqResponse vantiq.publish(String resource, String id, Object payload)| Name | Type | Required | Description |
|---|---|---|---|
| resource | String | Yes | The name of the resource type to query. |
Must be either `SystemResources.SERVICES.value()` or `SystemResources.TOPICS.value()` or `SystemResources.SOURCES.value()`.
id | String | Yes | The name of the Service Event Type, Topic or Source (ie: 'testService/inboundTestEvent' or '/test/topic' or 'mqttChannel').
payload | Object | Yes | For Topics, the payload is the message to send. For Sources, this is the parameters for the source.
handler | ResponseHandler | Yes | Listener that is called upon success or failure
For sources, the parameters required are source specific and are the same as those required
when performing a PUBLISH ... TO SOURCE ... USING params. Please refer to the specific source definition
documentation in the Vantiq API Documentation.
Since the publish operation is a fire-and-forget action, a successful publish will result in a boolean value indicating the publish occurred.
Send a message onto the /test/topic topic.
JsonObject message = new JsonObject();
message.addProperty("key", "AnotherKey");
message.addProperty("value", 13);
vantiq.publish(Vantiq.SystemResources.TOPICS.value(),
"/test/topic",
message,
new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("Published message successfully");
}
});Send a message to a SMS source mySMSSource.
JsonObject params = new JsonObject();
params.addProperty("body", "Nice message to the user");
params.addProperty("to", "+16505551212");
vantiq.publish(Vantiq.SystemResources.SOURCES.value(),
"mySMSSource",
params,
new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("Published to source successfully");
}
});The execute method executes a procedure on the Vantiq server. Procedures can
take parameters (i.e. arguments) and produce a result.
void vantiq.execute(String procedure, Object params, ResponseHandler response)
VantiqResponse vantiq.execute(String procedure, Object params)| Name | Type | Required | Description |
|---|---|---|---|
| procedure | String | Yes | The name of the procedure to execute |
| params | Object | No | An object that holds the parameters. |
| handler | ResponseHandler | Yes | Listener that is called upon success or failure |
The parameters may be provided as an array where the arguments are given in order. Alternatively, the parameters may be provided as an object where the arguments are named.
The execute method returns with a JsonObject object containing the result of the procedure call.
Executes an sum procedure that takes arg1 and arg2 arguments and returns the total using positional arguments.
JsonArray params = new JsonArray();
params.add(new JsonPrimitive(1));
params.add(new JsonPrimitive(2));
vantiq.execute("sum", params, new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("The sum of 1 + 2 = " + this.getBodyAsJsonObject().get("total"));
}
});Using named arguments.
JsonObject params = new JsonObject();
params.addProperty("arg1", 1);
params.addProperty("arg1", 2);
vantiq.execute("sum", params, new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("The sum of 1 + 2 = " + this.getBodyAsJsonObject().get("total"));
}
});The evaluate method evaluates an analytics model on the Vantiq server. Analytics models
expect input data as parameters and produce a result.
void vantiq.evaluate(String modelName, Object params, ResponseHandler response)
VantiqResponse vantiq.evaluate(String modelName, Object params)| Name | Type | Required | Description |
|---|---|---|---|
| modelName | String | Yes | The name of the analytics model to execute |
| params | Object | No | An object that holds the parameters. |
| handler | ResponseHandler | Yes | Listener that is called upon success or failure |
The input data in the params field should be structured in the form defined by the
analytics model. In general, it should be a JSON object with a structured defined as the
input record type in the model.
The evaluate method return with a JsonObject or JsonPrimitive object containing the result of the model.
Evaluates an Score analytics model that takes arg1 and arg2 arguments and returns the score in a
JsonObject.
JsonObject params = new JsonObject();
params.addProperty("arg1", "xxx");
params.addProperty("arg1", "yyy");
vantiq.evaluate("Score", params, new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("The model score is = " + this.getBodyAsJsonObject().get("score"));
}
});The query method performs a query (synchronous call) on the specified source. The query can
take parameters (i.e. arguments) and produce a result.
void vantiq.query(String source, Object params, ResponseHandler handler)
VantiqResponse vantiq.query(String source, Object params)| Name | Type | Required | Description |
|---|---|---|---|
| source | String | Yes | The name of the Source to perform the query |
| params | Object | No | An object that holds the parameters. |
| handler | ResponseHandler | Yes | Listener that is called upon success or failure |
The parameters required are source specific and are the same as those required
when performing a SELECT ... FROM SOURCE ... WITH params. Please refer to the specific source definition
documentation in the Vantiq API Documentation.
The query method returns with a JsonObject object containing the returned value from the source.
Query a REST source adder that returns the total of the given parameters.
JsonObject params = new JsonObject();
params.addProperty("path", "/api/adder");
params.addProperty("method", "POST");
params.addProperty("contentType", "application/json");
JsonObject body = new JsonObject();
body.addProperty("arg1", 1);
body.addProperty("arg2", 2);
params.add("body", body);
vantiq.query("sum", params, new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("The sum of 1 + 2 = " + this.getBodyAsJsonObject().get("total"));
}
});The subscribe method creates a WebSocket to the Vantiq server and listens for specified events. The provided
callback is executed whenever a matching event occurs.
void vantiq.subscribe(String resource, String name, TypeOperation operation, SubscriptionCallback callback, Map parameters)| Name | Type | Required | Description |
|---|---|---|---|
| resource | String | Yes | The resource event to subscribe. Must be either SystemResources.TOPICS.value(), SystemResources.SOURCES.value(), SystemResources.SERVICES.value(), or SystemResources.TYPES.value(). |
| name | String | Yes | The resource name that identifies the specific resource event. For topics, this is the topic name (e.g. '/my/topic/'). For sources, this is the source name. For services, this must be the service and event name in the form '/'. For types, this is the data type name. |
| operation | TypeOperation | No | This only applies for 'types' and specifies the operation to listen to (e.g. TypeOperation.INSERT, TypeOperation.UPDATE, TypeOperation.DELETE) |
| callback | SubscriptionCallback | Yes | This callback is executed when the specified events occur. |
| parameters | Map<String, String> | No | Map specifying extra details about the subscription to the server. (eg: {persistent:true} to create a persistent subscription, {persistent:true: subscriptionName: 'mySub', requestId: requestId} to reconnect to a broken persistent subscription) |
The SubscriptionCallback interface contains 4 methods:
| Name | Argument | Description |
|---|---|---|
onConnect() |
N/A | Called once the connection has been established and the subscription has been acknowledged by the Vantiq server. |
onMessage(m) |
SubscriptionMessage | Called for every matching event that occurs |
onError(e) |
String | Called whenever an error occurs that does not arise from an exception, such as if a non-success response is provided. The argument provides the error message. |
onFailure(e) |
Throwable | Called whenever an exception occurs during the subscription processing. |
The SubscriptionMessage contains the fields:
| Name | Type | Description |
|---|---|---|
| status | int | The status for the given message. The possible values are the HTTP status codes. Typically, this would be 100. |
| contentType | String | The content MIME type for the message body. Typically, this is application/json. |
| headers | Map | Headers associated with the response. |
| body | Object | The payload for the event. For JSON encoded responses, this is typically a Map. |
The structure of the body of the event is:
| Name | Type | Description |
|---|---|---|
| path | String | The full event path |
| value | Object | The payload of the event. |
N/A
In this example, we implement a callback that simply prints out the events to standard out:
public class StandardOutputCallback implements SubscriptionCallback {
@Override
public void onConnect() {
System.out.println("Connected Successfully");
}
@Override
public void onMessage(SubscriptionMessage message) {
System.out.println("Received Message: " + message);
}
@Override
public void onError(String error) {
System.out.println("Error: " + error);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}
Create a subscription to the /test/topic topic that prints out when events are published to the topic.
vantiq.subscribe(Vantiq.SystemResources.TOPICS.value(),
"/test/topic",
null,
new StandardOutputCallback());
Create a subscription to the MySource source that prints out when messages arrive at the source.
vantiq.subscribe(Vantiq.SystemResources.SOURCES.value(),
"MySource",
null,
new StandardOutputCallback());
Create a subscription to the MyService service's MyEvent service event that prints out when messages arrive at the source.
vantiq.subscribe(Vantiq.SystemResources.SERVICES.value(),
"MyService/MyEvent",
null,
new StandardOutputCallback());
Create a subscription to the MyDataType type for that prints out when that type has been updated.
vantiq.subscribe(Vantiq.SystemResources.TYPES.value(),
"MyDataType",
Vantiq.TypeOperation.UPDATE,
new StandardOutputCallback());
See acknowledge section for how to create a persistent subscription and acknowledge reliable events
The unsubscribeAll method removes all active subscriptions to the Vantiq server by
closing the WebSocket.
void vantiq.unsubscribeAll()N/A
N/A
vantiq.unsubscribeAll();
The upload method performs an upload of a file into a Vantiq resource. The default upload method will upload the file to
the ArsDocument resource, but the user may optionally specify which Vantiq resource they wish to upload to. The upload may be
asynchronous or synchronous.
void vantiq.upload(File file, String contentType, String documentPath, ResponseHandler responseHandler)
VantiqResopnse vantiq.upload(File file, String contentType, String documentPath)OR
void vantiq.upload(File file, String contentType, String documentPath, String resourcePath, ResponseHandler responseHandler)
VantiqResopnse vantiq.upload(File file, String contentType, String documentPath, String resourcePath)| Name | Type | Required | Description |
|---|---|---|---|
| file | File | Yes | The file to be uploaded |
| contentType | String | Yes | The MIME type of the uploaded file (e.g. "image/jpeg") |
| String | documentPath | Yes | The "path" of the ArsDocument in Vantiq (e.g. "assets/myDocument.txt") |
| String | resourcePath | No | The "path" of the Vantiq resource to which you wish to upload the file (e.g. "/resources/documents", "/resources/images", or "/resources/videos") |
The upload method returns a JsonObject object containing the information about the stored document. In particular, the response will contain:
| Name | Type | Description |
|---|---|---|
| name | String | The document path (e.g. "assets/myDocument.txt") |
| fileType | String | The MIME type of the uploaded file (e.g. "image/jpeg") |
| content | String | This provides the URI path to download the content. This is used in the download method. |
The following uploads a text file asynchronously and prints out the location of the content:
File myFile = ...
vantiq.upload(myFile,
"text/plain",
"myAssets/myFile.txt",
new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("Content Location = " + this.getBodyAsJsonObject().get("content"));
}
});The following uploads an image file asynchronously, specifying that the image be stored in Vantiq as an image (instead of a document), and prints out the location of the content:
File myFile = ...
vantiq.upload(myFile,
"image/jpeg",
"myAssets/myImage.jpg",
"/resources/images",
new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
System.out.println("Content Location = " + this.getBodyAsJsonObject().get("content"));
}
});The download method pulls down the content of a file that was
previously uploaded. The download method may be synchronous or asynchronous, but the data is always streamed to the client.
void vantiq.download(String path, ResponseHandler responseHandler)
VantiqResopnse vantiq.download(String path)| Name | Type | Required | Description |
|---|---|---|---|
| path | String | Yes | This is the path to the file. This can be gotten from the content field in the ArsDocument or the returned value from the upload method. |
The download response body is a Okio.BufferedSource that can be used
to stream the data to the client.
The following calls the download asynchronously and prints out the file contents:
String path = ...from ArsDocument...
vantiq.download(path, new BaseResponseHandler() {
@Override public void onSuccess(Object body, Response response) {
super.onSuccess(body, response);
byte[] data = ((BufferedSource) body).readByteArray();
System.out.println("File: " + new String(data, "UTF-8"));
}
});The following calls the download synchronoulsy and writes the file to disk:
String path = ...from ArsDocument...
OutputStream os = ...stream to write...
VantiqResponse resopnse = vantiq.download(path);
BufferedSource source = (BufferedSource) response.getBody();
byte[] buf = new byte[1024];
while((int len = source.read(buf)) != -1) {
os.write(buf, 0, len);
}
os.close();The acknowledge method is used to acknowledge the receipt of messages from reliable resources after creating a persistent subscription.
The provided callback is executed whenever a matching event occurs.
void vantiq.ack(String subscriptionName, String requestId, Map msg)| Name | Type | Required | Description |
|---|---|---|---|
| subscriptionName | String | Yes | The name of the subscription that uniquely identifies the persistent subscription. This was returned by the server on creation of the persistent subscription. |
| requestId | String | Yes | The id of the requestId that that uniquely identifies the websocket requests made by this subscription. This was returned by the server on creation of the persistent subscription. |
| msg | Map | Yes | The message in the event being acknowledged. This is the body of the SubscriptionMessage |
N/A
Create a callback that acknowledges events as they arrive.
public class AcknowledgingOutputCallback implements SubscriptionCallback {
private String subscriptionName;
private String requestId;
@Override
public void onConnect() {
System.out.println("Connected Successfully");
}
@Override
public void onMessage(SubscriptionMessage message) {
//Server response with subscription information (not a topic event)
if (message.body.subscriptionName) {
this.subscriptionName = message.body.subscriptionName;
this.requestId = message.body.requestId;
System.out.println("SubscriptionName " + this.subscriptionName);
System.out.println("RequestId " + this.requestId);
} else {
//message.body is an event on the subscribed topic. Acknowledge that we received the event
vantiq.ack(this.subscriptionName, this.requestId, message.body);
}
}
@Override
public void onError(String error) {
System.out.println("Error: " + error);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}
Create a persistent subscription to the /test/topic reliable topic that acknowledges when events are published to the topic.
vantiq.subscribe(Vantiq.SystemResources.TOPICS.value(),
"/test/topic",
null,
new AcknowledgingOutputCallback(),
{persistent: true});
Create a subscription to the MySource reliable source that prints out when messages arrive at the source.
vantiq.subscribe(Vantiq.SystemResources.SOURCES.value(),
"MySource",
null,
new AcknowledgingOutputCallback(),
{persistent: true});
To reconnect to a severed persistent subscription.
vantiq.subscribe(Vantiq.SystemResources.TOPICS.value(),
"/test/topic",
null,
new AcknowledgingOutputCallback(),
{persistent: true, subscriptionName: subscriptionName, requestId: requestId});
The accessToken property provides access to the
access token and a means for explicitly
setting an access token without the authenticate method.
The token may be a token previously retrieved through the
authenticate method or a long-lived token issued by the
Vantiq server.
After setting the access token, the SDK assumes that the session has been authenticated and operations can be issued.
The server URL used to connect to the Vantiq system.
After setting the server, the SDK uses the URL for all future requests.
The username associated with the authenticated user in Vantiq.
The authenticate method sets this upon success.
The enablePings property determines if periodic pings should
be sent on the WebSocket subscriptions. This may be required
as some proxy servers will close connections if they are idle.
The default value is true.
The readTimeout property determines the timeout for waiting
for data. A value of zero means there is no timeout.
The default value is 0.
The writeTimeout property determines the timeout while writing
data. A value of zero means there is no timeout.
The default value is 0.
The connectTimeout property determines the timeout to establish
a connection. A value of zero means there is no timeout.
The default value is 0.
The VantiqResponse object holds the completion state of the
Vantiq SDK method if the synchronous form is used.
| Name | Description |
|---|---|
| getBody | Returns the parsed content of the response. This is usually a JsonElement. |
| getContentType | Returns the content type header value |
| getCount | If a count was requested, this returns the count value |
| getErrors | Errors returned from the Vantiq server, if any |
| getException | The exception thrown during processing, if any |
| getResponse | The underlying OkHttp3 response object |
| getStatusCode | The HTTP response status code |
| hasErrors | Indicates if there were errors from the Vantiq server |
| hasException | Indicates if there was an exception during processing |
| isSuccess | Indicates if the operation was successful |
The ResponseHandler interface provides the API that are called when the Vantiq SDK methods complete either
successfully or in error.
The SDK provides the concrete class BaseResponseHandler that implements the ResponseHandler interface and provides
helper methods.
| Name | Description |
|---|---|
| onSuccess | Called when the method call returns successfully (i.e. HTTP status codes 2xx). The response body is parsed and provided in the body argument. |
| onError | Called when the server returns one or more errors (i.e. HTTP status codes 4xx/5xx). |
| onFailure | Called when the client has an exception during processing. |
On Android, the BaseResponseHandler can be used within an AsyncTask to support Vantiq server requests while still
allowing the UI to be responsive. Below is an example of how to create a base async task class (from the
Android example).
package io.vantiq.examplesdkclient;
import android.os.AsyncTask;
import io.vantiq.client.BaseResponseHandler;
import io.vantiq.client.Vantiq;
/**
* Abstract AsyncTask class that provides an easy mechanism to issue requests
* to the Vantiq server. Like other async tasks, this should only be used once.
*/
public abstract class VantiqAsyncTask<Params,Progress,Result> extends AsyncTask<Params,Progress,Result> {
private Vantiq vantiq;
private BaseResponseHandler handler;
private boolean done = false;
public VantiqAsyncTask(Vantiq vantiq) {
this.vantiq = vantiq;
// Provide the response handler that simply indicates when the response has finished
this.handler = new BaseResponseHandler() {
@Override public void completionHook(boolean success) {
VantiqAsyncTask.this.done = true;
}
};
}
/**
* Abstract method that must be overridden by subclasses to issue a Vantiq request.
* @param handler The response handler
*/
abstract protected void doRequest(Vantiq vantiq, BaseResponseHandler handler);
/**
* Abstract method that must be overridden by subclasses to return the result.
* @param handler The response handler
* @return The response of this async task
*/
abstract protected Result prepareResult(BaseResponseHandler handler);
@Override
protected final Result doInBackground(Params... params) {
// Issue request to the server
doRequest(this.vantiq, this.handler);
// Wait for the request to be completed
try {
while (!this.done) {
Thread.sleep(100);
}
} catch(InterruptedException ex) {
/* If interrupted, then just drop out */
}
return prepareResult(this.handler);
}
}This async task makes it easy to use the Vantiq SDK API. Here is an example of running a select operation.
// Trigger select query
this.selectTask = new SelectTypesTask(vantiq);
this.selectTask.execute((Void) null);Using the following SelectTypesTask.
/**
* Async task to perform a select to return all available types from the Vantiq server.
*/
public class SelectTypesTask extends VantiqAsyncTask<Void, Void, List<Map<String,String>>> {
SelectTypesTask(Vantiq vantiq) {
super(vantiq);
}
@Override
protected void doRequest(Vantiq vantiq, BaseResponseHandler handler) {
vantiq.select(Vantiq.SystemResources.TYPES.value(),
Arrays.asList("name", "namespace"),
null,
new SortSpec("name", /*descending=*/ false),
handler);
}
@Override
protected List<Map<String,String>> prepareResult(BaseResponseHandler handler) {
List<Map<String,String>> result = Lists.newArrayList();
// At this point, we should have a result, so we pull out the response
if(handler.getBody() != null) {
for(JsonObject obj : handler.getBodyAsList()) {
Map<String,String> entry = Maps.newHashMap();
entry.put("name", obj.get("name").getAsString());
entry.put("namespace", obj.get("namespace").getAsString());
result.add(entry);
}
} else if(handler.hasErrors()) {
MainActivity.this.onServerError(handler.getErrors().toString());
} else if(handler.hasException()) {
MainActivity.this.onServerError(handler.getException().getMessage());
}
return result;
}
@Override
protected void onPostExecute(final List<Map<String,String>> result) {
MainActivity.this.selectTask = null;
onServerCompletion(result);
}
}The REST API provides an error in the following form:
{
code: <ErrorIdentifier>,
message: <ErrorMessage>,
params: [ <ErrorParameter>, ... ]
}
The SDK returns errors using the VantiqError object.
| Name | Type | Description |
|---|---|---|
| code | String | The Vantiq error id (e.g. "io.vantiq.authentication.failed") |
| message | String | The human readable message associated with the error |
| params | List<Object> | A list of arguments associated with the error |