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.android.i18n.addressinput.JsoMap.java

String string() throws ClassCastException, IllegalArgumentException {
    StringBuilder sb = new StringBuilder("JsoMap[\n");
    JSONArray keys = getKeys();
    for (int i = 0; i < keys.length(); i++) {
        String key;/*from w  w  w  . j  a v  a 2 s .  c  om*/
        try {
            key = keys.getString(i);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        sb.append('(').append(key).append(':').append(get(key)).append(')').append('\n');
    }
    sb.append(']');
    return sb.toString();
}

From source file:com.android.i18n.addressinput.JsoMap.java

String map() throws ClassCastException, IllegalArgumentException {
    StringBuilder sb = new StringBuilder("JsoMap[\n");
    JSONArray keys = getKeys();
    for (int i = 0; i < keys.length(); i++) {
        String key;//from   w  w w .ja  va  2 s . c  o  m
        try {
            key = keys.getString(i);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        sb.append('(').append(key).append(':').append(getObj(key).string()).append(')').append('\n');
    }
    sb.append(']');
    return sb.toString();
}

From source file:com.smart.network.JsonResponseHelper.java

public boolean GetPictos(ArrayList<String> pictoArray, ArrayList<String> request) {
    boolean bret = false;
    try {/*www  .  j a v a  2 s. c o m*/
        JSONObject objectABLE = new JSONObject(mJsonResult);
        JSONArray pictos = objectABLE.getJSONArray("pictos");

        for (int i = 0; i < pictos.length(); i++) {
            String pictoURL = pictos.getString(i);
            pictoURL = trimEnd(pictoURL);
            if (i < request.size()) {
                //Log.i("EDSTAG", ">>> Request <<<" + request.get(i) + "<<< Response >>>" + pictoURL );
            } else {
                //Log.i("EDSTAG", "<<< Response >>>" + pictoURL);

            }
            if ((pictoURL.length() > 0)) {
                if (pictoURL.charAt(0) != '\n') {
                    pictoArray.add(pictoURL);
                }
            }
        }
        bret = true;

    } catch (JSONException e) {
        // TODO Auto-generated catch block

        e.printStackTrace();
    }
    return bret;
}

From source file:org.kaoriha.phonegap.plugins.licensing.LicenseVerificationPlugin.java

/**
 *    Executes the request and returns PluginResult
 * //from   w w w . j  av a2  s  . co  m
 *    @param action      Action to execute
 *    @param data         JSONArray of arguments to the plugin
 *  @param callbackId   The callback id used when calling back into JavaScript
 *  
 *  @return            A PluginRequest object with some result
 * */
@Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
    LicenseServiceConnection conn = new LicenseServiceConnection(ctx);
    PluginResult result;
    if (ACTION.equals(action)) {
        try {
            String nonce = data.getString(0);
            PLicenseQuery q = new PLicenseQuery(Integer.parseInt(nonce), callbackId);
            conn.offer(q);
            result = new PluginResult(PluginResult.Status.NO_RESULT);
            result.setKeepCallback(true);
        } catch (JSONException e) {
            Log.w(TAG, "Got JSON Exception: " + e.getMessage());
            result = new PluginResult(Status.JSON_EXCEPTION);
        }
    } else {
        Log.w(TAG, "Invalid action : " + action + " passed");
        result = new PluginResult(Status.INVALID_ACTION);
    }

    Log.i(TAG, "execute OK");
    return result;
}

From source file:uk.co.ghosty.phonegap.plugins.WakeOnLan.java

@Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
    // TODO Auto-generated method stub
    Log.d("WakeOnLan", "Calling plugin execute message");
    PluginResult result = null;//from w  ww .  j a  v  a  2s . c o m
    if (ACTION.equals(action)) {
        try {
            String macStr = data.getString(0);
            String ipStr = data.getString(1);

            byte[] macBytes = getMacBytes(macStr);
            byte[] bytes = new byte[6 + 16 * macBytes.length];

            for (int i = 0; i < 6; i++) {
                bytes[i] = (byte) 0xff;
            }
            for (int i = 6; i < bytes.length; i += macBytes.length) {
                System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
            }

            InetAddress address = InetAddress.getByName(ipStr);
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, PORT);
            DatagramSocket socket = new DatagramSocket();
            socket.send(packet);
            socket.close();

            System.out.println("Wake-on-LAN packet sent.");
            result = new PluginResult(Status.OK, "Packet sent");
        } catch (Exception e) {
            result = new PluginResult(Status.IO_EXCEPTION);
            Log.e("WakeOnLan", "Exception thrown", e);
        }
    } else {
        result = new PluginResult(Status.INVALID_ACTION);
        Log.d("DirectoryListPlugin", "Invalid action : " + action + " passed");
    }
    return result;
}

