How to Send a Push Notification to AWS SNS

JAX-RS

import static org.apache.commons.codec.digest.DigestUtils.sha256Hex;
import static org.apache.commons.codec.digest.HmacUtils.hmacSha256;
import static org.apache.commons.codec.digest.HmacUtils.hmacSha256Hex;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;

@WebServlet(name = "SampleSnsServlet", value = "/")
public final class SampleSnsServlet extends HttpServlet {

  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) {
    final Client client = ClientBuilder.newClient();

    final String stringToSign = "AWS4-HMAC-SHA256\nlongDate\nshortDate/regionName/sns/aws4_request\n" + sha256Hex("POST\n/accountId/SampleTopic\n\nhost:host\nx-amz-date:longDate\n\nhost;x-amz-date\n" + sha256Hex("Action=Publish&Message=Simples+Assim&TopicArn=topicArn"));

    final String signature = hmacSha256Hex(hmacSha256(hmacSha256(hmacSha256(hmacSha256("AWS4secretKey", shortDate), "regionName".getBytes()), "sns".getBytes()), "aws4_request".getBytes()), stringToSign.getBytes());

    final MultivaluedMap<String, String> params = new MultivaluedHashMap<>();

    params.putSingle("Action", "Publish");

    params.putSingle("Message", "Simples Assim");

    params.putSingle("TopicArn", "topicArn");

    client.target("queueUrl").request().header("X-Amz-Date", longDate).header("Authorization", "AWS4-HMAC-SHA256 Credential=accessKeyId/shortDate/regionName/sns/aws4_request, SignedHeaders=host;x-amz-date, Signature=" + signature).post(Entity.form(params));

    client.close();
  }

}

Java

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.sns.AmazonSNSClient;

public final class SnsSample {

  public static void main(final String[] args) throws Exception {
    final AmazonSNSClient client = new AmazonSNSClient(new BasicAWSCredentials("accessKeyId", "secretAccessKey"));

    client.publish("topicArn", "Simples Assim"");

    client.shutdown();
  }

}

JavaScript

AWS.config.update({ credentials: new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'identityPoolId', accessKeyId: 'accessKeyId', secretAccessKey: 'secretAccessKey' }), region: 'regionName' });

const sns = new AWS.SNS();

sns.publish({ Message: 'Simples Assim', TopicArn: 'topicArn' }, (err, res) => {});

Node.js

const AWS = require('aws-sdk');

AWS.config.update({ credentials: new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'identityPoolId', accessKeyId: 'accessKeyId', secretAccessKey: 'secretAccessKey' }), region: 'regionName' });

const sns = new AWS.SNS();

sns.publish({ Message: 'Simples Assim', TopicArn: 'topicArn' }, (err, res) => {});

Python

import boto3

sess = boto3.session.Session('accessKeyId', 'secretAccessKey', region_name='regionName')

sns = sess.resource('sns')

topic = sqs.create_topic(Name='SampleTopic')

topic.publish(Message='Simples Assim')
Advertisements

How to Receive a Message from AWS SQS

JAX-RS

import static java.lang.System.out;
import static org.apache.commons.codec.digest.DigestUtils.sha256Hex;
import static org.apache.commons.codec.digest.HmacUtils.hmacSha256;
import static org.apache.commons.codec.digest.HmacUtils.hmacSha256Hex;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;

@WebServlet(name = "SampleSqsServlet", value = "/")
public final class SampleSqsServlet extends HttpServlet {

  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp){
    final Client client = ClientBuilder.newClient();

    final String stringToSign = "AWS4-HMAC-SHA256\nlongDate\nshortDate/regionName/sqs/aws4_request\n" + sha256Hex("POST\n/accountId/SampleQueue\n\nhost:host\nx-amz-date:longDate\n\nhost;x-amz-date\n" + sha256Hex("Action=ReceiveMessage"));

    final String signature = hmacSha256Hex(hmacSha256(hmacSha256(hmacSha256(hmacSha256("AWS4secretKey", shortDate), "regionName".getBytes()), "sqs".getBytes()), "aws4_request".getBytes()), stringToSign.getBytes());

    final Response res = client.target("queueUrl").request().header("X-Amz-Date", longDate).header("Authorization", "AWS4-HMAC-SHA256 Credential=accessKeyId/shortDate/regionName/sqs/aws4_request, SignedHeaders=host;x-amz-date, Signature=" + signature).post(Entity.form(new Form().param("Action", "ReceiveMessage")));

    out.println(res.readEntity(String.class));

    client.close();
  }

}

Java

import static java.lang.System.out;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageResult;

public final class SqsSample {

  public static void main(final String[] args) throws Exception {
    final AmazonSQSClient client = new AmazonSQSClient(new BasicAWSCredentials("accessKeyId", "secretAccessKey"));

    final ReceiveMessageResult res = client.receiveMessage("queueUrl");

    for (final Message msg : res.getMessages()) {
      out.println(msg);

      client.deleteMessage("queueUrl", msg.getReceiptHandle());
    }

    client.shutdown();
  }

}

JavaScript

AWS.config.update({ credentials: new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'identityPoolId', accessKeyId: 'accessKeyId', secretAccessKey: 'secretAccessKey' }), region: 'regionName' });

const sqs = new AWS.SQS();

sqs.receiveMessage({ QueueUrl: 'queueUrl' }, (err, res) => {
  console.log(res.Messages[0].Body);

  sqs.deleteMessage({ QueueUrl: 'queueUrl', ReceiptHandle: res.Messages[0].ReceiptHandle }, (err, res) => {});
});

Node.js

const AWS = require('aws-sdk');

