Purchases


 

In this article we discuss some examples for API interaction. It should be noted that these are indeed examples and not production-grade code

Uploading Purchases

Language: Java
This example shows two different ways of interacting with the API through JAVA. One using a simple ByteOutputStream to write SOAP messages to, and one using JAVA's built-in SOAP capabilities. The code consists of three main classes:

  • Example2.java - The main class. The entry point to the application, where the logic of what we are doing is defined.
  • WSInteraction.java - The class dealing with interaction with the web service. It's used as a utility class by Example2.
  • Purchase.java - A simple class representing a Purchase object with all it's properties. Omitted here for the sake of brevity.

WSInteraction.java

package examples;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;

public class WSInteraction {

    private String currentSession ="";
    private String email = "defaultUser";
    private String pass = "defaultPass";
    private String wsURL = "https://api.billing.inter8.co/V1_0.svc";

    public WSInteraction() {
    }

    public WSInteraction(String wsUrl, String email, String password){
        this.wsURL = wsUrl;
        this.email = email;
        this.pass = password;
    }

    public WSInteraction(String email, String password) {
        this.email = email;
        this.pass = password;
    }

    public void uploadPurchases(ArrayList<Purchase> toUpload){
        if(currentSession.equals("")){
            login();
        }
        OutputStream out = null;
        HttpsURLConnection httpConn = null;
        URLConnection connection = null;
        try {
            String responseString = "";
            String outputString = "";
            URL url = new URL(wsURL);
            connection = url.openConnection();
            httpConn = (HttpsURLConnection)connection;
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            String xmlInput =
            "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
            "  <Header>\n" +
            "    <s:String xmlns:s=\"System\">"+currentSession+"</s:String>\n" +
            "  </Header>\n" +
            "  <Body>\n" +
            "    <UploadPurchases  xmlns=\"http://tempuri.org/\">\n" + 
            "      <purchases>\n";
            for(Purchase p : toUpload){
                xmlInput +=
                    "        <Purchase xmlns=\"http://schemas.datacontract.org/2004/07/Kolonel.Public.Service.API.Contracts.V1_0\">\n" +
                    "          <BillInAdvance>"+p.getBillInAdv()+"</BillInAdvance>\n" +
                    "          <CustomerCode>"+p.getCustCode()+"</CustomerCode>\n" +
                    "          <EndDate>"+p.getEndDate()+"</EndDate>\n" +
                    "          <ProductLabel>"+p.getProdLbl()+"</ProductLabel>\n" +
                    "          <PurchaseDate>"+p.getPurchDate()+"</PurchaseDate>\n" +
                    "          <PurchaseReference>"+p.getPurchRef()+"</PurchaseReference>\n" +
                    "          <Quantity>"+p.getQuantity()+"</Quantity>\n" +
                    "          <RecurrencePeriodSize>"+p.getRecPerSiz()+"</RecurrencePeriodSize>\n" +
                    "          <RecurrencePeriodUOM>"+p.getRecPerUOM()+"</RecurrencePeriodUOM>\n" +
                    "          <StringValues>\n";
                        for(String n : p.getStringValues().keySet()){
                            xmlInput +=
                    "            <StringNameValuePair>\n"+
                    "              <Name>"+n+"</Name>\n"+
                    "              <Value>"+p.getStringValues().get(n)+"</Value>\n"+
                    "            </StringNameValuePair>\n";
                            }
                        xmlInput+=
                    "          </StringValues>\n"+
                    "        </Purchase>\n";

            }
            xmlInput +=
            "      </purchases>\n" +
            "    </UploadPurchases>\n" +
            "  </Body>\n" +
            "</Envelope>";
            byte[] buffer = new byte[xmlInput.length()];
            buffer = xmlInput.getBytes();
            bout.write(buffer);
            byte[] b = bout.toByteArray();
            String SOAPAction =
                "\"http://tempuri.org/IAPIServiceEndpoint/UploadPurchases\"";
            // Set the appropriate HTTP parameters.
            httpConn.setRequestProperty("Content-Length",
                                        String.valueOf(b.length));
            httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            httpConn.setRequestProperty("SOAPAction", SOAPAction);
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            out = httpConn.getOutputStream();
            //Write the content of the request to the outputstream of the HTTP Connection.
            out.write(b);
            out.close();
            //Read the response.
            InputStreamReader isr =
                new InputStreamReader(httpConn.getInputStream());
            BufferedReader in = new BufferedReader(isr);
            //Write the SOAP message response to a String.
            while ((responseString = in.readLine()) != null) {
                outputString = outputString + responseString;
            }
        } catch (IOException ex) {
            if(ex.getMessage().contains("500")){
                System.out.println("error: " + ex.getMessage());
                InputStreamReader err = new InputStreamReader(httpConn.getErrorStream());
                BufferedReader er = new BufferedReader(err);
                String t;
                try{
                    while((t=er.readLine())!=null){
                        System.out.println(t);
                    }
                } catch (IOException e){
                    Logger.getLogger(WSInteraction.class.getName()).log(Level.SEVERE, null, e);
                }
            } else {
                System.out.println("error: " + ex.getMessage());
                System.out.println(ex.toString());
            }

            if(out!=null){
                try {
                    out.close();
                } catch (IOException ex1) {
                    Logger.getLogger(WSInteraction.class.getName()).log(Level.SEVERE, null, ex1);
                }
            }
            if(httpConn!=null){
                httpConn.disconnect();
                System.out.println("Disconnected");
            } else {
                System.out.println("null");
            }
            //perform login
            login();
            //send again
            uploadPurchases(toUpload);
        }
    }

