Example usage for org.json JSONArray getString

List of usage examples for org.json JSONArray getString

Introduction

In this page you can find the example usage for org.json JSONArray getString.

Prototype

public String getString(int index) throws JSONException 

Source Link

Document

Get the string associated with an index.

Usage

From source file:com.phonegap.AccelListener.java

/**
 * Executes the request and returns PluginResult.
 * /* ww w  .  j  a v  a  2 s .  c  o  m*/
 * @param action       The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @param callbackId   The callback id used when calling back into JavaScript.
 * @return             A PluginResult object with a status and message.
 */
public PluginResult execute(String action, JSONArray args, String callbackId) {
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    try {
        if (action.equals("getStatus")) {
            int i = this.getStatus();
            return new PluginResult(status, i);
        } else if (action.equals("start")) {
            int i = this.start();
            return new PluginResult(status, i);
        } else if (action.equals("stop")) {
            this.stop();
            return new PluginResult(status, 0);
        } else if (action.equals("getAcceleration")) {
            // If not running, then this is an async call, so don't worry about waiting
            if (this.status != AccelListener.RUNNING) {
                int r = this.start();
                if (r == AccelListener.ERROR_FAILED_TO_START) {
                    return new PluginResult(PluginResult.Status.IO_EXCEPTION,
                            AccelListener.ERROR_FAILED_TO_START);
                }
                // Wait until running
                long timeout = 2000;
                while ((this.status == STARTING) && (timeout > 0)) {
                    timeout = timeout - 100;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (timeout == 0) {
                    return new PluginResult(PluginResult.Status.IO_EXCEPTION,
                            AccelListener.ERROR_FAILED_TO_START);
                }
            }
            this.lastAccessTime = System.currentTimeMillis();
            JSONObject r = new JSONObject();
            r.put("x", this.x);
            r.put("y", this.y);
            r.put("z", this.z);
            // TODO: Should timestamp be sent?
            r.put("timestamp", this.timestamp);
            return new PluginResult(status, r);
        } else if (action.equals("setTimeout")) {
            try {
                float timeout = Float.parseFloat(args.getString(0));
                this.setTimeout(timeout);
                return new PluginResult(status, 0);
            } catch (NumberFormatException e) {
                status = PluginResult.Status.INVALID_ACTION;
                e.printStackTrace();
            } catch (JSONException e) {
                status = PluginResult.Status.JSON_EXCEPTION;
                e.printStackTrace();
            }
        } else if (action.equals("getTimeout")) {
            float f = this.getTimeout();
            return new PluginResult(status, f);
        }
        return new PluginResult(status, result);
    } catch (JSONException e) {
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    }
}

From source file:org.dasein.cloud.rackspace.RackspaceException.java

static public ExceptionItems parseException(int code, String json) {
    ExceptionItems items = new ExceptionItems();

    items.code = code;/* w w w  .ja v a  2 s.co  m*/
    items.type = CloudErrorType.GENERAL;
    items.message = "unknown";
    items.details = "The cloud provided an error code without explanation";

    if (json != null) {
        try {
            JSONObject ob = new JSONObject(json);

            if (ob.has("details")) {
                items.details = ob.getString("details");
            } else {
                items.details = "[" + code + "] " + items.message;
            }
            if (ob.has("message")) {
                items.message = ob.getString("message");
                if (items.message == null) {
                    items.message = "unknown";
                } else {
                    items.message = items.message.trim();
                }
                if (code == 400 && items.message.equalsIgnoreCase("validation failure")
                        && ob.has("validationErrors")) {
                    JSONObject v = ob.getJSONObject("validationErrors");

                    if (v.has("messages")) {
                        StringBuilder str = new StringBuilder();
                        JSONArray msgs = v.getJSONArray("messages");

                        for (int i = 0; i < msgs.length(); i++) {
                            String msg = msgs.getString(i).trim();

                            if (msg != null) {
                                if (str.length() > 0) {
                                    str.append("; ");
                                }
                                str.append(msg);
                            }
                        }
                        if (str.length() > 0) {
                            items.details = str.toString();
                        }
                    }
                }
            } else {
                items.message = "unknown";
            }
            String t = items.message.toLowerCase().trim();

            if (t.equals("unauthorized")) {
                items.type = CloudErrorType.AUTHENTICATION;
            } else if (t.equals("serviceunavailable")) {
                items.type = CloudErrorType.CAPACITY;
            } else if (t.equals("badrequest") || t.equals("badmediatype") || t.equals("badmethod")
                    || t.equals("notimplemented")) {
                items.type = CloudErrorType.COMMUNICATION;
            } else if (t.equals("overlimit")) {
                items.type = CloudErrorType.QUOTA;
            } else if (t.equals("servercapacityunavailable")) {
                items.type = CloudErrorType.CAPACITY;
            } else if (t.equals("itemnotfound")) {
                return null;
            }
        } catch (JSONException e) {
            RackspaceCloud.getLogger(RackspaceException.class, "std")
                    .warn("parseException(): Invalid JSON in cloud response: " + json);

            items.details = json;
        }
    }
    return items;
}

From source file:com.worthed.util.LocationUtils.java

/**
 * ?Google API ???/*ww w .j  av  a 2s.c  o  m*/
 * https://developers.google.com/maps/documentation/geocoding
 *
 * @param jsonObject ?Json
 * @return 
 */
public static String decodeLocationName(JSONObject jsonObject) {
    JSONArray jsonArray;
    String country = "", city = "";
    String TYPE_COUNTRY = "country";
    String TYPE_LOCALITY = "locality";
    String TYPE_POLITICAL = "political";
    boolean hasCountry = false;
    try {
        jsonArray = jsonObject.getJSONArray("address_components");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jo = jsonArray.getJSONObject(i);
            JSONArray types = jo.getJSONArray("types");
            boolean hasLocality = false, hasPolicical = false;

            for (int j = 0; j < types.length(); j++) {
                String type = types.getString(j);
                if (type.equals(TYPE_COUNTRY) && !hasCountry) {
                    country = jo.getString("long_name");
                } else {
                    if (type.equals(TYPE_POLITICAL)) {
                        hasPolicical = true;
                    }
                    if (type.equals(TYPE_LOCALITY)) {
                        hasLocality = true;
                    }
                    if (hasPolicical && hasLocality) {
                        city = jo.getString("long_name");
                    }
                }
            }
        }
        return city + "," + country;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (jsonObject.has("formatted_address")) {
        try {
            return jsonObject.getString("formatted_address");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.urbtek.phonegap.SpeechRecognizer.java

/**
 * Fire an intent to start the speech recognition activity.
 * /*from   w ww  .ja  v  a  2  s.co m*/
 * @param args Argument array with the following string args: [req code][number of matches][prompt string]
 */
private void startSpeechRecognitionActivity(JSONArray args) {
    int reqCode = 42; //Hitchhiker?
    int maxMatches = 0;
    String prompt = "";

    try {
        if (args.length() > 0) {
            // Request code - passed back to the caller on a successful operation
            String temp = args.getString(0);
            reqCode = Integer.parseInt(temp);
        }
        if (args.length() > 1) {
            // Maximum number of matches, 0 means the recognizer decides
            String temp = args.getString(1);
            maxMatches = Integer.parseInt(temp);
        }
        if (args.length() > 2) {
            // Optional text prompt
            prompt = args.getString(2);
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, String.format("startSpeechRecognitionActivity exception: %s", e.toString()));
    }

    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    if (maxMatches > 0)
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxMatches);
    if (!prompt.isEmpty())
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
    ctx.startActivityForResult(this, intent, reqCode);
}

From source file:util.Overview.java

public static void getFlows(JSONObject Summary) throws JSONException, SQLException, IOException {
    /* //from   w w w  .ja  v  a  2s  .  co m
     * LOGICA PARA SACAR LA LISTA DE SWITCHES QUE CONTIENEN FLUJOS Y 
     * LOS FLUJOS INSTALADOS EN CADA SWITCH Y SUS VARIABLES PARA 
     * LA BASE DE DATOS
     */

    JSONArray AS = Summary.names(); // Arreglo de Switches conectados                                 

    for (int i = 0; i < Summary.length(); i++) {
        JSONObject s = Summary.getJSONObject(AS.getString(i)); // Se obtiene el JSONObject de los flujos que pertenece a cada switch
        JSONArray arr = s.names(); // Arreglo con los nombres de los flujos para ser recorrido

        for (int j = 0; j < s.length(); j++) {
            JSONObject t = s.getJSONObject(arr.getString(j)); // Se obtiene el JSONObject con los datos del flujo actual
            JSONObject match = t.getJSONObject("match"); // Se obtiene el JSONObject con los matchs del flujo actual
            int priority = t.getInt("priority"); // Se obtiene la prioridad del flujo actual
            int InputPort = match.getInt("inputPort"); // Se obtiene el inputPort del flujo actual
            JSONArray action = t.getJSONArray("actions"); // Se obtiene el JSONArray con los actions del flujo actual
            JSONObject actions = action.getJSONObject(0); // Se obtiene el JSONObject con el action del flujo actual
            int OutputPort = actions.getInt("port"); // Se obtiene el outputPort del flujo actual
            String accion = actions.getString("type"); // Se obtiene el tipo de la accion del flujo actual

            DBManager dbm = new DBManager();
            String sname = arr.getString(j);
            int switchh = dbm.getIndex(AS.getString(i));
            dbm.InsertFlow(j, i, sname, priority, InputPort, accion, OutputPort);
        }
    }
}

From source file:util.Overview.java

public static void getPortStatistics(JSONObject PortSummary) throws JSONException {
    JSONArray PortNames;
    PortNames = PortSummary.names();/*from   www .  j av  a  2 s. c om*/

    for (int i = 0; i < PortSummary.length(); i++) {
        //se obtiene el arreglo que contiene las caracteristicas 
        //del swich actual
        JSONArray pri = PortSummary.getJSONArray(PortNames.getString(i));

        for (int j = 0; j < pri.length(); j++) {
            System.out.println("\n estadisticas generales del swich " + PortNames.getString(i));

            //se obtiene el objeto JSON con las estadisticas de cada puerto
            JSONObject pre = pri.getJSONObject(j);
            int portNumber, receiveBytes, collisions, transmitBytes;
            int transmitPackets, receivePackets;

            portNumber = pre.getInt("portNumber");
            receiveBytes = pre.getInt("receiveBytes");
            collisions = pre.getInt("collisions");
            transmitBytes = pre.getInt("transmitBytes");
            transmitPackets = pre.getInt("transmitPackets");
            receivePackets = pre.getInt("receivePackets");

            // SE DEBE VERIFICAR UNA VARIABLE 'DATE' PARA ENVIAR A LA BASE DE DATOS Y QUE SEA EL EJE X DE UNA POSIBLE GRAFICA
            //DBManager dbm = new DBManager();
            //String sname = arr.getString(j);              
            //int switchh = dbm.getIndex(AS.getString(i));
            //dbm.InsertPortStatistics(j,i,portNumber,receiveBytes,collisions,transmitBytes,transmitPackets,receivePackets);

            //System.out.println("portNumber: " + portNumber);
            //System.out.println("receiveBytes: " + receiveBytes);
            //System.out.println("collisions: " + collisions);
            //System.out.println("transmitBytes: " + transmitBytes);
            //System.out.println("transmitPackets: " + transmitPackets);
            //System.out.println("receivePackets: " + receivePackets);
        }
    }
}

From source file:util.Overview.java

public static void getFlowStatistics(JSONObject FlowSummary) throws JSONException {
    JSONArray SFlowNames = FlowSummary.names();
    //se obtiene el arreglo de equipos que tienen flujos activos

    for (int i = 0; i < SFlowNames.length(); i++) {
        //se obtienen las estadisticas de los flujos del switch actual
        JSONArray FlowStatistics = FlowSummary.getJSONArray(SFlowNames.getString(i));

        for (int j = 0; j < FlowStatistics.length(); j++) {
            JSONObject FlowMatch;/* ww w . j  a  v a  2s  .c  o  m*/
            int packetCount, byteCount, FlowMatchPort, durationSeconds;

            //se obtiene las estadisticas del flujos actual
            JSONObject flow = FlowStatistics.getJSONObject(j);
            packetCount = flow.getInt("packetCount");
            byteCount = flow.getInt("byteCount");
            durationSeconds = flow.getInt("durationSeconds");

            //las estadisticas floodlight las organiza de acuerdo a como 
            //se instalaron
            //los flujos,asi mismo actualmente se determina a cual 
            //flujo pertenece
            //usando los if.

            //CUANDO SE INSERTE TODO EN LA DB, ESTA PARTE NO SERA NECESARIA
            //PORQUE PARA SABER EL FLUJO AL QUE PERTENECE, SOLO SE HARIAN
            //COMPARACION DE LOS SELECTS DE LA TABLAS FLUJOS Y ESTADISTICAS 
            //POR FLUJOS
            //COMPARANDO INPUTPORT,OUTPUTPORT Y LA ACCION A EJECUTAR
            //if(j==0) {
            //    System.out.println("\n estadisticas especificas del "
            //            + "flujo 1");
            //} else {
            //    System.out.println("\n estadisticas especificas del "
            //            + "flujo 2");
            //}

            System.out.println("Estadisticas especificas del flujo: " + j + "\n");
            System.out.println("packetCount: " + packetCount);
            System.out.println("byteCount: " + byteCount);
            System.out.println("durationSeconds: " + durationSeconds);

            FlowMatch = flow.getJSONObject("match");

            FlowMatchPort = FlowMatch.getInt("inputPort");
            System.out.println("puerto de entrada: " + FlowMatchPort);

            JSONArray FlowActions;

            //se obtiene el arreglos de acciones que tiene el flujo actual
            FlowActions = flow.getJSONArray("actions");
            int FlowOutport;
            String FlowType;
            JSONObject FActions;

            //se obtiene la accion correspondiente al flujo
            FActions = FlowActions.getJSONObject(0);
            FlowOutport = FActions.getInt("port");
            FlowType = FActions.getString("type");
            System.out.println("accion a ejecutar: " + FlowType);
            System.out.println("puerto de salida: " + FlowOutport + "\n");
        }
    }
}

From source file:com.github.cnanders.cordova3video.VideoPlayer.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    try {/*from   w  w  w.j  a v  a 2  s  . co m*/
        if (action.equals("playVideo")) {
            playVideo(args.getString(0));
        } else {
            status = PluginResult.Status.INVALID_ACTION;
        }
        callbackContext.sendPluginResult(new PluginResult(status, result));
    } catch (JSONException e) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
    } catch (IOException e) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION));
    }
    return true;
}