AWS.config.update({ credentials: new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'identityPoolId', accessKeyId: 'accessKeyId', secretAccessKey: 'secretAccessKey' }), region: 'regionName' });

const sqs = new AWS.SQS();

sqs.receiveMessage({ QueueUrl: 'queueUrl' }, (err, res) => {
  console.log(res.Messages[0].Body);

  sqs.deleteMessage({ QueueUrl: 'queueUrl', ReceiptHandle: res.Messages[0].ReceiptHandle }, (err, res) => {});
});

Python

import boto3

sess = boto3.session.Session('accessKeyId', 'secretAccessKey', region_name='regionName')

sqs = sess.resource('sqs')

queue = sqs.create_queue(QueueName='SampleQueue')

for msg in queue.receive_messages():
  print(msg)

  msg.delete()

How to Send a Message to AWS SQS

JAX-RS

import static org.apache.commons.codec.digest.DigestUtils.sha256Hex;
import static org.apache.commons.codec.digest.HmacUtils.hmacSha256;
import static org.apache.commons.codec.digest.HmacUtils.hmacSha256Hex;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;

@WebServlet(name = "SampleSqsServlet", value = "/")
public final class SampleSqsServlet extends HttpServlet {

  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) {
    final Client client = ClientBuilder.newClient();

    final String stringToSign = "AWS4-HMAC-SHA256\nlongDate\nshortDate/regionName/sqs/aws4_request\n" + sha256Hex("POST\n/accountId/SampleQueue\n\nhost:host\nx-amz-date:longDate\n\nhost;x-amz-date\n" + sha256Hex("Action=SendMessage&MessageBody=Simples+Assim"));

    final String signature = hmacSha256Hex(hmacSha256(hmacSha256(hmacSha256(hmacSha256("AWS4secretKey", shortDate), "regionName".getBytes()), "sqs".getBytes()), "aws4_request".getBytes()), stringToSign.getBytes());

    final MultivaluedMap<String, String> params = new MultivaluedHashMap<>();

    params.putSingle("Action", "SendMessage");

    params.putSingle("MessageBody", "Simples Assim");

    client.target("queueUrl").request().header("X-Amz-Date", longDate).header("Authorization", "AWS4-HMAC-SHA256 Credential=accessKeyId/shortDate/regionName/sqs/aws4_request, SignedHeaders=host;x-amz-date, Signature=" + signature).post(Entity.form(params));

    client.close();
  }

}

Java

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.sqs.AmazonSQSClient;

public final class SqsSample {

  public static void main(final String[] args) throws Exception {
    final AmazonSQSClient client = new AmazonSQSClient(new BasicAWSCredentials("accessKeyId", "secretAccessKey"));

    client.sendMessage("queueUrl", "Simples Assim"");

    client.shutdown();
  }

}

JavaScript

AWS.config.update({ credentials: new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'identityPoolId', accessKeyId: 'accessKeyId', secretAccessKey: 'secretAccessKey' }), region: 'regionName' });

const sqs = new AWS.SQS();

sqs.sendMessage({ MessageBody: 'Simples Assim', QueueUrl: 'queueUrl' }, (err, res) => {});

Node.js

const AWS = require('aws-sdk');

AWS.config.update({ credentials: new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'identityPoolId', accessKeyId: 'accessKeyId', secretAccessKey: 'secretAccessKey' }), region: 'regionName' });

const sqs = new AWS.SQS();

sqs.sendMessage({ MessageBody: 'Simples Assim', QueueUrl: 'queueUrl' }, (err, res) => {});

Python

import boto3

sess = boto3.session.Session('accessKeyId', 'secretAccessKey', region_name='regionName')

sqs = sess.resource('sqs')

queue = sqs.create_queue(QueueName='SampleQueue')

queue.send_message(MessageBody='Simples Assim')

How to Receive a Pull Notification from the Oracle Messaging Cloud Service

JAX-RS

W/o Durability

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

@WebServlet(name = "SampleOmcsServlet", value = "/")
public final class SampleOmcsServlet extends HttpServlet {

  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    final Client client = ClientBuilder.newClient();

    client.register(HttpAuthenticationFeature.basic("username", "password"));

    Response res = client.target("https://host/service/api/v1/connections/SampleConnection").request().header("X-OC-ID-TOKEN-STATUS", "disabled").put(Entity.json(""));

    final Cookie jsessionid = res.getCookies().get("JSESSIONID");

    client.target("https://host/service/api/v1/sessions/SampleSession").queryParam("connection", "SampleConnection").request().cookie(jsessionid).put(Entity.json(""));

    client.target("https://host/service/api/v1/consumers/SampleConsumer").queryParam("destination", "/topics/SampleTopic").queryParam("session", "SampleSession").request().cookie(str).put(Entity.json(""));

    client.target("https://host/service/api/v1/connections/SampleConnection").queryParam("action", "start").request().cookie(jsessionid).post(Entity.json(""));

    res = client.target("https://host/service/api/v1/consumers/SampleConsumer/messages").queryParam("timeout", 1000).request().cookie(jsessionid).post(Entity.json(""));

    resp.getWriter().println(res.readEntity(String.class));

    client.close();
  }

}

W/ Durability

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

@WebServlet(name = "SampleOmcsServlet", value = "/")
public final class SampleOmcsServlet extends HttpServlet {

  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    final Client client = ClientBuilder.newClient();

    client.register(HttpAuthenticationFeature.basic("username", "password"));

    Response res = client.target("https://host/service/api/v1/connections/SampleConnection").request().header("X-OC-ID-TOKEN-STATUS", "disabled").queryParam("clientId", "SampleClient").put(Entity.json(""));