From source file:com.dbmojo.DBMojoServer.java

private static DBMojoServer getMojoServerFromConfig(String[] args) {

    DBMojoServer server = null;/*from  w w  w  .j  a  va  2s. c o m*/

    try {
        String configFilePath = null;
        String json = null;
        JSONObject jObj = null;

        parseJson: {
            //If a command line argument is passed then assume it is the config file.
            //Otherwise use the default location
            if (args.length > 0) {
                configFilePath = args[0];
            } else {
                configFilePath = DBMojoServer.defaultConfigPath;
            }

            try {
                json = Util.fileToString(configFilePath);
            } catch (Exception fileEx) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', could not be found and/or read");
            }

            if (json == null || json.equals("")) {
                throw new Exception("the specified config file, '" + configFilePath + "', is empty");
            }

            try {
                jObj = new JSONObject(json);
            } catch (Exception je) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', does not contain valid JSON");
            }
        }

        //Load basic config data
        short serverPort = (short) jObj.optInt("serverPort");
        boolean useGzip = jObj.optBoolean("useGzip");
        short maxConcReq = (short) jObj.optInt("maxConcurrentRequests");
        String accessLogPath = jObj.optString("accessLogPath");
        String errorLogPath = jObj.optString("errorLogPath");
        String debugLogPath = jObj.optString("debugLogPath");

        checkMaxConcurrentReqeusts: {
            if (maxConcReq <= 0) {
                throw new Exception("please set the max concurrent requests to " + "a resonable number");
            }
        }

        checkServerPort: {
            //Make sure serverPort was specified
            if (serverPort <= 0) {
                throw new Exception("the server port was not specified");
            }

            //Make sure serverPort is not in use
            ServerSocket tSocket = null;
            try {
                tSocket = new ServerSocket(serverPort);
            } catch (Exception se) {
                tSocket = null;
                throw new Exception("the server port specified is already in use");
            } finally {
                if (tSocket != null) {
                    tSocket.close();
                }
                tSocket = null;
            }
        }

        startLogs: {
            if (!accessLogPath.equals("")) {
                //Make sure accessLogPath exists
                Util.pathExists(accessLogPath, true);
                //Start logging
                AccessLog.start(accessLogPath);
            }

            if (!errorLogPath.equals("")) {
                //Make sure errorLogPath exists
                Util.pathExists(errorLogPath, true);
                //Start logging
                ErrorLog.start(errorLogPath);
            }

            if (!debugLogPath.equals("")) {
                //Make sure debugLogPath exists
                Util.pathExists(debugLogPath, true);
                //Start logging
                DebugLog.start(debugLogPath);
            }
        }

        ConcurrentHashMap<String, ConnectionPool> dbPools = new ConcurrentHashMap<String, ConnectionPool>();
        loadDbAlaises: {
            ClassLoader classLoader = ClassLoader.getSystemClassLoader();
            final JSONArray dbAliases = jObj.getJSONArray("dbAliases");

            for (int i = 0; i < dbAliases.length(); i++) {
                final JSONObject tObj = dbAliases.getJSONObject(i);
                final String tAlias = tObj.getString("alias");
                final String tDriver = tObj.getString("driver");
                final String tDsn = tObj.getString("dsn");
                final String tUsername = tObj.getString("username");
                final String tPassword = tObj.getString("password");
                int tMaxConnections = tObj.getInt("maxConnections");
                //Seconds
                int tExpirationTime = tObj.getInt("expirationTime") * 1000;
                //Seconds
                int tConnectTimeout = tObj.getInt("connectTimeout");

                //Make sure each alias is named
                if (tAlias.equals("")) {
                    throw new Exception("alias #" + i + " is missing a name");
                }

                //Attempt to load each JDBC driver to ensure they are on the class path
                try {
                    Class aClass = classLoader.loadClass(tDriver);
                } catch (ClassNotFoundException cnf) {
                    throw new Exception("JDBC Driver '" + tDriver + "' is not on the class path");
                }

                //Make sure each alias has a JDBC connection string
                if (tDsn.equals("")) {
                    throw new Exception("JDBC URL, 'dsn', is missing for alias '" + tAlias + "'");
                }

                //Attempt to create a JDBC Connection
                ConnectionPool tPool;
                try {
                    tPool = new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, 1, 1, 1, tAlias);
                    tPool.checkOut(false);
                } catch (Exception e) {
                    throw new Exception(
                            "JDBC Connection cannot be established " + "for database '" + tAlias + "'");
                } finally {
                    tPool = null;
                }

                //If the max connections option is not set for this alias 
                //then set it to 25
                if (tMaxConnections <= 0) {
                    tMaxConnections = 25;
                    System.out.println("DBMojoServer: Warning, 'maxConnections' " + "not set for alias '"
                            + tAlias + "' using 25");
                }

                //If the connection expiration time is not set for this alias then 
                //set it to 30 seconds
                if (tExpirationTime <= 0) {
                    tExpirationTime = 30;
                    System.out.println("DBMojoServer: Warning, 'expirationTime' not " + "set for alias '"
                            + tAlias + "' using 30 seconds");
                }

                //If the connection timeout is not set for this alias then 
                //set it to 10 seconds
                if (tConnectTimeout <= 0) {
                    tConnectTimeout = 10;
                    System.out.println("DBMojoServer Warning, 'connectTimeout' not " + "set for alias '"
                            + tAlias + "' using 10 seconds");
                }

                //Make sure another alias with the same name is not already 
                //defined in the config
                if (dbPools.containsKey(tAlias)) {
                    throw new Exception(
                            "the alias '" + tAlias + "' is already defined in " + " the provided config file");
                }

                //Everything is nicely set! Lets add a connection pool to the 
                //dbPool Hashtable keyed by this alias name
                dbPools.put(tAlias, new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, tMaxConnections,
                        tExpirationTime, tConnectTimeout, tAlias));
            }
        }

        loadClusters: {
            final JSONArray tClusters = jObj.optJSONArray("clusters");

            if (tClusters != null) {
                for (int c = 0; c < tClusters.length(); c++) {
                    final JSONObject tObj = tClusters.getJSONObject(c);
                    final String tAlias = tObj.getString("alias");
                    final String tWriteTo = tObj.getString("writeTo");

                    if (dbPools.containsKey(tAlias)) {
                        throw new Exception("the alias '" + tAlias + "' is already defined.");
                    }

                    if (!dbPools.containsKey(tWriteTo)) {
                        throw new Exception(
                                "the alias '" + tWriteTo + "' is not present in the valid dbAliases. "
                                        + "This alias cannot be used for a cluster.");
                    }

                    //Add the dbAlias to the cluster writeTo list
                    ConnectionPool writeTo = dbPools.get(tWriteTo);

                    final JSONArray tReadFrom = tObj.getJSONArray("readFrom");
                    ArrayList<ConnectionPool> readFromList = new ArrayList<ConnectionPool>();
                    for (int r = 0; r < tReadFrom.length(); r++) {
                        final String tRead = tReadFrom.getString(r);
                        if (!dbPools.containsKey(tRead)) {
                            throw new Exception(
                                    "the alias '" + tRead + "' is not present in the valid dbAliases. "
                                            + "This alias cannot be used for a cluster.");
                        }
                        //Add the dbAlias to the cluster readFrom list
                        readFromList.add(dbPools.get(tRead));
                    }

                    dbPools.put(tAlias, new JDBCClusteredConnectionPool(tAlias, writeTo, readFromList));
                }
            }
        }

        server = new DBMojoServer(useGzip, serverPort, maxConcReq, dbPools);

    } catch (Exception jsonEx) {
        System.out.println("DBMojoServer: Config error, " + jsonEx);
        System.exit(-1);
    }

    return server;
}

