Examples
Query example
package com.kx.sapi.examples;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.kx.sapi.constants.RC;
import com.kx.q.c;
import com.kx.sapi.Kxs;
import com.kx.sapi.KxsResponse;
import com.kx.sapi.RetryPolicy;
import com.kx.sapi.SapiConfig;
import com.kx.sapi.SapiTLS;
//
// This program provides a basic example for executing commands using the SDK.
//
public class Execute {
private static final Logger LOG = LoggerFactory.getLogger(Execute.class);
static final Logger logger = LoggerFactory.getLogger("My logger");
public static void main(String []args) {
SapiConfig options = new SapiConfig();
// Set up the connection properties
options.setUsername("your-username");
options.setPassword("your-password");
options.setInstanceName("your-instance-name");
options.setListenPorts("10000-10010");
// options.setAdvertiseHosts("10.10.0.3");
SapiTLS tls = new SapiTLS();
Path currentPath = Paths.get("").toAbsolutePath();
tls.setCAFile(currentPath.resolve("examples/certs/ca-cert.pem").toString());
tls.setCertFile(currentPath.resolve("examples/certs/client-cert.pem").toString());
tls.setKeyFile(currentPath.resolve("examples/certs/client-private-key.pem").toString());
tls.setVerifyClient(false);
tls.setVerifyServer(false);
options.setUseTLS(true);
options.setTLS(tls);
// Specify the discovery server(s) node urls
options.setDiscoveryHosts(new String[] {
"your-discovery-node.com:20000"
});
RetryPolicy rp = new RetryPolicy(3, 20000, 1000, 1.5f);
options.setRetryPolicy(rp); // Assign the retry policy to the connection options
Kxs kxs = new Kxs();
KxsResponse response = new KxsResponse(); // Attempt the connection process
if (!kxs.connect(options, response))
{
if (LOG != null) LOG.error("Unexpected RC response, rc={} ac={}", response.getRC(), response.getAC());
return;
}
createDict(kxs); // Creates a c.Dict that will be sent to the server and displays the result
createFlip(kxs); // Creates a c.Flip that will be sent to the server and displays the result
}
public static void createDict(Kxs kxs) {
String[] requestKeys = new String[] { "query" };
Object[] requestValues = new Object[] { "(`a`b`c)!(1 2 3)".toCharArray() };
c.Dict request = new c.Dict(requestKeys, requestValues);
KxsResponse response = new KxsResponse();
boolean result = kxs.execute(".kxs.execute", request, null, null, response);
if (result && response.getRC() == RC.OK.value)
{
c.Dict dict = (c.Dict) response.getPayload();
String[] headers = (String[]) dict.x;
long[] values = (long[]) dict.y;
for (int i = 0; i < headers.length; i++)
{
if (LOG != null) LOG.debug("name={} value={}", headers[i], values[i]);
}
}
}
public static void createFlip(Kxs kxs) {
String[] requestKeys = new String[] { "query" };
Object[] requestValues = new Object[] { "10#enlist (`a`b`c)!(1 2 3)".toCharArray() };
c.Dict request = new c.Dict(requestKeys, requestValues);
KxsResponse response = new KxsResponse();
boolean result = kxs.execute(".kxs.execute", request, null, null, response);
if (result && response.getRC() == RC.OK.value)
{
c.Flip flip = (c.Flip) response.getPayload();
for (int i = 0; i < flip.x.length; i++)
{
long[] values = (long[]) flip.y[i];
for (int j = 0; j < values.length; j++)
{
if (LOG != null) LOG.debug("name={} value={}", flip.x[i], values[j]);
}
}
}
}
}
Publish example
package com.kx.sapi.examples;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.kx.sapi.Kxs;
import com.kx.sapi.KxsResponse;
import com.kx.sapi.RetryPolicy;
import com.kx.sapi.SapiConfig;
import com.kx.sapi.SapiRtConfig;
import com.kx.sapi.SapiTLS;
import com.kx.q.c;
import com.kx.q.c.KException;
//
// This program provides a basic example for executing commands using the SDK.
//
public class Publish {
private static final ThreadLocal<c> THREAD_SERIALIZER = ThreadLocal.withInitial(c::new);
private static final Logger LOG = LoggerFactory.getLogger(Publish.class);
static final Logger logger = LoggerFactory.getLogger("My logger");
public static void main(String[] args) throws InterruptedException {
SapiConfig options = new SapiConfig();
// Set up the connection properties
options.setUsername("your-username");
options.setPassword("your-password");
options.setInstanceName("java-instance");
options.setListenPorts("8000-8020");
// Specify the discovery server(s) node urls
options.setDiscoveryHosts(new String[] {
"your-discovery-node.com:20000"
});
options.setAdvertiseHosts("10.10.0.3");
Path currentPath = Paths.get("").toAbsolutePath();
SapiTLS tls = new SapiTLS();
tls.setCAFile(currentPath.resolve("examples/certs/ca-cert.pem").toString());
tls.setCertFile(currentPath.resolve("examples/certs/client-cert.pem").toString());
tls.setKeyFile(currentPath.resolve("examples/certs/client-private-key.pem").toString());
tls.setVerifyClient(false);
tls.setVerifyServer(false);
options.setTLS(tls);
options.setUseTLS(true);
SapiRtConfig rtConfig = new SapiRtConfig();
rtConfig.setRtDir(currentPath.resolve("rt").toString());
rtConfig.setConfigPath(currentPath.resolve("rt").toString());
rtConfig.setUseBridge(true);
options.setRtConfig(rtConfig);
RetryPolicy rp = new RetryPolicy(3, 5000, 1000, 1.5f);
options.setRetryPolicy(rp); // Assign the retry policy to the connection options
Kxs kxs = new Kxs();
KxsResponse response = new KxsResponse(); // Attempt the connection process
if (!kxs.connect(options, response)) {
LOG.error("Unexpected RC response, rc={} ac={}", response.getRC(), response.getAC());
return;
}
try {
publish(kxs);
} catch (IOException e) {
e.printStackTrace();
} catch (KException e) {
e.printStackTrace();
}
}
public static void publish(Kxs kxs) throws KException, UnsupportedEncodingException, IOException, InterruptedException {
Path currentPath = Paths.get("").toAbsolutePath();
KxsResponse response = new KxsResponse();
long topicHandle = kxs.registerPublisher("feed1", response);
if (topicHandle > 0)
{
for (int i = 0; i < 50000; i++)
{
c.Dict header = (c.Dict) deserialize(readFileToBytes(currentPath.resolve("examples/data/ingen_publish_header.bin").toString()));
Object payload = deserialize(readFileToBytes(currentPath.resolve("examples/data/ingen_publish_payload.bin").toString()));
RetryPolicy rp = new RetryPolicy(3, 5000, 1000, 1.5f);
KxsResponse pubResponse = new KxsResponse();
Boolean result = kxs.publish(topicHandle, (short) 100, payload, header, rp, pubResponse);
Thread.sleep(50);
}
kxs.unregisterPublisher(topicHandle, response);
}
}
public static byte[] readFileToBytes(String filePath) throws IOException {
Path path = Paths.get(filePath);
return Files.readAllBytes(path);
}
public static Object deserialize(byte[] bytes) throws UnsupportedEncodingException, KException {
return bytes == null ? null : THREAD_SERIALIZER.get().deserialize(bytes);
}
}
MQ example
package com.kx.sapi.examples;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.kx.sapi.Kxs;
import com.kx.sapi.KxsResponse;
import com.kx.sapi.RetryPolicy;
import com.kx.sapi.SapiTLS;
import com.kx.sapi.KxsQueueListener;
import com.kx.sapi.SapiConfig;
import com.kx.sapi.KxsQueueListener.AckMode;
//
// This program provides a basic example for executing commands using the SDK.
//
public class QueueListener {
private static final Logger LOG = LoggerFactory.getLogger(QueueListener.class); // <-- fixed
static final Logger logger = LoggerFactory.getLogger("My logger");
private static final String LOG_CATEGORY = "Java Example";
public static void main(String []args) {
SapiConfig options = new SapiConfig();
// Set up the connection properties
options.setUsername("your-username");
options.setPassword("your-password");
options.setInstanceName("your-instance-name");
options.setListenPorts("10000-10010");
options.setAdvertiseHosts("10.10.0.3");
SapiTLS tls = new SapiTLS();
Path currentPath = Paths.get("").toAbsolutePath();
tls.setCAFile(currentPath.resolve("examples/certs/ca-cert.pem").toString());
tls.setCertFile(currentPath.resolve("examples/certs/client-cert.pem").toString());
tls.setKeyFile(currentPath.resolve("examples/certs/client-private-key.pem").toString());
tls.setVerifyClient(false);
tls.setVerifyServer(false);
options.setUseTLS(true);
options.setTLS(tls);
// Specify the discovery server(s) node urls
options.setDiscoveryHosts(new String[] {
"your-discovery-node.com:20000"
});
RetryPolicy rp = new RetryPolicy(3, 20000, 1000, 1.5f);
options.setRetryPolicy(rp); // Assign the retry policy to the connection options
Kxs kxs = new Kxs();
KxsResponse response = new KxsResponse();
if (!kxs.connect(options, response)) {
if (LOG != null) LOG.error("Unexpected RC response, rc={} ac={}", response.getRC(), response.getAC());
return;
}
log(LogLevel.INFO, "Connected to server!");
final String queueName = "DistSD";
KxsQueueListener listener = new KxsQueueListener() {
@Override
public boolean accept(Kxs client, String queue, long messageId, KxsResponse response) {
log(LogLevel.INFO, String.format(
"Received message/ack, queue=%s id=%d reqCorr=%s",
queue, messageId, response != null ? response.getReqCorr() : "null"));
client.ackQueueMessage(queue, messageId);
return true;
}
};
response = new KxsResponse();
boolean reqQueue = kxs.registerQueueListener(queueName, listener, AckMode.CLIENT, response);
log(LogLevel.INFO, String.format(
"registerQueueListener RC=%d AC=%d AI=%d ok=%s",
response.getRC(), response.getAC(), response.getAi(), reqQueue));
// Waiting 1 minute for callbacks
try {
Thread.sleep(60_000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
// Unregister and disconnect
response = new KxsResponse();
boolean unregQueue = kxs.unregisterQueueListener(queueName, response);
log(LogLevel.INFO, String.format(
"unregisterQueueListener RC=%d AC=%d AI=%d ok=%s",
response.getRC(), response.getAC(), response.getAi(), unregQueue));
kxs.disconnect();
}
private static void log(LogLevel lvl, String msg) {
System.out.printf("%d [%s] %s%n", lvl.code, LOG_CATEGORY, msg);
}
private enum LogLevel {
VERBOSE(1), DEBUG(2), INFO(3), WARN(4), ERROR(5), FATAL(6);
final int code;
LogLevel(int c) { this.code = c; }
}
}