    final Cookie jsessionid = res.getCookies().get("JSESSIONID");

    client.target("https://host/service/api/v1/sessions/SampleSession").queryParam("connection", "SampleConnection").request().cookie(jsessionid).put(Entity.json(""));

    client.target("https://host/service/api/v1/consumers/SampleConsumer").queryParam("destination", "/topics/SampleTopic").queryParam("session", "SampleSession").queryParam("subscriptionName", "SampleSubscription").request().cookie(str).put(Entity.json(""));

    client.target("https://host/service/api/v1/connections/SampleConnection").queryParam("action", "start").request().cookie(jsessionid).post(Entity.json(""));

    res = client.target("https://host/service/api/v1/consumers/SampleConsumer/messages").queryParam("timeout", 1000).request().cookie(jsessionid).post(Entity.json(""));

    resp.getWriter().println(res.readEntity(String.class));

    client.close();
  }

}

Java

W/o Durability

import static java.lang.System.out;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import oracle.cloud.messaging.client.MessagingService;
import oracle.cloud.messaging.client.MessagingServiceCredentials;
import oracle.cloud.messaging.client.MessagingServiceFactory;
import oracle.cloud.messaging.client.MessagingServiceNamespace;

public final class OmcsSample {

  public static void main(final String[] args) throws Exception {
    final MessagingServiceFactory serviceFactory = MessagingServiceFactory.getInstance();

    final MessagingService service = serviceFactory.getMessagingService(new MessagingServiceNamespace("uri"), new MessagingServiceCredentials("username", "password"));

    final ConnectionFactory connFactory = service.getConnectionFactory();

    final Connection conn = connFactory.createConnection();

    final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    final Destination dest = sess.createTopic("SampleTopic");

    final MessageConsumer cons = sess.createConsumer(dest);

    conn.start();

    final Message msg = cons.receive();

    out.println(msg);

    conn.close();
  }

}

W/ Durability

import static java.lang.System.out;
 
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.Topic;

import oracle.cloud.messaging.client.MessagingService;
import oracle.cloud.messaging.client.MessagingServiceCredentials;
import oracle.cloud.messaging.client.MessagingServiceFactory;
import oracle.cloud.messaging.client.MessagingServiceNamespace;

public final class OmcsSample {

  public static void main(final String[] args) throws Exception {
    final MessagingServiceFactory serviceFactory = MessagingServiceFactory.getInstance();

    final MessagingService service = serviceFactory.getMessagingService(new MessagingServiceNamespace("uri"), new MessagingServiceCredentials("username", "password"));

    final ConnectionFactory connFactory = service.getConnectionFactory("SampleClient");

    final Connection conn = connFactory.createConnection();

    final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    final Topic dest = sess.createTopic("SampleTopic");

    final MessageConsumer cons = sess.createDurableSubscriber(dest, "SampleSubscription");

    conn.start();

    final Message msg = cons.receive();

    out.println(msg);

    conn.close();
  }

}

JavaScript

W/o Durability

const req = new XMLHttpRequest();

req.open("PUT", "https://host/service/api/v1/connections/SampleConnection", true, "username", "password");

req.setRequestHeader("X-OC-ID-TOKEN-STATUS", "disabled");

req.onreadystatechange = () => {

  if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
    const req = new XMLHttpRequest();

    req.open("PUT", "https://host/service/api/v1/sessions/SampleSession?connection=SampleConnection");

    req.onreadystatechange = () => {

      if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
        const req = new XMLHttpRequest();

        req.open("PUT", "https://host/service/api/v1/consumers/SampleConsumer?destination=/topics/SampleTopic&session=SampleSession");

        req.onreadystatechange = () => {

          if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
            const req = new XMLHttpRequest();

            req.open("POST", "https://host/service/api/v1/connections/SampleConnection?action=start");

            req.onreadystatechange = () => {

              if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 200)) {
                const req = new XMLHttpRequest();

                req.open("POST", "https://host/service/api/v1/consumers/SampleConsumer/messages?timeout=1000");

                req.onreadystatechange = () => {

                  if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 200))
                    console.log(req.responseText);

                };

                req.send();
              }

            };

            req.send();
          }

        };

        req.send();
      }

    };

    req.send();
  }

};

req.send();

W/ Durability

const req = new XMLHttpRequest();

req.open("PUT", "https://host/service/api/v1/connections/SampleConnection?clientId=SampleClient", true, "username", "password");

req.setRequestHeader("X-OC-ID-TOKEN-STATUS", "disabled");

req.onreadystatechange = () => {

  if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
    const req = new XMLHttpRequest();

    req.open("PUT", "https://host/service/api/v1/sessions/SampleSession?connection=SampleConnection");

    req.onreadystatechange = () => {

      if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
        const req = new XMLHttpRequest();

        req.open("PUT", "https://host/service/api/v1/consumers/SampleConsumer?destination=/topics/SampleTopic&session=SampleSession&subscriptionName=SampleSubscription");

        req.onreadystatechange = () => {

          if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
            const req = new XMLHttpRequest();

            req.open("POST", "https://host/service/api/v1/connections/SampleConnection?action=start");

            req.onreadystatechange = () => {

              if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 200)) {
                const req = new XMLHttpRequest();

                req.open("POST", "https://host/service/api/v1/consumers/SampleConsumer/messages?timeout=1000");

                req.onreadystatechange = () => {

                  if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 200))
                    console.log(req.responseText);

                };

                req.send();
              }

            };

            req.send();
          }

        };

        req.send();
      }

    };

    req.send();
  }

};

