org.belio.service.gateway.AirtelCharging.java Source code

Java tutorial

Introduction

Here is the source code for org.belio.service.gateway.AirtelCharging.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.belio.service.gateway;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.X509Certificate;
import org.apache.axis.encoding.Base64;
import static org.apache.http.HttpHeaders.USER_AGENT;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.belio.Launcher;
import org.belio.domain.tix.Outbox;

/**
 *
 * @author jacktone
 */
public class AirtelCharging {

    Properties networkproperties;

    //"https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1";
    public AirtelCharging(Properties networkproperties) {
        this.networkproperties = networkproperties;
        //this.url = networkproperties.getProperty("airtel_charging_url");
    }

    // Authentication Query
    private String xmlRequest(String sourceCode, String phone, String contentid, String itemName,
            String contentDescription, String actualPrice, String contentMediaType) {

        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "
                + "xmlns:char=\"http://ChargingProcess/com/ibm/sdp/services/charging/abstraction/Charging\">\n"
                + "<soapenv:Header/>\n" + "<soapenv:Body>\n" + "<char:charge>\n" + "<inputMsg>\n"
                + "<operation>debit</operation>\n" + "<userId>" + phone + "</userId>\n" //put in Kenya Number
                + "<contentId>" + contentid + "</contentId>\n" // 11927
                + "<itemName>" + itemName + "</itemName>\n" + "<contentDescription>" + contentDescription
                + "</contentDescription>\n" + "<circleId/>\n" + "<lineOfBusiness/>\n" + "<customerSegment/>\n"
                + "<contentMediaType>" + contentMediaType + "</contentMediaType>\n" + "<serviceId/>\n"
                + "<parentId/>\n" + "<actualPrice>" + actualPrice + "</actualPrice>\n" //25
                + "<basePrice>0</basePrice> \n" + "<discountApplied>0.0</discountApplied>\n" + "<paymentMethod/>\n"
                + "<revenuePercent/>\n" + "<netShare/>\n" + "<cpId>ROAMTECH SOLUTIONS_KE</cpId>\n"
                + "<customerClass/>\n" + "<eventType>ReSubscription</eventType>\n" + "<localTimeStamp/>\n"
                + "<transactionId/>\n" + "<parentType/>\n" + "<deliveryChannel>sms</deliveryChannel>\n"
                + "<subscriptionTypeCode>34</subscriptionTypeCode>\n"
                + "<subscriptionName>Subscription</subscriptionName>\n"
                + "<subscriptionExternalId>4</subscriptionExternalId>\n"
                + "<subscriptiondays>1</subscriptiondays>\n" + "<contentSize/>\n" + "<currency>Kshs</currency>\n"
                + "<copyrightId>mauj</copyrightId>\n" + "<cpTransactionId/>\n" + "<copyrightDescription/>\n"
                + "<sMSkeyword>VL</sMSkeyword>\n" + "<srcCode>" + sourceCode + "</srcCode>\n"
                + "<contentUrl>abe.com</contentUrl>\n" + "</inputMsg>\n" + "</char:charge>\n" + "</soapenv:Body>\n"
                + "</soapenv:Envelope>";

        //  echo frame . "\n\n";
        return xml;
    }

    private String sendXmlOverPost(String url, String xml) {
        StringBuffer result = new StringBuffer();
        try {
            Launcher.LOG.info("======================xml==============");

            Launcher.LOG.info(xml.toString());

            //            String userPassword = "roamtech_KE:roamtech _KE!ibm123";
            //            URL url2 = new URL("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");

            String userPassword = "" + networkproperties.getProperty("air_info_u") + ":"
                    + networkproperties.getProperty("air_info_p");
            URL url2 = new URL(url);

            // URLConnection urlc =  url.openConnection();
            URLConnection urlc = url2.openConnection();
            HttpsURLConnection conn = (HttpsURLConnection) urlc;
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("SOAPAction", "run");

            //            urlc.setDoOutput(true);
            //            urlc.setUseCaches(false);
            //            urlc.setAllowUserInteraction(false);
            conn.setRequestProperty("Authorization", "Basic " + new Base64().encode(userPassword.getBytes()));
            conn.setRequestProperty("Content-Type", "text/xml");

            conn.setHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            // Write post data
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.writeBytes(xml);
            out.flush();
            out.close();
            BufferedReader aiResult = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            StringBuffer responseMessage = new StringBuffer();
            while ((line = aiResult.readLine()) != null) {
                responseMessage.append(line);
            }
            System.out.println(responseMessage);

            //urlc.s("POST");  
            //  urlc.setRequestProperty("SOAPAction", SOAP_ACTION);

            urlc.connect();

        }

        catch (MalformedURLException ex) {
            Logger.getLogger(AirtelCharging.class

                    .getName()).log(Level.SEVERE, null, ex);
        }

        catch (IOException ex) {
            Logger.getLogger(AirtelCharging.class

                    .getName()).log(Level.SEVERE, null, ex);
        }
        return result.toString();

        //        try {
        //            // String url = "https://selfsolve.apple.com/wcResults.do";
        //            HttpClient client = new DefaultHttpClient();
        //            HttpPost post = new HttpPost("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");
        //            // add header
        //            post.setHeader("User-Agent", USER_AGENT);
        //            post.setHeader("Content-type:", " text/xml");
        //            post.setHeader("charset", "utf-8");
        //            post.setHeader("Accept:", ",text/xml");
        //            post.setHeader("Cache-Control:", " no-cache");
        //            post.setHeader("Pragma:", " no-cache");
        //            post.setHeader("SOAPAction:", "run");
        //            post.setHeader("Content-length:", "xml");
        //            
        ////            String encoding = new Base64().encode((networkproperties.getProperty("air_charge_n") + ":"
        ////                    + networkproperties.getProperty("air_charge_p")).getBytes());
        //            String encoding = new Base64().encode( ("roamtech_KE:roamtech _KE!ibm123").getBytes());
        //            
        //            post.setHeader("Authorization", "Basic " + encoding);
        //
        //            // post.setHeader("Authorization: Basic ", "base64_encode(credentials)");
        //            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        //            
        //            urlParameters.add(new BasicNameValuePair("xml", xml));
        //            
        //            System.out.println("\n============================ : " + url);
        //
        ////            urlParameters.add(new BasicNameValuePair("srcCode", ""));
        ////            urlParameters.add(new BasicNameValuePair("phone", ""));
        ////            urlParameters.add(new BasicNameValuePair("contentId", ""));
        ////            urlParameters.add(new BasicNameValuePair("itemName", ""));
        ////            urlParameters.add(new BasicNameValuePair("contentDescription", ""));
        ////            urlParameters.add(new BasicNameValuePair("actualPrice", ""));
        ////            urlParameters.add(new BasicNameValuePair("contentMediaType", ""));
        ////            urlParameters.add(new BasicNameValuePair("contentUrl", ""));
        //            post.setEntity(new UrlEncodedFormEntity(urlParameters));
        //            
        //            HttpResponse response = client.execute(post);
        //            Launcher.LOG.info("\nSending 'POST' request to URL : " + url);
        //            Launcher.LOG.info("Post parameters : " + post.getEntity());
        //            Launcher.LOG.info("Response Code : "
        //                    + response.getStatusLine().getStatusCode());
        //            
        //            BufferedReader rd = new BufferedReader(
        //                    new InputStreamReader(response.getEntity().getContent()));
        //            
        //            String line = "";
        //            while ((line = rd.readLine()) != null) {
        //                result.append(line);
        //            }
        //            
        //            System.out.println(result.toString());
        //        } catch (UnsupportedEncodingException ex) {
        //            Launcher.LOG.info(ex.getMessage());
        //        } catch (IOException ex) {
        //            Launcher.LOG.info(ex.getMessage());
        //        }
    }

