IBM Support

REST API Proof Of Concept - Automate Sterling FileGateway Community and Trading Partner creation

Technical Blog Post


Abstract

REST API Proof Of Concept - Automate Sterling FileGateway Community and Trading Partner creation

Body

            I am going to present a REST client, written using Apache HTTP Client, that trigger SB2Bi/SFG REST API calls to create Community and Trading Partner. As I have noticed users trying to create these SFG resources through direct Database SQL inserts and/or XAPI service calls but often used to end up in errors or lead to inconsistent partner accounts. I am targeting this article for those customers and hoping this would help all such customers in simplifying resource creation with less of efforts.

            While REST APIs introduced very first time in Sterling Integrator and Sterling FileGateway through 5.2.6.1 fixpack, these capabilities were expanded in recently released 5.2.6.2 fixpack.

Product Documentation : Introduction to using B2Bi REST APIs

 

API additions in SB2BI 5.2.6.2 / SFG 2.2.6.2

1. Community Services - Services to create, read, update, and delete Communities in Sterling File Gateway.
2. Partner Group Services - Services to create, read, update, and delete partner groups.
3. Virtual Root Services - Services to create, read, and delete virtual root mailboxes.
4. Document Services - More APIs added.
5. Trading Partner APIs - More APIs added.

Full list of B2B REST APIs available in SB2Bi/SFG

 

