Virtuoso System Documentation
version 1.1.1 - 2 April 2018
Contents
Virtuoso Documentation - Properties
Web Services

The Virtuoso REST API allows you to send and receive messages.

Since the API is based on REST principles, it's very easy to write and test applications. You can use your browser to access URLs, and you can use pretty much any HTTP client in any programming language to interact with the Virtuoso REST API.

To send a message to Virtuoso365 you need your credentials and the User Channel Configuration Id (UccId). THe UccId is the unique id that idenifies your channel. The UccId is shown for each channel in the Virtuoso365 console:

Java Code snippets

The example java code to send a message is:

              
    public void sendMessage(byte[] payload, int uccId) throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			httpclient.getCredentialsProvider().setCredentials(
					new AuthScope(AuthScope.ANY_HOST, portInt,
							AuthScope.ANY_REALM),
					new UsernamePasswordCredentials(virtuosoUserName,
							virtuosoPassword));

			// String qName = URLEncoder.encode(queueName, "UTF-8");
			String httpStr = "http://" + hostStr + ":" + portInt
					+ "/virtuoso-message-broker/message/send/" + uccId;
			HttpPost http = new HttpPost(httpStr);
			ByteArrayEntity bae = new ByteArrayEntity(payload);
			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);

			http.setEntity(bae);

			HttpResponse response = httpclient.execute(http);
			HttpEntity respEntity = response.getEntity();

			EntityUtils.consume(respEntity);
			// System.out.println("The response Code is " +
			// response.getStatusLine().getStatusCode());

		} catch (Exception e) {

			logger.error(e.getMessage());
			throw new Exception(e);

		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpclient.getConnectionManager().shutdown();
		}
	}
      
       
         

