External API calls inside Custom Cordova plugin


#1

I want to create a custom cordova plugin in an which an external api call is made. But the native java method is not calling from js when External API call done within it. The JS file and native java code is give here.

cordova-plugin-tsp.js

cordova.define("cordova-plugin-tsp.TSP", function(require, exports, module) {
//var exec = require('cordova/exec');
var TSP = function() {
    var _appID = "";
};
TSP.prototype.startInit = function(appId) {
	TSP._appID = appId;
    return this;
};
TSP.prototype.tsp_a10000 = function(arg0, success, error) {
	cordova.exec(success, error, "tsp", "tsp_a10000", [arg0]);
};


//-------------------------------------------------------------------

if(!window.plugins)
    window.plugins = {};

if (!window.plugins.TSP)
    window.plugins.TSP = new TSP();

if (typeof module != 'undefined' && module.exports)
    module.exports = TSP;
});

tsp.java

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.PluginResult;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import sample.test;

/**
 * This class echoes a string called from JavaScript.
 */
public class tsp extends CordovaPlugin {
	
	// This is to prevent an issue where if two Javascript calls are made to OneSignal expecting a callback then only one would fire.
	  private static void callbackSuccess(CallbackContext callbackContext, JSONObject jsonObject) {
	    if (jsonObject == null) // in case there are no data
	      jsonObject = new JSONObject();

	    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, jsonObject);
	    pluginResult.setKeepCallback(true);
	    callbackContext.sendPluginResult(pluginResult);
	  }
	  
	  private static void callbackError(CallbackContext callbackContext, JSONObject jsonObject) {
	    if (jsonObject == null) // in case there are no data
	      jsonObject = new JSONObject();
	    
	    PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, jsonObject);
	    pluginResult.setKeepCallback(true);
	    callbackContext.sendPluginResult(pluginResult);
	  }
	  
	  private static void callbackError(CallbackContext callbackContext, String str) {
	    PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, str);
	    pluginResult.setKeepCallback(true);
	    callbackContext.sendPluginResult(pluginResult);
	  }
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("tsp_a10000")) {
            String message = args.getString(0);
            this.tsp_a10000(message, callbackContext);
            return true;
        }
        return false;
    }

    private void tsp_a10000(String message, CallbackContext callbackContext) {
    	 JSONObject jsonIds = new JSONObject();
    	// test s=new test();
        if (message != null && message.length() > 0) {
        	try {
        		String s="";
        		s += "\n OS Version: " + System.getProperty("os.version") + "(" + android.os.Build.VERSION.INCREMENTAL + ")";
        		s += "\n OS API Level: " + android.os.Build.VERSION.SDK_INT;
        		s += "\n Device: " + android.os.Build.DEVICE;
        		s += "\n Model (and Product): " + android.os.Build.MODEL + " ("+ android.os.Build.PRODUCT + ")";
        		jsonIds.put("message", message);
        		jsonIds.put("Debug-infos",s);
        		 try {
	        			 HttpGet httpget = new HttpGet("http://echo.jsontest.com/title/ipsum/content/blah");
	        			 CloseableHttpResponse response = HttpClients.createDefault().execute(httpget);
        		        int responseCode = response.getStatusLine().getStatusCode();
          	           	jsonIds.put("GET_request_Url",httpget.getURI().toString());
          	           	jsonIds.put("Response_Code", Integer.toString(responseCode));
          	            
          	          BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        		        StringBuffer sb = new StringBuffer("");
        		        String line = "";
        		        while ((line = in.readLine()) != null) {                    
        		            sb.append("\n"+line);
        		        }
        		        in.close();
        		        jsonIds.put("Content",line);
     	        } catch (Exception e) {
     	        	jsonIds.put("Exception", e.toString());
     	        	callbackError(callbackContext,jsonIds);
     	            //e.printStackTrace();
     	        }
        		callbackSuccess(callbackContext,jsonIds);
        	}catch(Throwable t){
        		 t.printStackTrace();
        	}
        } else {
        	callbackError(callbackContext,"Expected one non-empty string argument.");
        }
    }
}

Plugin.XML

<?xml version='1.0' encoding='utf-8'?>
<plugin id="cordova-plugin-tsp" version="0.0.4" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
	<name>cordova-plugin-tsp</name>
	<js-module name="TSP" src="www/cordova-plugin-tsp.js">
		<clobbers target="TSP" />
	</js-module>
	<platform name="android">
		<config-file parent="/*" target="res/xml/config.xml">
			<feature name="tsp">
				<param name="android-package" value="tsp" />
			</feature>
		</config-file>
		<config-file parent="/manifest" target="AndroidManifest.xml">
			<uses-permission  android:name="android.permission.INTERNET" />
		</config-file>
		<source-file src="src/android/lib/sample.jar" target-dir="libs" framework="true"/>
		<source-file src="src/android/lib/cordova-2.4.0.jar" target-dir="libs" framework="true"/>
		<source-file src="src/android/lib/common-lang3.jar" target-dir="libs" framework="true"/>
		<source-file src="src/android/lib/json-lib-2.3-jdk15.jar" target-dir="libs" framework="true"/>
		<source-file src="src/android/lib/json-20070829.jar" target-dir="libs" framework="true"/>
		<source-file src="src/android/lib/jose4j-0.5.5.jar" target-dir="libs" framework="true"/>
		<source-file src="src/android/lib/httpcore-4.4.jar" target-dir="libs" framework="true"/>
		<source-file src="src/android/lib/httpcomponents-httpclient-4.5.2.jar" target-dir="libs" framework="true"/>
		<source-file src="src/android/tsp.java" target-dir="src/cordova-plugin-tsp/tsp" />
	</platform>
</plugin>

**

The plugin method called in my App is as below:

**

window['plugins'].TSP.tsp_a10000('Hi',function(data){
                     console.log('tsp_a10000 sucess: ' + JSON.stringify(data));
                },function(error){
                    console.log('tsp_a10000 error: ' + JSON.stringify(error));
                });

please help me…