From source file:com.facebook.share.internal.ShareInternalUtility.java

public static JSONObject removeNamespacesFromOGJsonObject(JSONObject jsonObject, boolean requireNamespace) {
    if (jsonObject == null) {
        return null;
    }//from  w w  w.j  av a  2s.co m

    try {
        JSONObject newJsonObject = new JSONObject();
        JSONObject data = new JSONObject();
        JSONArray names = jsonObject.names();
        for (int i = 0; i < names.length(); ++i) {
            String key = names.getString(i);
            Object value = null;
            value = jsonObject.get(key);
            if (value instanceof JSONObject) {
                value = removeNamespacesFromOGJsonObject((JSONObject) value, true);
            } else if (value instanceof JSONArray) {
                value = removeNamespacesFromOGJsonArray((JSONArray) value, true);
            }

            Pair<String, String> fieldNameAndNamespace = getFieldNameAndNamespaceFromFullName(key);
            String namespace = fieldNameAndNamespace.first;
            String fieldName = fieldNameAndNamespace.second;

            if (requireNamespace) {
                if (namespace != null && namespace.equals("fbsdk")) {
                    newJsonObject.put(key, value);
                } else if (namespace == null || namespace.equals("og")) {
                    newJsonObject.put(fieldName, value);
                } else {
                    data.put(fieldName, value);
                }
            } else if (namespace != null && namespace.equals("fb")) {
                newJsonObject.put(key, value);
            } else {
                newJsonObject.put(fieldName, value);
            }
        }

        if (data.length() > 0) {
            newJsonObject.put("data", data);
        }

        return newJsonObject;
    } catch (JSONException e) {
        throw new FacebookException("Failed to create json object from share content");
    }
}