    private void login(){
        System.out.println("\nLogin:");
        try {
            String tempUri = "http://tempuri.org/";

            SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
            SOAPConnection sc = scf.createConnection();

            MessageFactory mf = MessageFactory.newInstance();
            SOAPMessage sm = mf.createMessage();

            SOAPEnvelope se = sm.getSOAPPart().getEnvelope();

            se.addNamespaceDeclaration("tem", tempUri);

            SOAPHeader sh = sm.getSOAPHeader();

            SOAPBody sb = sm.getSOAPBody();
            SOAPBodyElement bodyElement = sb.addBodyElement(se.createName("Login","tem",tempUri));

            SOAPElement eml = bodyElement.addChildElement("emailAddress","tem");
            eml.addTextNode(email);

            SOAPElement password = bodyElement.addChildElement("password","tem");
            password.addTextNode(pass);

            MimeHeaders mh = sm.getMimeHeaders();
            mh.addHeader("SOAPAction", tempUri+"IAPIServiceEndpoint/Login");

            //send
            SOAPMessage response = sc.call(sm, wsURL);

            SOAPFault sf = response.getSOAPBody().getFault();
            if(sf==null){
                System.out.println("no error");
                System.out.println("Session ID:");
                currentSession = response.getSOAPBody().getChildNodes().item(0).getChildNodes().item(0).getChildNodes().item(0).getTextContent();
                System.out.println(currentSession);
            } else {
                System.out.println("Error: " + sf.getFaultCode() + " " + sf.getFaultString());

            }

        } catch (SOAPException | UnsupportedOperationException ex) {
            Logger.getLogger(WSInteraction.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Example2.java

package examples;

import java.util.ArrayList;
import java.util.UUID;

public class Example2 {
    public static void main(String[] args) {
        WSInteraction cb = new WSInteraction("https://api.billing.inter8.co/V1_0.svc", "admin@example.com", "examplePassword");
        ArrayList<Purchase> purchases = new ArrayList<>();
        //generate 100 purchase
        for(int i=0;i<100;i++){
            Purchase p = new Purchase("C001", UUID.randomUUID().toString(), "2015-01-02T12:34:56", Math.random()*5+"", "None", "0", "false", "Bicycle");
            purchases.add(p);
        }
        cb.uploadPurchases(purchases);
    }

}