As we all aware typical REST APIs need input parameters as JSON object and this request object varies from one API to other. I would obtain structure of respective JSON object from B2BAPIs UI. (http://host:LIBERTY_HTTP_PORT/B2BAPIs/svc).

Screen below, just for reference, shows JSON request for Create Community POST API. As you see, for this Community, I checked all check boxes except 2 and respective JSON attributes shown true vs false. I would use this kind of JSON body while invoking REST API call in my REST client class.

image

Following is REST Client interacts with B2B REST APIs creating Community and Partner inside Community. I put inline documentation within code to make it self explanatory.
 

//CommunityPartnerAPIs.java

import java.io.IOException;
import java.net.URISyntaxException;
import java.io.*;

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

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

import com.ibm.misc.BASE64Encoder;
import com.ibm.xtq.xslt.xylem.instructions.nodeconstructors.CreateDocumentFragmentInstruction;

public class CommunityPartnerAPIs {
        
        /* Initialize environment Information as required*/
        private static final String PROTO="http://";
        private static final String HOST="1.1.1.1";
        private static final String PORT="5040";
        private static final String authentication = "user:password";    

        public static void main(String[] args) throws Exception{
            
            String COMM_URL = PROTO + HOST + ":" + PORT + "/B2BAPIs/svc/communities/";
            String PART_URL = PROTO + HOST + ":" + PORT + "/B2BAPIs/svc/tradingpartners/";
            
            /* Encode login/password using Base64Encoder as required by HTTP header*/
            String auth = (new BASE64Encoder()).encode(new String(authentication).getBytes());
            try {
                System.out.println("API call to create Community");
                String status = createCommunity(COMM_URL,auth);
                
                /* Proceed to create partner only if Community was created successfully*/
                if(status!=null && !"created".equalsIgnoreCase(status.trim())) {
                    System.exit(-1);
                }
                System.out.println("Community was created successfully. Now API call to create Partner");
                createPartner(PART_URL,auth);
                
                System.out.println("\nCompleted!");
            } catch (IOException e) {
                e.printStackTrace(System.out);
            } catch (Exception e) {
                e.printStackTrace(System.out);
            }
        }
        
        public static String createCommunity(String URL, String auth) throws Exception{
            CloseableHttpResponse response = null;
            
            CloseableHttpClient httpclient = HttpClients.createDefault();
            
            //Create JSON request body
            JSONObject commJson = new JSONObject();

            /* JSON attributes for Community. Please refer to screen-shot captured from B2BAPIs UI
                {
                  "cdListening": true,
                  "ftpListening": true,
                  "name": "REST_UI_Community",
                  "partnerNotificationsEnabled": true,
                  "partnersInitiateConnections": false,
                  "partnersListenForConnections": true,
                  "sshListening": false,
                  "wsListening": true
                }
            */

            
            /* Prepare a JSON request object with input values */
            commJson.put("cdListening",true);
            commJson.put("ftpListening",true);
            commJson.put("name","REST_API_Community");
            commJson.put("partnerNotificationsEnabled",true);
            commJson.put("partnersInitiateConnections",false);
            commJson.put("partnersListenForConnections",true);
            commJson.put("sshListening",false);
            commJson.put("wsListening",true);
            String commJsonString = commJson.toString();

            System.out.println("commJsonString looks like this : " + commJsonString);
            try {
                //Create and make request
                HttpRequestBase request = prepareAPIRequest("POST", URL, auth, commJsonString);
                System.out.println("Executing REST API call to Create Community");
                response = httpclient.execute(request);
                
                int retCode = response.getStatusLine().getStatusCode();
                System.out.println("Response return code : "+ retCode);

                String retPhrase = response.getStatusLine().getReasonPhrase();
                System.out.println("Response Phrase : " + retPhrase);

                //Parse API response to derive community location
                HttpEntity entity = response.getEntity();
                String responseString = parseResponseToString(entity);
                System.out.println("Response String : " + responseString);
                JSONObject json = (JSONObject)JSONSerializer.toJSON(responseString);                    

                return retPhrase;                    
            } catch (IOException e) {
                throw new Exception("HTTP POST for createCommunity failed: " + e);
            } finally { //Must close response
                if(response!=null)
                    response.close();
            }
        }
        
        public static void createPartner(String URL, String auth) throws Exception{
            
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;

            //Create JSON request body. Obtained JSON structure for Create Trading Partner from B2BAPIs UI
            JSONObject partnerJson = new JSONObject();
            partnerJson.put("authenticationType", "Local");
            partnerJson.put("community", "REST_API_Community");
            partnerJson.put("emailAddress", "kk@ibm.com");
            partnerJson.put("givenName", "Demo");
            partnerJson.put("isInitiatingConsumer", false);
            partnerJson.put("isInitiatingProducer", true);
            partnerJson.put("isListeningConsumer", false);
            partnerJson.put("isListeningProducer", false);
            partnerJson.put("doesUseSSH", false);
            partnerJson.put("partnerName", "REST_API_Partner");
            partnerJson.put("password", "password");
            partnerJson.put("phone","1234567891");
            partnerJson.put("postalCode", "12345");
            partnerJson.put("surname", "Partner");
            partnerJson.put("username", "demopartner");

            String partnerJsonString = partnerJson.toString();
            System.out.println("partnerJsonString looks like this : " + partnerJsonString);

            try {
                //Generate API request
                HttpRequestBase request = prepareAPIRequest("POST", URL, auth, partnerJsonString);
                
                System.out.println("Executing REST API call to create Trading Partner");
                response = httpclient.execute(request);
                HttpEntity entity = response.getEntity();
                
                // Get status and phrase from APi response
                int retCode = response.getStatusLine().getStatusCode();
                System.out.println("HTTP Response: " + retCode);

                String retPhrase = response.getStatusLine().getReasonPhrase();
                System.out.println("Response Phrase : " + retPhrase);

                String responseString = parseResponseToString(entity);
                System.out.println("responseString " + responseString);
                    
            } catch (IOException e) {
                //e.printStackTrace();
                throw new Exception("HTTP POST Request for Creating SFG Trading Partner failed: " + e);
            } finally { //Must close response
                if(response!=null)
                    response.close();
            }
        }

        public static HttpRequestBase prepareAPIRequest(String type, String URL, String credentials, String jsonString) throws UnsupportedEncodingException, URISyntaxException {
                HttpRequestBase httpRequest = null;
            if(!type.equalsIgnoreCase("POST")) {
                System.out.println("Oops! Not Implemented for " + type);
                System.exit(-1);
            }
            httpRequest = new HttpPost(URL);
            ((HttpPost) httpRequest).setEntity(new StringEntity(jsonString));
            httpRequest.addHeader("Authorization", "Basic " + credentials);
            httpRequest.addHeader("content-type", "application/json");
            httpRequest.addHeader("Accept","application/json");
            return httpRequest;
        }

        public static String parseResponseToString(HttpEntity entity) throws IOException{
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            entity.writeTo(os);
            String jsonResponse = new String(os.toByteArray());
            return jsonResponse;
        }

}

 

I needed 9 jars to compile and execute this class. While 6 of them part of SB2Bi install, other 3 needs to downloaded from Java and Apache web-sites.

  1. sb2bi_install/jar/commons_beanutils/1_6_1/commons-beanutils.jar
  2. sb2bi_install/commons_codec/1_3/commons-codec-1.3.jar
  3. sb2bi_install/jar/commons_logging/1_0_4/commons-logging.jar
  4. sb2bi_install/jar/commons_lang/2_1/commons-lang-2.1.jar
  5. sb2bi_install/jar/ezmorph/1_0_4/ezmorph-1.0.4.jar
  6. sb2bi_installinstall/jar/commons_collections/3_2_2/commons-collections-3.2.2.jar
  7. httpclient-4.5.1.jar (http://archive.apache.org/dist/httpcomponents/)
  8. httpcore-4.4.3.jar (http://archive.apache.org/dist/httpcomponents/)
  9. json-lib-2.3-jdk15.jar (http://www.java2s.com/Code/Jar/j/Downloadjsonlib23jdk15jar.htm)

-- Compile

sb2bi_install/jdk/bin/javac -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 CommunityPartnerAPIs.java

-- 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 CommunityPartnerAPIs

--Output from class execution

image

 

You should see both Community and Partner in filegateway dashboard as below.

image

It is just for POC purpose and is limited to POST (Create) operation. But similar client is possible for any SB2Bi/SFG REST API and any supported operation such as /POST/PUT/DELETE/GET.

Thanks for reading through. You may post your questions, comments, feedback under comments section below.

 

[{"Business Unit":{"code":"BU012","label":"WCE"}, "Product":{"code":"SSMHNK","label":"IBM Sterling B2B Integrator"},"Component":"","Platform":[{"code":"PF025","label":"Platform Independent"}],"Version":"","Edition":""}]

UID

ibm11121469