From source file:com.cranberrygame.cordova.plugin.ad.adbuddiz.Util.java

private void setUp(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    //Activity activity=cordova.getActivity();
    //webView//  w ww.ja v a  2 s .c o  m
    //args.length()
    //args.getString(0)
    //args.getString(1)
    //args.getInt(0)
    //args.getInt(1)
    //args.getBoolean(0)
    //args.getBoolean(1)
    //JSONObject json = args.optJSONObject(0);
    //json.optString("adUnitBanner")
    //json.optString("adUnitFullScreen")
    //JSONObject inJson = json.optJSONObject("inJson");
    //final String adUnitBanner = args.getString(0);
    //final String adUnitFullScreen = args.getString(1);            
    //final boolean isOverlap = args.getBoolean(2);            
    //final boolean isTest = args.getBoolean(3);
    //final String[] zoneIds = new String[args.getJSONArray(4).length()];
    //for (int i = 0; i < args.getJSONArray(4).length(); i++) {
    //   zoneIds[i] = args.getJSONArray(4).getString(i);
    //}         
    //Log.d(LOG_TAG, String.format("%s", adUnitBanner));         
    //Log.d(LOG_TAG, String.format("%s", adUnitFullScreen));
    //Log.d(LOG_TAG, String.format("%b", isOverlap));
    //Log.d(LOG_TAG, String.format("%b", isTest));
    final String publisherKey = args.getString(0);
    Log.d(LOG_TAG, String.format("%s", publisherKey));

    callbackContextKeepCallback = callbackContext;

    cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            _setUp(publisherKey);
        }
    });
}