req.send();

Node.js

W/o Durability

const https = require('https');

const req = https.request({ auth: 'username:password', headers: { 'X-OC-ID-TOKEN-STATUS': 'disabled' }, hostname: 'host', method: 'PUT', path: '/service/api/v1/connections/SampleConnection' }, (res) => {

  if (res.statusCode === 201) {
    const cookies = res.headers['set-cookie'];

    const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'PUT', path: '/service/api/v1/sessions/SampleSession?connection=SampleConnection' }, (res) => {

      if (res.statusCode === 201) {
        const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'PUT', path: '/service/api/v1/consumers/SampleConsumer?destination=/topics/SampleTopic&session=SampleSession' }, (res) => {

          if (res.statusCode === 201) {
            const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'POST', path: '/service/api/v1/connections/SampleConnection?action=start' }, (res) => {

              if (res.statusCode === 200) {
                const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'POST', path: '/service/api/v1/consumers/SampleConsumer/messages?timeout=1000' }, (res) => {

                  if (res.statusCode === 200) {
                    var body = '';

                    res.on('data', (chunk) => {
                      body += chunk.toString();
                    });

                    res.on('end', () => {
                      console.log(body);
                    });

                  }

                });

                req.end();
              }

            });

            req.end();
          }

        });

        req.end();
      }

    });

    req.end();
  }

});

req.end();

W/ Durability

const https = require('https');

const req = https.request({ auth: 'username:password', headers: { 'X-OC-ID-TOKEN-STATUS': 'disabled' }, hostname: 'host', method: 'PUT', path: '/service/api/v1/connections/SampleConnection?clientId=SampleClient' }, (res) => {

  if (res.statusCode === 201) {
    const cookies = res.headers['set-cookie'];

    const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'PUT', path: '/service/api/v1/sessions/SampleSession?connection=SampleConnection' }, (res) => {

      if (res.statusCode === 201) {
        const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'PUT', path: '/service/api/v1/consumers/SampleConsumer?destination=/topics/SampleTopic&session=SampleSession&subscriptionName=SampleSubscription' }, (res) => {

          if (res.statusCode === 201) {
            const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'POST', path: '/service/api/v1/connections/SampleConnection?action=start' }, (res) => {

              if (res.statusCode === 200) {
                const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'POST', path: '/service/api/v1/consumers/SampleConsumer/messages?timeout=1000' }, (res) => {

                  if (res.statusCode === 200) {
                    var body = '';

                    res.on('data', (chunk) => {
                      body += chunk.toString();
                    });

                    res.on('end', () => {
                      console.log(body);
                    });
  
                  }

                });

                req.end();
              }

            });

            req.end();
          }

        });

        req.end();
      }

    });

    req.end();
  }

});

req.end();

Python

W/o Durability

import requests

res = requests.put('https://host/service/api/v1/connections/SampleConnection', auth=('username', 'password'), headers={'X-OC-ID-TOKEN-STATUS':'disabled'})

cookies = dict(res.cookies)

requests.put('https://host/service/api/v1/sessions/SampleSession', auth=('username', 'password'), cookies=cookies, params={'connection':'SampleConnection'})

requests.put('https://host/service/api/v1/consumers/SampleConsumer', auth=('username', 'password'), cookies=cookies, params={'destination':'/topics/SampleTopic', 'session':'SampleSession'})

requests.post('https://host/service/api/v1/connections/SampleConnection', auth=('username', 'password'), cookies=cookies, params={'action':'start'})

res = requests.post('https://host/service/api/v1/consumers/SampleConsumer/messages', auth=('username', 'password'), cookies=cookies, params={'timeout':'1000'})

print(res.text)

W/ Durability

import requests

res = requests.put('https://host/service/api/v1/connections/SampleConnection', auth=('username', 'password'), headers={'X-OC-ID-TOKEN-STATUS':'disabled'}, params={'clientId':'SampleClient'})

cookies = dict(res.cookies)

requests.put('https://host/service/api/v1/sessions/SampleSession', auth=('username', 'password'), cookies=cookies, params={'connection':'SampleConnection'})

requests.put('https://host/service/api/v1/consumers/SampleConsumer', auth=('username', 'password'), cookies=cookies, params={'destination':'/topics/SampleTopic', 'session':'SampleSession', 'subscriptionName':'SampleSubscription'})

requests.post('https://host/service/api/v1/connections/SampleConnection', auth=('username', 'password'), cookies=cookies, params={'action':'start'})

res = requests.post('https://host/service/api/v1/consumers/SampleConsumer/messages', auth=('username', 'password'), cookies=cookies, params={'timeout':'1000'})

print(res.text)

How to Send a Pull Notification to the Oracle Messaging Cloud Service

JAX-RS

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

@WebServlet(name = "SampleOmcsServlet", value = "/")
public final class SampleOmcsServlet extends HttpServlet {

  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) {
    final Client client = ClientBuilder.newClient();

    client.register(HttpAuthenticationFeature.basic("username", "password"));

    final Response res = client.target("https://host/service/api/v1/connections/SampleConnection").request().header("X-OC-ID-TOKEN-STATUS", "disabled").put(Entity.json(""));

    final Cookie jsessionid = res.getCookies().get("JSESSIONID");

    client.target("https://host/service/api/v1/sessions/SampleSession").queryParam("connection", "SampleConnection").request().cookie(jsessionid).put(Entity.json(""));

    client.target("https://host/service/api/v1/producers/SampleProducer").queryParam("destination", "/topics/SampleTopic").queryParam("session", "SampleSession").request().cookie(jsessionid).put(Entity.json(""));

    client.target("https://host/service/api/v1/producers/SampleProducer/messages").request().cookie(jsessionid).post(Entity.json("Simples Assim"));

    client.close();
  }

}

