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

Java tutorial

Introduction

Here is the source code for org.belio.service.gateway.Gateway.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.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
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 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;
import org.belio.domain.tix.OutboxList;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

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

    String url = "http://api.infobip.com/api/v3/sendsms/xml";
    private Properties networkprop;

    public Gateway() {
        try {
            this.networkprop = Launcher.fetchConfigurations("networks.properties");
        } catch (IOException ex) {
            Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public synchronized boolean sendBulkMessages(OutboxList outboxList) {
        try {
            for (Outbox outbox : outboxList.getOutboxes()) {
                return sendXmlBulk(outbox); // sendJsonBulk(Outbox outbox)
            }

            //doPostJson(new JSONObject(createJsonString()));
        } catch (Exception ex) {
            ex.printStackTrace();
            Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
        }

        return false;
    }

    private synchronized boolean sendXmlBulk(Outbox outbox) {

        System.out.println("TTTTTTTTTTTTTTTTTTTTT=================Sending Other network message");

        return doPostXml(getXml(outbox));

    }

    private synchronized void sendJsonBulk(Outbox outbox) {
        try {
            // Random
            JSONObject obj = new JSONObject();
            JSONObject auth = new JSONObject();
            JSONObject messages = new JSONObject();
            JSONObject receipients = new JSONObject();
            receipients.put("gsm", outbox.getMsisdn());
            receipients.put("messageId", Math.abs(new Random().nextInt()));
            messages.put("sender", "Roamtech");
            messages.put("text", outbox.getText());
            messages.put("receipients", receipients);

            auth.put("username", networkprop.getProperty("roam_info_u"));
            auth.put("password", networkprop.getProperty("roam_info_u"));
            obj.put("authentication", auth);
            obj.put("messages", messages);
            doPostJson(obj);

            System.out.println(obj);
            System.out.println();
        } catch (JSONException ex) {
            Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private synchronized void doPostJson(JSONObject obj) {
        try {
            // String urlParameters = "param1=a&param2=b&param3=c";
            String request = "http://api.infobip.com/api/v3/sendsms/json";
            URL url = new URL(request);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setInstanceFollowRedirects(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");
            // connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
            connection.setUseCaches(false);

            OutputStream wr = connection.getOutputStream();
            //  wr.writeBytes(urlParameters);
            wr.write(obj.toString().getBytes());
            wr.flush();

            BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            String line;
            while ((line = rd.readLine()) != null) {
                System.out.println(line);
            }
            wr.close();
            rd.close();

            //s wr.close();
            connection.disconnect();
        } catch (MalformedURLException ex) {
            Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ProtocolException ex) {
            Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private synchronized boolean doPostXml(String xml) {

        try {
            // String urlParameters = "param1=a&param2=b&param3=c";

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            post.setHeader("HOST", "api.infobip.com");

            // add header
            // post.setHeader("User-Agent", USER_AGENT);
            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            urlParameters.add(new BasicNameValuePair("xml", xml));

            post.setEntity(new UrlEncodedFormEntity(urlParameters));

            HttpResponse response = client.execute(post);
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + post.getEntity());
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }

            System.out.println(result.toString());
        } catch (IOException ex) {
            Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }

    private synchronized String getXml(Outbox outbox) {
        StringBuilder builder = null;
        try {
            // String rec = "254724170138";
            // String rec = "254772429102";
            //0774799687
            // String rec = "254736375819";
            // String rec = "254723781479";
            //String rec = "254723781479";
            Long rec = outbox.getMsisdn();
            //String message = URLEncoder.encode(outbox.getText(), "UTF-8");
            String message = URLDecoder.decode(URLEncoder.encode(outbox.getText(), "UTF-8"), "UTF-8");
            String messageId = String.valueOf(Math.abs(new Random().nextInt()));
            // String sender = "Roamtech";            
            String sender = outbox.getShortCode();
            String username = networkprop.getProperty("roam_info_u");
            String password = networkprop.getProperty("roam_info_p");
            builder = new StringBuilder();
            builder.append("<SMS>").append("<authentication>").append("<username>").append(username)
                    .append("</username>").append("<password>").append(password).append("</password>")
                    .append("</authentication>").append("<message>").append("<sender>").append(sender)
                    .append("</sender>").append("<text>").append(message).append("</text>").append("<recipients>")
                    .append("<gsm messageId=\"").append(messageId).append("\">").append(rec).append("</gsm>")
                    .append("</recipients>").append("<Srcton>5</Srcton>").append("<Srcnpi>0</Srcnpi>")
                    .append("</message>").append("</SMS>");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
        }
        return builder.toString();

    }

    //    private String createJsonString() {
    //        String json = "";
    //        try {
    //            String rec = "254724170138";
    //           // String rec = "254736375819";
    //            String message = URLEncoder.encode("Hello", "UTF-8");
    //            String messageId = String.valueOf(Math.abs(new Random().nextInt()));
    //            String sender = "Roamtech";
    //            String username = "roam11";
    //            String password = "22tech";
    //            json = "{"
    //                    + "\"authentication\": {"
    //                    + "\"username\": \"" + username + "\","
    //                    + "\"password\": \"" + password + "\""
    //                    + "},"
    //                    + "\"messages\": ["
    //                    + "{"
    //                    + "\"sender\": \"" + sender + "\","
    //                    + "\"text\": \"" + message + "\","
    //                    + "\"recipients\": ["
    //                    + "{"
    //                    + "\"gsm\": \"" + rec + "\","
    //                    + "\"messageId\": \"" + messageId + "\""
    //                    + "}]}]}";
    //
    //        } catch (UnsupportedEncodingException ex) {
    //            Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
    //        }
    //        return json;
    //    }
    private static class InstanceHolder {

        private static final Gateway GATEWAY = new Gateway();
    }

    public static Gateway getInstance() {
        return InstanceHolder.GATEWAY;
    }
}