    public String chargeSms(Outbox outbox) {
        String x = "no change ";
        try {
            //            String sourceCode = outbox.getShortCode();
            //            String phone = "254736375819";
            //            //String phone = outbox.getMsisdn();
            //            String contentid = String.valueOf(outbox.getRefNo());
            //            String itemName = String.valueOf(outbox.getRefNo());
            //            String contentDescription = URLEncoder.encode(outbox.getText(), "UTF-8");
            //            String actualPrice = "5";
            //            String contentMediaType = outbox.getShortCode();
            //            String contentUrl = URLEncoder.encode(outbox.getText(), "UTF-8");
            String sourceCode = "22554";
            String phone = "254736375819";
            String contentid = String.valueOf(Math.abs(new Random().nextInt()));
            String itemName = String.valueOf(Math.abs(new Random().nextInt()));
            String contentDescription = "sms";
            String actualPrice = "5";
            String contentMediaType = URLDecoder.decode(URLEncoder.encode("sasa jacktone test", "UTF-8"), "UTF-8");
            String xml = xmlRequest(sourceCode, phone, contentid, itemName, contentDescription, actualPrice,
                    contentMediaType);
            x = sendXmlOverPost(networkproperties.getProperty("airtel_charging_url"), xml);
        } catch (UnsupportedEncodingException ex) {
            Launcher.LOG.info(ex.getMessage());
        } catch (Exception ex) {
            Launcher.LOG.info(ex.getMessage());
        }
        return x;
    }

    public static void main(String args[]) {
        // new AirtelCharging().chargeSms(new Outbox());

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    //  System.out.println(url);
                    long before, sleepDuration, operationTime;
                    int tps = 6500;
                    for (int i = 0; i < 100; i++) {
                        before = System.currentTimeMillis();
                        // do your operations
                        operationTime = (long) (tps * Math.random());
                        System.out.print("Doing operations for " + operationTime + "ms\t");
                        Thread.sleep(operationTime);

                        // sleep for up to 1000ms
                        sleepDuration = Math.min(1000, Math.max(1000 - (System.currentTimeMillis() - before), 0));
                        Thread.sleep(sleepDuration);
                        System.out.println("wait\t" + sleepDuration + "ms =\telapsed "
                                + (operationTime + sleepDuration) + (operationTime > 1000 ? "<" : ""));
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }).start();
    }

    //    static {
    //    disableSslVerification();
    //}
    //
    //private static void disableSslVerification() {
    //    try
    //    {
    //        // Create a trust manager that does not validate certificate chains
    //        TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
    //            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    //                return null;
    //            }
    //            @Override
    //            public void checkClientTrusted(java.security.cert.X509Certificate[] xcs, String string) throws CertificateException {
    //              
    //            }
    //
    //            @Override
    //            public void checkServerTrusted(java.security.cert.X509Certificate[] xcs, String string) throws CertificateException {
    //              
    //            }
    //        }
    //        };
    //
    //        // Install the all-trusting trust manager
    //        SSLContext sc = SSLContext.getInstance("SSL");
    //        sc.init(null, trustAllCerts, new java.security.SecureRandom());
    //        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    //
    //        // Create all-trusting host name verifier
    //        HostnameVerifier allHostsValid = new HostnameVerifier() {
    //              @Override
    //            public boolean verify(String hostname, SSLSession session) {
    //                return true;
    //            }
    //
    //         
    //        };
    //
    //        // Install the all-trusting host verifier
    //        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    //    } catch (NoSuchAlgorithmException e) {
    //        e.printStackTrace();
    //    } catch (KeyManagementException e) {
    //        e.printStackTrace();
    //    }
    //}

}