Java

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

import oracle.cloud.messaging.client.MessagingService;
import oracle.cloud.messaging.client.MessagingServiceCredentials;
import oracle.cloud.messaging.client.MessagingServiceFactory;
import oracle.cloud.messaging.client.MessagingServiceNamespace;

public final class OmcsSample {

  public static void main(final String[] args) throws Exception {
    final MessagingServiceFactory serviceFactory = MessagingServiceFactory.getInstance();

    final MessagingService service = serviceFactory.getMessagingService(new MessagingServiceNamespace("uri"), new MessagingServiceCredentials("username", "password"));

    final ConnectionFactory connFactory = service.getConnectionFactory();

    final Connection conn = connFactory.createConnection();

    final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    final Destination dest = sess.createTopic("SampleTopic");

    final MessageProducer prod = sess.createProducer(dest);

    final Message msg = sess.createTextMessage("Simples Assim");

    prod.send(msg);

    conn.close();
  }

}

JavaScript

const req = new XMLHttpRequest();

req.open("PUT", "https://host/service/api/v1/connections/SampleConnection", true, "username", "password");

req.setRequestHeader("X-OC-ID-TOKEN-STATUS", "disabled");

req.onreadystatechange = () => {

  if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
    const req = new XMLHttpRequest();

    req.open("PUT", "https://host/service/api/v1/sessions/SampleSession?connection=SampleConnection");

    req.onreadystatechange = () => {

      if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
        const req = new XMLHttpRequest();

        req.open("PUT", "https://host/service/api/v1/producers/SampleProducer?destination=/topics/SampleTopic&session=SampleSession");

        req.onreadystatechange = () => {

          if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
            const req = new XMLHttpRequest();

            req.open("POST", "https://host/service/api/v1/producers/SampleProducer/messages");

            req.send('Simples Assim');
          }

        };

        req.send();
      }

    };

    req.send();
  }

};

req.send();

Node.js

const https = require('https');

const req = https.request({ auth: 'username:password', headers: { 'X-OC-ID-TOKEN-STATUS': 'disabled' }, hostname: 'host', method: 'PUT', path: '/service/api/v1/connections/SampleConnection' }, (res) => {

  if (res.statusCode === 201) {
    const cookies = res.headers['set-cookie'];

    const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'PUT', path: '/service/api/v1/sessions/SampleSession?connection=SampleConnection' }, (res) => {

      if (res.statusCode === 201) {
        const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'PUT', path: '/service/api/v1/producers/SampleProducer?destination=/topics/SampleTopic&session=SampleSession' }, (res) => {

          if (res.statusCode === 201) {
            const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'POST', path: '/service/api/v1/producers/SampleProducer/messages' });

            req.write('Simples Assim');

            req.end();
          }

        });

        req.end();
      }

    });

    req.end();
  }

});

req.end();

Python

import requests

res = requests.put('https://host/service/api/v1/connections/SampleConnection', auth=('username', 'password'), headers={'X-OC-ID-TOKEN-STATUS':'disabled'})

cookies = dict(res.cookies)

requests.put('https://host/service/api/v1/sessions/SampleSession', auth=('username', 'password'), cookies=cookies, params={'connection':'SampleConnection'})

requests.put('https://host/service/api/v1/producers/SampleProducer', auth=('username', 'password'), cookies=cookies, params={'destination':'/topics/SampleTopic', 'session':'SampleSession'})

requests.post('https://host/service/api/v1/producers/SampleProducer/messages', auth=('username', 'password'), cookies=cookies, data='Simples Assim')

How to Receive a Message from the Oracle Messaging Cloud Service

JAX-RS

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

@WebServlet(name = "SampleOmcsServlet", value = "/")
public final class SampleOmcsServlet extends HttpServlet {

  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    final Client client = ClientBuilder.newClient();

    client.register(HttpAuthenticationFeature.basic("username", "password"));

    Response res = client.target("https://host/service/api/v1/connections/SampleConnection").request().header("X-OC-ID-TOKEN-STATUS", "disabled").put(Entity.json(""));

    final Cookie jsessionid = res.getCookies().get("JSESSIONID");

    client.target("https://host/service/api/v1/sessions/SampleSession").queryParam("connection", "SampleConnection").request().cookie(jsessionid).put(Entity.json(""));

    client.target("https://host/service/api/v1/consumers/SampleConsumer").queryParam("destination", "/queues/SampleQueue").queryParam("session", "SampleSession").request().cookie(str).put(Entity.json(""));

    client.target("https://host/service/api/v1/connections/SampleConnection").queryParam("action", "start").request().cookie(jsessionid).post(Entity.json(""));

    res = client.target("https://host/service/api/v1/consumers/SampleConsumer/messages").queryParam("timeout", 1000).request().cookie(jsessionid).post(Entity.json(""));

    resp.getWriter().println(res.readEntity(String.class));

    client.close();
  }

}

Java

import static java.lang.System.out;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import oracle.cloud.messaging.client.MessagingService;
import oracle.cloud.messaging.client.MessagingServiceCredentials;
import oracle.cloud.messaging.client.MessagingServiceFactory;
import oracle.cloud.messaging.client.MessagingServiceNamespace;

public final class OmcsSample {

