0

So I am creating a daemon that connects to some API and returns a payload. The actual transaction works just ok, but now I am working on the exception. Below is my Java code.

public static void main(String args[]) throws IOException,NoSuchAlgorithmException {

    String username = "XXXXX";
    String password = "XXXX";
    String nonce = "XXXXX";

    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    String created = dateFormatter.format(new Date());
    // String created = "2018-07-12EAT14:31:1210800";
    String input = nonce + created + password;
    //String passwordDigest = "jro73ZmrGeYEG7OqPWdU9fgyEFY=";
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    String passwordDigest = DatatypeConverter.printBase64Binary(md.digest(input.getBytes("UTF-8")));
    // System.out.println(header.toString());
    System.out.println(DatatypeConverter.printBase64Binary(input.getBytes("UTF-8")) + " === " + created + " " + username);

    String xml = "<fulfillmentRequest>"
            + "<msisdn>260964293635</msisdn>"
            + "<operationType>3</operationType>"
            + "<iname>Stanchart</iname>"
            + "<clientTransactionId>19035542356435323</clientTransactionId>"
            + "<productCode>NACT_ZM_Data_4764</productCode>"
            + "<pin>2018</pin><benmsisdn>260966745046</benmsisdn>"
            + "</fulfillmentRequest>";

    System.out.println("This is the request to MTN => " + xml);
    String endpoint = "http://172.25.48.43:8312/1/cis/services/fulfillment";

    System.out.println("This is the endpoint we are posting the transaction to => " + endpoint);

    boolean hasResponse = false;
    String statCode = null;
    String statusResponse = null;
    String receiptNo = null;

    //OutputStream zp =null;
    BufferedReader  br;
    StringBuilder sb;

    String respTxt= "";
    int msg=0 ;
    String response;
    URL url;
    HttpURLConnection connection ;

    try {
        url = new URL(endpoint);

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        connection.setRequestProperty("Authorization", "WSSE realm=\"SDP\", profile=\"UsernameToken\"");
        connection.setRequestProperty("User-Agent", "Jakarta Commons-HttpClient/3.1");
        connection.setRequestProperty("X-WSSE", "UsernameToken Username="+username+",PasswordDigest="+passwordDigest+",Nonce=\""+nonce+"\",Created=\""+created+"\"");
        connection.setRequestProperty("Host", "172.25.48.43:8312");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(50000);
        connection.setReadTimeout(90000);
        DataOutputStream output = new DataOutputStream(connection.getOutputStream());
        output.writeBytes(xml);
        output.flush();
        responseCode = connection.getResponseCode();
        respTxt = connection.getResponseMessage();
        System.out.println("Status code after sending the the payload to mtn => " + responseCode + " Now waiting for response: ");
        Object vm = connection.toString();

        msg = connection.getContentLength();
        br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
        sb = new StringBuilder();

        System.out.println("| Response |" + br.toString() + " |beepTrxID: " );
        while ((response = br.readLine()) != null) {
            sb.append(response);
        }
        System.out.println(sb.toString());
        if (br.toString().isEmpty() || br.toString() == null) {
            hasResponse = false;
            statusResponse = "Empty response from MTN server:" + br.toString();
        } else {
            DocumentBuilder builder = dbf.newDocumentBuilder();
            InputSource source = new InputSource(new StringReader(sb.toString()));
            Document document = builder.parse(source);
            NodeList responseCode = document.getElementsByTagName("responseCode");
            NodeList responseDescription = document.getElementsByTagName("responseDescription");
            NodeList receipt;
            if (br.toString().contains("requestId")) {
                receipt = document.getElementsByTagName("requestId");
                receiptNo = receipt.item(0).getTextContent().trim();
            } else {
                receiptNo = "value";
            }
            System.out.println("|Extracting status code..." + " |beepTrxID: "+sb.toString());
            statCode = responseCode.item(0).getTextContent().trim();
            statusResponse = responseDescription.item(0).getTextContent().trim();
            System.out.println("|Status Code: " + statCode + "| Status Response: " + statusResponse + " |beepTrxID: ");
        }
        br.close();
        connection.disconnect();
    } catch (MalformedURLException ex) {
        System.out.println("An error occured:" + respTxt);
        System.out.println(msg);
    } catch (IOException ex ){
        System.out.println("An error occured:" + respTxt);
    } catch (ParserConfigurationException ex) {
        System.out.println(ex);
    } catch (SAXException ex) {
        System.out.println(ex);
    }
}

Below is the reponse when an exception is thrown:

HTTP/1.1 500 Internal Server Error
Content-Type: application/xml; charset=UTF-8
Connection: close
Content-Length: 401

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><fulfillmentService><responseCode>1106</responseCode><status>FAILURE</status><systemType>CIS</systemType><responseDescription>Sorry! We are unable to process your request. Call 111 for customer care or visit www.mtnzambia.com.</responseDescription><requestId>WEB_10.100.244.97_7889e49b-24f4-4c27-8d69-f4fd6d25c603</requestId></fulfillmentService>

When the exception runs I need it display xml payload. And I have no idea how to do it. Please help.

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
  • Too much code. Please [edit] your question and trim it down to a [mcve]. Make sure you format the code so that it's easy to read. You may want to take the [tour] to better understand how to ask questions here. – Robert Aug 14 '18 at 19:45
  • Possible duplicate of [Read url to string in few lines of java code](https://stackoverflow.com/questions/4328711/read-url-to-string-in-few-lines-of-java-code) – Alex Shesterov Aug 14 '18 at 20:27

0 Answers0