From source file:com.googlecode.android_scripting.facade.ui.AlertDialogTask.java

/**
 * Set list items./*from w w  w. ja  va  2 s  .c o  m*/
 * 
 * @param items
 */
public void setItems(JSONArray items) {
    mItems.clear();
    for (int i = 0; i < items.length(); i++) {
        try {
            mItems.add(items.getString(i));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
    mInputType = InputType.MENU;
}

From source file:dk.iface.cordova.plugin.googlenavigate.GoogleNavigate.java

private boolean navigate(JSONArray args, CallbackContext callbackContext) {
    boolean result;

    try {/* www  . ja  va  2s .  c  o  m*/
        String query = args.getString(0);

        if (query != null && query.length() > 0) {
            Log.d(LOG_TAG, "Navigating to " + query);
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" + query));
            this.cordova.getActivity().startActivity(i);
            callbackContext.success();
        } else {
            Log.d(LOG_TAG, "Expected non-empty string arguments for query.");
            callbackContext.error("Expected non-empty string arguments for query.");
        }
        result = true;
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Exception occurred: ".concat(e.getMessage()));
        result = false;
    }
    return result;
}

From source file:com.naman14.algovisualizer.AlgoDescriptionFragment.java

private void addDescData(String algorithmKey) {
    if (descJson == null || descObject == null || getActivity() == null) {
        return;//from  w ww. j  a va  2 s.c  o m
    }
    rootView.removeAllViews();
    try {
        JSONObject dataObject = descObject.getJSONObject(algorithmKey);

        Iterator<?> keys = dataObject.keys();

        while (keys.hasNext()) {

            View descView = LayoutInflater.from(getActivity()).inflate(R.layout.item_code_desc, rootView,
                    false);
            TextView title = (TextView) descView.findViewById(R.id.title);
            TextView desc = (TextView) descView.findViewById(R.id.desc);
            desc.setMovementMethod(LinkMovementMethod.getInstance());

            String key = (String) keys.next();
            title.setText(key);

            if (dataObject.get(key) instanceof JSONObject) {
                JSONObject jsonObject = dataObject.getJSONObject(key);
                String descString = "";

                Iterator<?> complexityKeys = jsonObject.keys();

                while (complexityKeys.hasNext()) {
                    String complexityKey = (String) complexityKeys.next();
                    descString += " - ";
                    descString += complexityKey;
                    descString += " : ";
                    descString += jsonObject.getString(complexityKey);
                    descString += "<br>";
                }
                desc.setText(Html.fromHtml(descString));

            } else if (dataObject.get(key) instanceof JSONArray) {
                JSONArray array = dataObject.getJSONArray(key);
                String descString = "";

                for (int i = 0; i < array.length(); i++) {
                    descString += " - ";
                    descString += array.getString(i);
                    descString += "<br>";
                }
                desc.setText(Html.fromHtml(descString));

            } else if (dataObject.get(key) instanceof String) {
                desc.setText(Html.fromHtml(dataObject.getString(key)));
            }

            rootView.addView(descView);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:fr.haploid.webservices.WebServicesHelper.java

protected static synchronized WebServicesResponseData downloadFromServer(String url, JSONObject params,
        String type) {//from  ww w . ja v a2 s  .c  o  m

    int responseCode = 9999;

    StringBuffer buffer = new StringBuffer();

    Uri.Builder builder = new Uri.Builder();
    builder.encodedPath(url);

    JSONArray namesOfParams = params.names();

    for (int i = 0; i < namesOfParams.length(); i++) {
        try {
            String param = namesOfParams.getString(i);
            builder.appendQueryParameter(param, params.get(param).toString());
        } catch (JSONException e) {
            return new WebServicesResponseData("JSONException " + e.toString(), responseCode, false);
        }
    }

    URL urlBuild;

    try {
        urlBuild = new URL(builder.build().toString());
    } catch (MalformedURLException e) {
        return new WebServicesResponseData("MalformedURLException " + e.toString(), responseCode, false);
    }

    try {
        HttpURLConnection urlConnection = (HttpURLConnection) urlBuild.openConnection();
        try {
            urlConnection.setRequestMethod(type);
        } catch (ProtocolException e) {
            return new WebServicesResponseData("ProtocolException " + e.toString(), responseCode, false);
        }

        urlConnection.connect();
        responseCode = urlConnection.getResponseCode();
        if (responseCode < 400) {
            InputStream inputStream = urlConnection.getInputStream();
            if (inputStream == null) {
                return new WebServicesResponseData(null, responseCode, false);
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                return new WebServicesResponseData(null, responseCode, false);
            }
        }
    } catch (IOException e) {
        return new WebServicesResponseData("IOException " + e.toString(), responseCode, false);
    }
    return new WebServicesResponseData(buffer.toString(), responseCode, true);
}