  public static void main(final String[] args) throws Exception {
    final MessagingServiceFactory serviceFactory = MessagingServiceFactory.getInstance();

    final MessagingService service = serviceFactory.getMessagingService(new MessagingServiceNamespace("uri"), new MessagingServiceCredentials("username", "password"));

    final ConnectionFactory connFactory = service.getConnectionFactory();

    final Connection conn = connFactory.createConnection();

    final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    final Destination dest = sess.createQueue("SampleQueue");

    final MessageConsumer cons = sess.createConsumer(dest);

    conn.start();

    final Message msg = cons.receive();

    out.println(msg);

    conn.close();
  }

}

JavaScript

const req = new XMLHttpRequest();

req.open("PUT", "https://host/service/api/v1/connections/SampleConnection", true, "username", "password");

req.setRequestHeader("X-OC-ID-TOKEN-STATUS", "disabled");

req.onreadystatechange = () => {

  if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
    const req = new XMLHttpRequest();

    req.open("PUT", "https://host/service/api/v1/sessions/SampleSession?connection=SampleConnection");

    req.onreadystatechange = () => {

      if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
        const req = new XMLHttpRequest();

        req.open("PUT", "https://host/service/api/v1/consumers/SampleConsumer?destination=/queues/SampleQueue&session=SampleSession");

        req.onreadystatechange = () => {

          if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
            const req = new XMLHttpRequest();

            req.open("POST", "https://host/service/api/v1/connections/SampleConnection?action=start");

            req.onreadystatechange = () => {

              if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 200)) {
                const req = new XMLHttpRequest();

                req.open("POST", "https://host/service/api/v1/consumers/SampleConsumer/messages?timeout=1000");

                req.onreadystatechange = () => {

                  if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 200))
                    console.log(req.responseText);

                };

                req.send();
              }

            };

          req.send();
        }

      };

      req.send();
    }

   };

   req.send();
  }

};

req.send();

Node.js

const https = require('https');

const req = https.request({ auth: 'username:password', headers: { 'X-OC-ID-TOKEN-STATUS': 'disabled' }, hostname: 'host', method: 'PUT', path: '/service/api/v1/connections/SampleConnection' }, (res) => {

  if (res.statusCode === 201) {
    const cookies = res.headers['set-cookie'];

    const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'PUT', path: '/service/api/v1/sessions/SampleSession?connection=SampleConnection' }, (res) => {

      if (res.statusCode === 201) {
        const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'PUT', path: '/service/api/v1/consumers/SampleConsumer?destination=/queues/SampleQueue&session=SampleSession' }, (res) => {

          if (res.statusCode === 201) {
            const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'POST', path: '/service/api/v1/connections/SampleConnection?action=start' }, (res) => {

              if (res.statusCode === 200) {
                const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'POST', path: '/service/api/v1/consumers/SampleConsumer/messages?timeout=1000' }, (res) => {

                  if (res.statusCode === 200) {
                    var body = '';

                    res.on('data', (chunk) => {
                      body += chunk.toString();
                    });

                    res.on('end', () => {
                      console.log(body);
                    });

                  }

                });

                req.end();
              }

            });

            req.end();
          }

        });

        req.end();
      }

    });

    req.end();
  }

});

req.end();

Python

import requests

res = requests.put('https://host/service/api/v1/connections/SampleConnection', auth=('username', 'password'), headers={'X-OC-ID-TOKEN-STATUS':'disabled'})

cookies = dict(res.cookies)

requests.put('https://host/service/api/v1/sessions/SampleSession', auth=('username', 'password'), cookies=cookies, params={'connection':'SampleConnection'})

requests.put('https://host/service/api/v1/consumers/SampleConsumer', auth=('username', 'password'), cookies=cookies, params={'destination':'/queues/SampleQueue', 'session':'SampleSession'})

requests.post('https://host/service/api/v1/connections/SampleConnection', auth=('username', 'password'), cookies=cookies, params={'action':'start'})

res = requests.post('https://host/service/api/v1/consumers/SampleConsumer/messages', auth=('username', 'password'), cookies=cookies, params={'timeout':'1000'})

print(res.text)

How to Send a Message to the Oracle Messaging Cloud Service

JAX-RS

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

@WebServlet(name = "SampleOmcsServlet", value = "/")
public final class SampleOmcsServlet extends HttpServlet {

  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) {
    final Client client = ClientBuilder.newClient();

    client.register(HttpAuthenticationFeature.basic("username", "password"));

    final Response res = client.target("https://host/service/api/v1/connections/SampleConnection").request().header("X-OC-ID-TOKEN-STATUS", "disabled").put(Entity.json(""));

    final Cookie jsessionid = res.getCookies().get("JSESSIONID");

    client.target("https://host/service/api/v1/sessions/SampleSession").queryParam("connection", "SampleConnection").request().cookie(jsessionid).put(Entity.json(""));

    client.target("https://host/service/api/v1/producers/SampleProducer").queryParam("destination", "/queues/SampleQueue").queryParam("session", "SampleSession").request().cookie(jsessionid).put(Entity.json(""));

    client.target("https://host/service/api/v1/producers/SampleProducer/messages").request().cookie(jsessionid).post(Entity.json("Simples Assim"));

    client.close();
  }

}

Java

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

import oracle.cloud.messaging.client.MessagingService;
import oracle.cloud.messaging.client.MessagingServiceCredentials;
import oracle.cloud.messaging.client.MessagingServiceFactory;
import oracle.cloud.messaging.client.MessagingServiceNamespace;

public final class OmcsSample {