The example jave code to get or receive a message is :

            
    
    /**
 	public VirtuosoMessage getMessage(long uccId, String userName, String password) throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		VirtuosoMessage vm = null;
        try {
			
       
        
            httpclient.getCredentialsProvider().setCredentials(
					new AuthScope("", ),
					new UsernamePasswordCredentials(userName, password));
			HttpGet http = new HttpGet(
					"http:///virtuoso-message-broker/message/retrieve/" +uccId);
			HttpResponse response = httpclient.execute(http);
			HttpEntity entity = response.getEntity();
				if (entity != null) {
				logger.debug("Response content length: "
						+ entity.getContentLength());
			}
			if(response.getStatusLine().getStatusCode()==200) {
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			String line = "";
			StringBuffer buff = new StringBuffer();
			while ((line = rd.readLine()) != null) {
				buff.append(line);
			}

		
			
			ObjectMapper mapper = new ObjectMapper();
			JsonFactory factory = mapper.getJsonFactory();
			JsonParser jp = factory.createJsonParser(buff.toString());
			JsonNode obj = jp.readValueAsTree();

			 vm = mapper.readValue(obj.toString(),
					new TypeReference() {
					});
			
			logger.debug(new String(vm.getPayload(), "UTF8"));
			}
			else {
				logger.debug("No waiting  Messages in Channel");
			}
			EntityUtils.consume(entity);
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpclient.getConnectionManager().shutdown();
		}
        
        return vm;
	}

	

        
        
    public class VirtuosoMessage implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 8208577046312245031L;
	private Long guId;
	private Integer channelId;
	private Long uccId;
	private String channelName;
	private byte[] payload;   //raw initial payload
	private String originatingSender;
	private String queueName;
	private Integer messageStatus;
	private String messageStatusDescription;
	private Timestamp timestamp;
	private String processPoint; //classname or queuename updated by each process point the message is sent to - used by the message process flow to write to database
	private String errorMessageText; //should an error occure not persisted in message only errorMessage
	private Long originatingUserId;
	private String introspectReference;  //user defined value set via userChannelConfiguration
    private byte[] payloadProcessed; //payload in despatcher (INBOUND) queue
	private String errorFolderLocation;
    private String notifierEmailName;
    private boolean persistMessage; //true if message is to be  persisted
    
	public boolean isPersistMessage() {
		return persistMessage;
	}
	public void setPersistMessage(boolean persistMessage) {
		this.persistMessage = persistMessage;
	}
	public static final int MESSAGE_RECEIVED = 1;
	public static final int MESSAGE_PROCESSED = 2;
	public static final int MESSAGE_DELIVERED = 3;
	public static final int MESSAGE_ACKNOWLEDGED=4;
	public static final int MESSAGE_ERROR_PENDING=5;
	public static final int MESSAGE_ERROR_FINALISED=6;
	
	
	/**
	 * @return the errorFolderLocation
	 */
	public String getErrorFolderLocation() {
		return errorFolderLocation;
	}
	/**
	 * @param errorFolderLocation the errorFolderLocation to set
	 */
	public void setErrorFolderLocation(String errorFolderLocation) {
		this.errorFolderLocation = errorFolderLocation;
	}
	/**
	 * @return the payloadProcessed
	 */
	public byte[] getPayloadProcessed() {
		return payloadProcessed;
	}
	/**
	 * @param payloadProcessed the payloadProcessed to set
	 */
	public void setPayloadProcessed(byte[] payloadProcessed) {
		this.payloadProcessed = payloadProcessed;
	}
	/**
	 * @return the messageStatusDescription
	 */
	public String getMessageStatusDescription() {
		return messageStatusDescription;
	}
	/**
	 * @param messageStatusDescription the messageStatusDescription to set
	 */
	public void setMessageStatusDescription(String messageStatusDescription) {
		this.messageStatusDescription = messageStatusDescription;
	}
	/**
	 * @return the uccId
	 */
	public Long getUccId() {
		return uccId;
	}
	/**
	 * @param uccId the uccId to set
	 */
	public void setUccId(Long uccId) {
		this.uccId = uccId;
	}
	/**
	 * @return the introspectReference
	 */
	public String getIntrospectReference() {
		return introspectReference;
	}
	/**
	 * @param introspectReference the introspectReference to set
	 */
	public void setIntrospectReference(String introspectReference) {
		this.introspectReference = introspectReference;
	}
	/**
	 * @return the serialversionuid
	 */
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	/**
	 * @return the guId
	 */
	public Long getGuId() {
		return guId;
	}
	/**
	 * @param guId the guId to set
	 */
	public void setGuId(Long guId) {
		this.guId = guId;
	}
	/**
	 * @return the channelId
	 */
	public Integer getChannelId() {
		return channelId;
	}
	/**
	 * @param channelId the channelId to set
	 */
	public void setChannelId(Integer channelId) {
		this.channelId = channelId;
	}
	/**
	 * @return the messageStatus
	 */
	public Integer getMessageStatus() {
		return messageStatus;
	}
	/**
	 * @param messageStatus the messageStatus to set
	 */
	public void setMessageStatus(Integer messageStatus) {
		this.messageStatus = messageStatus;
	}
	public String getQueueName() {
		return queueName;
	}
	public void setQueueName(String queueName) {
		this.queueName = queueName;
	}
	public String getChannelName() {
		return channelName;
	}
	public void setChannelName(String channelName) {
		this.channelName = channelName;
	}
	public byte[] getPayload() {
		return payload;
	}
	public void setPayload(byte[] payload) {
		this.payload = payload;
	}
	public String getOriginatingSender() {
		return originatingSender;
	}
	public void setOriginatingSender(String originatingSender) {
		this.originatingSender = originatingSender;
	}
	/**
	 * @return the timestamp
	 */
	public Timestamp getTimestamp() {
		return timestamp;
	}
	/**
	 * @param timestamp the timestamp to set
	 */
	public void setTimestamp(Timestamp timestamp) {
		this.timestamp = timestamp;
	}
	/**
	 * @return the processPoint
	 */
	public String getProcessPoint() {
		return processPoint;
	}
	/**
	 * @param processPoint the processPoint to set
	 */
	public void setProcessPoint(String processPoint) {
		this.processPoint = processPoint;
	}
	/**
	 * @return the errorMessageText
	 */
	public String getErrorMessageText() {
		return errorMessageText;
	}
	/**
	 * @param errorMessageText the errorMessageText to set
	 */
	public void setErrorMessageText(String errorMessageText) {
		this.errorMessageText = errorMessageText;
	}
	/**
	 * @return the originatingUserId
	 */
	public Long getOriginatingUserId() {
		return originatingUserId;
	}
	/**
	 * @param originatingUserId the originatingUserId to set
	 */
	public void setOriginatingUserId(Long originatingUserId) {
		this.originatingUserId = originatingUserId;
	}
	public String getNotifierEmailName() {
		return notifierEmailName;
	}
	public void setNotifierEmailName(String notifierEmailName) {
		this.notifierEmailName = notifierEmailName;
	}
	
	

}
        
    
    
     
                
     

Microsoft C# Code snippets

