IBM Support

REST API Client - upload message to Sterling B2B Integrator Mailbox

Technical Blog Post


Abstract

REST API Client - upload message to Sterling B2B Integrator Mailbox

Body

You may have requirement for your business to automate file uploads to SB2Bi/SFG Mailbox. It is possible through programmatic approach by using REST APIs offered in 526x fixpacks. In this blog, I provided a sample java class that takes location of a file and adds it to SB2Bi mailbox.

I had covered such program in one of blogs in past for different requirement. Please refer to it for outline and dependency jars - REST API Proof Of Concept - Automate Sterling FileGateway Community and Trading Partner creation

 

As you see in API documentation for "Create Mailbox Message", it requires "documentId" instead of actual payload. That means, we need to generate documentId with "Create Document" API. So this is 2 step process. Pasted API doc references below. (http://host:port/B2BAPIs/svc/doc)

image

image

Here is the java class that actually does job for us. variables highlighted in blue Italic are just place holders. You may replace them as necessary.

 

import java.io.IOException;
import java.net.URISyntaxException;
import java.io.*;
import com.ibm.misc.BASE64Encoder;

 

import org.apache.http.client.methods.HttpPost;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.entity.StringEntity;

 

import net.sf.json.JSONSerializer;
import net.sf.json.JSONObject;

 

public class MailboxAddClient {            
                    
        public static void main(String[] args) {
            final String DOC_URL = "http://1.1.1.1:10074/B2BAPIs/svc/documents";
            final String MBX_URL = "http://1.1.1.1:10074/B2BAPIs/svc/mailboxmessages/";

            final String MBX_PATH = "/KKIn";
            final String FILE_PATH="/home/kkonda/index.html";
            final String MESSAGE_NAME = "NewIndex.html";

            final String authentication = "admin:password";

            try {
                    System.out.println("Initiating REST API call for Document Creation");
                    String documentID = new MailboxAddClient().createDocument(DOC_URL, authentication, FILE_PATH);
                    if(documentID == null) System.exit(-1);
                    
                    System.out.println("Posting to mailbox through REST API call..");
                    new MailboxAddClient().addMessageToMailBox(MBX_URL, authentication, documentID, MBX_PATH, MESSAGE_NAME);
                    System.out.println("Upload successful!");
            } catch (IOException e) {
                e.printStackTrace(System.out);
            } catch (Exception e) {
                e.printStackTrace(System.out);
            }
        }
        
        public String createDocument(String URL, String authentication, String filePath) throws Exception{
            CloseableHttpResponse response = null;
            String encAuth = new BASE64Encoder().encode(new String(authentication).getBytes());
            //This will store the id of the document we're going to create
            String documentId = null;
            
            CloseableHttpClient httpclient = HttpClients.createDefault();
            
            //Create JSON request body
            JSONObject docJson = new JSONObject();
            String payload = new BASE64Encoder().encode(getPayload(filePath).getBytes());
            docJson.put("payload",payload);
            String docJsonString = docJson.toString();

 

            try {
                //Create and make request
                HttpRequestBase request = createPostRequest(URL, encAuth, docJsonString);
                response = httpclient.execute(request);

                //Parse created document id out of response JSON
                HttpEntity entity = response.getEntity();
                int retCode = response.getStatusLine().getStatusCode();
            
                System.out.println("retCode : "+ retCode);
    
                if(retCode==200 || retCode==201 || retCode==202){
                    
                    String responseString = convertResponseToString(entity);
                    System.out.println("responseString : " + responseString);
                    JSONObject json = (JSONObject)JSONSerializer.toJSON(responseString);

                    //Get created Location element from JSON
                    String jsonLocation = (String) json.get("Location");

                    //Split the location and grab the last entry, the document id
                    String[] jsonLocationSplit = jsonLocation.split("/");
                    documentId = jsonLocationSplit[jsonLocationSplit.length-1];
                    
                    System.out.println("Created document id: " + documentId);
                }else{

                    throw new IOException("HTTP POST Request for createDocument failed: " + retCode);  
                }


            } catch (IOException e) {
                throw new Exception("HTTP POST Request for CreateDocument failed: " + e);
            } finally { //Must close response
                if(response!=null)
                    response.close();
            }
            return documentId;
        }


        private String getPayload(String filePath) throws FileNotFoundException, IOException {

            BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath))));
            String s,fileContent = "";
            while((s=r.readLine())!=null)
                fileContent +=s;
            
            System.out.println("Payload : " + filePath + " size : " + fileContent.length());
            return fileContent;
        }    
        
        public boolean addMessageToMailBox(String URL,String authentication,String documentID,String mailBoxPath,String msgName) throws Exception{
            
            String encAuth = new BASE64Encoder().encode(new String(authentication).getBytes());
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            //
            // Create Message
            //
            //Create JSON request body
            JSONObject msgJson = new JSONObject();
            msgJson.put("documentId", documentID);
            msgJson.put("extractableCount", 3);
            msgJson.put("mailboxPath", mailBoxPath);
            msgJson.put("name", msgName);
            String msgJsonString = msgJson.toString();
            System.out.println("msgJsonString : " + msgJsonString);
            try {
                //Create and make request
                HttpRequestBase request = createPostRequest(URL, encAuth, msgJsonString);
                response = httpclient.execute(request);
                HttpEntity entity = response.getEntity();
                int retCode = response.getStatusLine().getStatusCode();
                
                if(retCode==200 || retCode==201 || retCode==202){
                    String responseString = convertResponseToString(entity);
                    System.out.println(responseString);
                    return true;
                    
                }else{
                    throw new Exception("HTTP POST Request for Creating Mailbox Message failed: " + retCode);
                }  
                
            } catch (IOException e) {
                //e.printStackTrace();
                throw new Exception("HTTP POST Request for Creating Mailbox Message failed: " + e);
            } finally { //Must close response
                if(response!=null)
                    response.close();
            }
        }

 

        private static HttpRequestBase createPostRequest(String URL, String encAuth, String jsonString) throws UnsupportedEncodingException, URISyntaxException {
            HttpRequestBase httpRequest = null;
            httpRequest = new HttpPost(URL + "/");
            ((HttpPost) httpRequest).setEntity(new StringEntity(jsonString));
            httpRequest.addHeader("Authorization", "Basic " + encAuth);
            httpRequest.addHeader("content-type", "application/json");
            httpRequest.addHeader("Accept","application/json");
            return httpRequest;
        }
        
        private String convertResponseToString(HttpEntity entity) throws IOException{
             ByteArrayOutputStream os = new ByteArrayOutputStream();
             entity.writeTo(os);
             String jsonResponse = new String(os.toByteArray());
             return jsonResponse;
    }
}

 

-- Execute

sb2bi_install/jdk/bin/java -classpath .:commons-beanutils.jar:commons-codec-1.3.jar:commons-logging.jar:commons-lang-2.1.jar:ezmorph-1.0.4.jar:commons-collections-3.2.2.jar:httpclient-4.5.1.jar:httpcore-4.4.3.jar:json-lib-2.3-jdk15.jar MailboxAddClient

--Output from class execution

image

 

 

screenshot from dashboard Message Management - File was uploaded with message ID of 730.

image

 

Feel free to add a note with your questions.

 

PS - This client class is presented here as a sample so that it throws an idea. You may not want to use/plugin class as is. Instead you may want to enhance this such a way it can be easy-to-manage as you make more changes.

 

[{"Business Unit":{"code":"BU059","label":"IBM Software w\/o TPS"},"Product":{"code":"SS3JSW","label":"IBM Sterling B2B Integrator"},"Component":"","Platform":[{"code":"PF025","label":"Platform Independent"}],"Version":"","Edition":"","Line of Business":{"code":"LOB59","label":"Sustainability Software"}}]

UID

ibm11120923