  public static void main(final String[] args) throws Exception {
    final MessagingServiceFactory serviceFactory = MessagingServiceFactory.getInstance();

    final MessagingService service = serviceFactory.getMessagingService(new MessagingServiceNamespace("uri"), new MessagingServiceCredentials("username", "password"));

    final ConnectionFactory connFactory = service.getConnectionFactory();

    final Connection conn = connFactory.createConnection();

    final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    final Destination dest = sess.createQueue("SampleQueue");

    final MessageProducer prod = sess.createProducer(dest);

    final Message msg = sess.createTextMessage("Simples Assim");

    prod.send(msg);

    conn.close();
  }

}

JavaScript

const req = new XMLHttpRequest();

req.open("PUT", "https://host/service/api/v1/connections/SampleConnection", true, "username", "password");

req.setRequestHeader("X-OC-ID-TOKEN-STATUS", "disabled");

req.onreadystatechange = () => {

  if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
    const req = new XMLHttpRequest();

    req.open("PUT", "https://host/service/api/v1/sessions/SampleSession?connection=SampleConnection");

    req.onreadystatechange = () => {

      if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
        const req = new XMLHttpRequest();

        req.open("PUT", "https://host/service/api/v1/producers/SampleProducer?destination=/queues/SampleQueue&session=SampleSession");

        req.onreadystatechange = () => {

          if ((req.readyState === XMLHttpRequest.DONE) && (req.status === 201)) {
            const req = new XMLHttpRequest();

            req.open("POST", "https://host/service/api/v1/producers/SampleProducer/messages");

            req.send('Simples Assim');
          }

        };

        req.send();
      }

    };

    req.send();
  }

};

req.send();

Node.js

const https = require('https');

const req = https.request({ auth: 'username:password', headers: { 'X-OC-ID-TOKEN-STATUS': 'disabled' }, hostname: 'host', method: 'PUT', path: '/service/api/v1/connections/SampleConnection' }, (res) => {

  if (res.statusCode === 201) {
    const cookies = res.headers['set-cookie'];

    const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'PUT', path: '/service/api/v1/sessions/SampleSession?connection=SampleConnection' }, (res) => {

      if (res.statusCode === 201) {
        const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'PUT', path: '/service/api/v1/producers/SampleProducer?destination=/queues/SampleQueue&session=SampleSession' }, (res) => {

          if (res.statusCode === 201) {
            const req = https.request({ auth: 'username:password', headers: { cookie: cookies }, hostname: 'host', method: 'POST', path: '/service/api/v1/producers/SampleProducer/messages' });

            req.write('Simples Assim');

            req.end();
          }

        });

        req.end();
      }

    });

    req.end();
  }

});

req.end();

Python

import requests

res = requests.put('https://host/service/api/v1/connections/SampleConnection', auth=('username', 'password'), headers={'X-OC-ID-TOKEN-STATUS':'disabled'})

cookies = dict(res.cookies)

requests.put('https://host/service/api/v1/sessions/SampleSession', auth=('username', 'password'), cookies=cookies, params={'connection':'SampleConnection'})

requests.put('https://host/service/api/v1/producers/SampleProducer', auth=('username', 'password'), cookies=cookies, params={'destination':'/queues/SampleQueue', 'session':'SampleSession'})

requests.post('https://host/service/api/v1/producers/SampleProducer/messages', auth=('username', 'password'), cookies=cookies, data='Simples Assim')

How to Receive a Message from OpenStack Zaqar

JAX-RS

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
 
@WebServlet(name = "SampleZaqarServlet", value = "/")
public final class SampleZaqarServlet extends HttpServlet {

  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    final Client client = ClientBuilder.newClient();

    final MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();

    headers.putSingle("Client-ID", ...);

    headers.putSingle("X-Auth-Token", ...);

    headers.putSingle("X-Project-Id", ...);

    final Response res = client.target("http://host:8888/v1.1/queues/SampleQueue/claims").request().headers(headers).post(Entity.json(""));

    resp.getWriter().println(res.readEntity(String.class));
 
    client.close();
  }
 
}

Java API for WebSocket

JsonDecoder.java

import java.io.StringReader;

import javax.json.Json;
import javax.json.JsonObject;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;

public final class JsonDecoder implements Decoder.Text<JsonObject> {

  public JsonObject decode(final String s) {
    return Json.createReader(new StringReader(s)).readObject();
  }

  public void destroy() {
  }

  public void init(final EndpointConfig config) {
  }

  public boolean willDecode(final String s) {
    return true;
  }

}

SampleZaqarEndpoint.java

import static java.lang.System.out;

import java.io.IOException;

import javax.json.JsonObject;
import javax.websocket.ClientEndpoint;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;

@ClientEndpoint(decoders = JsonDecoder.class)
public final class SampleZaqarEndpoint {

  @OnMessage
  public void onMessage(final JsonObject msg) {

    if (msg.getJsonObject("body").getJsonArray("messages") != null)
      out.println(msg.getJsonObject("body").getJsonArray("messages").getJsonObject(0).getString("body"));

  }

  @OnOpen
  public void onOpen(final Session sess) throws IOException {
    final RemoteEndpoint.Basic remote = sess.getBasicRemote();

    remote.sendText("{ \"action\": \"authenticate\", \"headers\": { \"X-Auth-Token\": ..., \"X-Project-ID\": ... } }"); // refer to bug #1553398

    remote.sendText("{ \"action\": \"claim_create\", \"body\": { \"queue_name\": \"SampleQueue\" }, \"headers\": { \"Client-ID\": ..., \"X-Project-ID\": ... } }");
  }

}

SampleZaqarServlet.java

import java.net.URI;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.ContainerProvider;
import javax.websocket.WebSocketContainer;

@WebServlet(name = "SampleZaqarServlet", value = "/")
public final class SampleZaqarServlet extends HttpServlet {

  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) {
    final WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    container.connectToServer(SampleZaqarEndpoint.class, new URI("ws://host:9090"));
  }

}