The example C# code is

            
        
     async public static Task sendMessage(string userName, string password, string baseUrl, byte[] message, long uccId) 
  {
      String url = baseUrl + "/virtuoso-message-broker/message/send/" + uccId;
   
      int statusCode = 0;

      // var content = syncClient.UploadString(baseUrl, "");
      using (var client = new HttpClient())
      {
          var byteArray = Encoding.ASCII.GetBytes(userName + ":" + password);
          var header = new System.Net.Http.Headers.AuthenticationHeaderValue(
                     "Basic", Convert.ToBase64String(byteArray));
          client.DefaultRequestHeaders.Authorization = header;

          try
          {
              System.Net.Http.ByteArrayContent byteContent = new ByteArrayContent(message);
              HttpResponseMessage response = await client.PostAsync(url, byteContent); 
              Console.WriteLine(response.StatusCode);
              statusCode = (int) response.StatusCode;
              response.EnsureSuccessStatusCode();
          }
          catch (Exception e)
          {
              // throw new Exception(statusCode.ToString());
               return statusCode;
          }
      }

      return statusCode;
  }

  
        

                

The example c# code to get a message is:

             

  public static VirtuosoMessage getMessage(string userName, string password, string baseUrl, long uccId)
  {
      String url = baseUrl + "/virtuoso-message-broker/message/retrieve/" + uccId;
   
     var syncClient = new WebClient
      {
          Credentials = new NetworkCredential(userName,password),
      };

     // var content = syncClient.UploadString(baseUrl, "");
      byte[] content = null;
      try
      {
          content = syncClient.DownloadData(url);
      }
      catch(Exception e) {
          throw e;
      }
            
      DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(VirtuosoMessage));
      VirtuosoMessage retVal = null;

    if (content.Length>0)
    {
        retVal = new VirtuosoMessage();
        using (var ms = new MemoryStream(content))
        {
            // deserialize the JSON object using the WeatherData type.
            retVal = (VirtuosoMessage)serializer.ReadObject(ms);
        }
        retVal.payloadBytes = Convert.FromBase64String(retVal.payload);
      //  Console.WriteLine(System.Text.Encoding.UTF8.GetString(retVal.payloadBytes));
    }
   

      return retVal;
  }

  }


    }
            
            
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;

namespace VirtuosoCommonAPI
{

    [DataContract]
    public class VirtuosoMessage
    {
    [DataMember]
   public long guId { get; set; }
        [DataMember]
   public int? channelId { get; set; }
  [DataMember]
        public long uccId { get; set; }
   [DataMember]
        public string payload { get; set; }   //raw initial payload

   public byte[] payloadBytes { get; set; }
   [DataMember]
        public string originatingSender { get; set; }
   [DataMember]
        public string queueName { get; set; }
   [DataMember]
        public int? messageStatus { get; set; }
   [DataMember]
        public string errorFolderLocation { get; set; }
   [DataMember]
        public string notifierEmailName { get; set; }
    
	public  const int MESSAGE_RECEIVED = 1;
    public  const int MESSAGE_PROCESSED = 2;
    public const int MESSAGE_DELIVERED = 3;
    public  const int MESSAGE_ACKNOWLEDGED = 4;
    public  const int MESSAGE_ERROR_PENDING = 5;
    public  const int MESSAGE_ERROR_FINALISED = 6;
    }

}

            
            
        

                

Python Code snippets

The example python code to send a message is:

              

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 12 22:06:43 2018

@author: ray
"""
import sys
import httplib2
import urllib


def sendMessage(msg):
    
    http = httplib2.Http()

    http.add_credentials(user, passwd) 
    
    headers = {'Content-Type': 'application/atom+xml'}
    uccId='20'
    resp,content = http.request("http://ec2-34-216-201-219.us-west-2.compute.amazonaws.com:8080/virtuoso-message-broker/message/send/" + uccId,
                        body=urllib.toBytes(msg),
                        method="POST",
                       headers=headers)
    return content 



bodyText = 'this is a test'
user = 'Daniel'
passwd = 'dan'
count=0
for arg in sys.argv:
    if count>0: 
       bodyText +=  arg + " "
    count = count + 1
 




     
        

                

The example python code to get a message is:

             

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 12 21:06:11 2018
@author: ray
"""
import requests
import base64
from requests.auth import HTTPBasicAuth
 
user = 'Daniel'
passwd = 'dan'
uccId = '2'
content = requests.get("http://ec2-34-216-201-219.us-west-2.compute.amazonaws.com:8080/virtuoso-message-broker/message/retrieve/" + uccId, auth=HTTPBasicAuth(user,passwd)) 

try:
 data = content.json()
 #print data["guId"]
 print base64.b64decode(data["payload"])

except:
 print "No Message in Queue"    
    



                

Copyright © 2014-2018 Virtuoso365 B2BFusion Ltd