JavaScript

const ws = new WebSocket('ws://host:9000');

ws.onmessage = (e) => {
  const msg = JSON.parse(e.data);

  if (msg.body.messages)
    console.log(msg.body.messages[0].body);

};

ws.onopen = () => {
  ws.send('{ "action": "authenticate", "headers": { "X-Auth-Token": ..., "X-Project-ID": ... } }'); // refer to bug #1553398

  ws.send('{ "action": "claim_create", "body": { "queue_name": "SampleQueue" }, "headers": { "Client-ID": ..., "X-Project-ID": ... } }');
};

Node.js

const WebSocket = require('ws');

const ws = new WebSocket('ws://host:9000');

ws.on('message', (data, flags) => {
  const msg = JSON.parse(data);
 
  if (msg.body.messages)
    console.log(msg.body.messages[0].body);

});

ws.on('open', () => {
  ws.send('{ "action": "authenticate", "headers": { "X-Auth-Token": ..., "X-Project-ID": ... } }'); // refer to bug #1553398

  ws.send('{ "action": "claim_create", "body": { "queue_name": "SampleQueue" }, "headers": { "Client-ID": ..., "X-Project-ID": ... } }');
});

Python

from zaqarclient.queues.v1 import client

client = client.Client('http://host:8888', conf={ 'auth_opts': { 'options': { 'client_uuid': ..., 'os_auth_token': ..., 'os_auth_url': 'http://host:5000/v3.0/', 'os_project_id': ...}}}, version=1.1)

queue = client.queue('SampleQueue')

claim = queue.claim(ttl=600, grace=600) // refer to bug #1553387

for msg in claim:
  print(msg)

How to Send a Message to OpenStack Zaqar

JAX-RS

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;

@WebServlet(name = "SampleZaqarServlet", value = "/")
public final class SampleZaqarServlet extends HttpServlet {

  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) {
    final Client client = ClientBuilder.newClient();

    final MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();

    headers.putSingle("Client-ID", ...);

    headers.putSingle("X-Auth-Token", ...);

    headers.putSingle("X-Project-Id", ...);

    client.target("http://host:8888/v1.1/queues/SampleQueue/messages").request(MediaType.APPLICATION_JSON_TYPE).headers(headers).post(Entity.json("{\"messages\":[{\"body\":\"Simples Assim\"}]}"));

    client.close();
  }
 
}

Java API for WebSocket

SampleZaqarEndpoint.java

import java.io.IOException;

import javax.websocket.ClientEndpoint;
import javax.websocket.OnOpen;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;

@ClientEndpoint
public final class SampleZaqarEndpoint {

  @OnOpen
  public void onOpen(final Session sess) throws IOException {
    final RemoteEndpoint.Basic remote = sess.getBasicRemote();

    remote.sendText("{ \"action\": \"authenticate\", \"headers\": { \"X-Auth-Token\": ..., \"X-Project-ID\": ... } }"); // refer to bug #1553398

    remote.sendText("{ \"action\": \"message_post\", \"body\": { \"messages\": [ { \"body\": \"Simples Assim\" } ], \"queue_name\": \"SampleQueue\" }, \"headers\": { \"Client-ID\": ..., \"X-Project-ID\": ... } }");
  }

}

SampleZaqarServlet.java

import java.net.URI;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.ContainerProvider;
import javax.websocket.WebSocketContainer;

@WebServlet(name = "SampleZaqarServlet", value = "/")
public final class SampleZaqarServlet extends HttpServlet {

  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) {
    final WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    container.connectToServer(SampleZaqarEndpoint.class, new URI("ws://host:9090"));
  }

}

JavaScript

const ws = new WebSocket('ws://host:9000');
 
ws.onopen = () => {
  ws.send('{ "action": "authenticate", "headers": {"X-Auth-Token": ..., "X-Project-ID": ... } }'); // refer to bug #1553398

  ws.send('{ "action": "message_post", "body": { "messages": [ { "body": "Simples Assim" } ], "queue_name": "SampleQueue" }, "headers": { "Client-ID": ..., "X-Project-ID": ... } }');
};

Node.js

const WebSocket = require('ws');

const ws = new WebSocket('ws://host:9000');

ws.on('open', () => {
  ws.send('{ "action": "authenticate", "headers": { "X-Auth-Token": ..., "X-Project-ID": ... } }'); // refer to bug #1553398
 
  ws.send('{ "action": "message_post", "body": { "messages": [ { "body": "Simples Assim" } ], "queue_name": "SampleQueue" }, "headers": { "Client-ID": ..., "X-Project-ID": ... } }');
});

Python

from zaqarclient.queues.v1 import client

client = client.Client('http://host:8888', conf={ 'auth_opts': { 'options': { 'client_uuid': ..., 'os_auth_token': ..., 'os_auth_url': 'http://host:5000/v3.0/', 'os_project_id': ... } } }, version=1.1)

queue = client.queue('SampleQueue')

queue.post([ { 'body': 'Simples Assim' } ])

How to Update an Entry with the Infinispan REST API

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

@SuppressWarnings("serial")
@WebServlet(name = "SampleInfinispanServlet", value = "/")
public final class SampleInfinispanServlet extends HttpServlet {

  @Override
  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) {
    final Client client = ClientBuilder.newClient();

    client.register(HttpAuthenticationFeature.basic("username", "password"));

    final Entity entity = ...

    client.target("http://localhost:8080/rest/samplecache/samplekey").request().post(entity);

    client.close();
  }

}