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:samurai.geeft.android.geeft.utilities.GCM.MyGcmListenerService.java

private void parseCostum(String custom) {
    try {//from ww  w. j a va  2s  .  c om
        JSONObject obj = new JSONObject(custom);
        JSONArray array = obj.getJSONArray("custom");
        key = array.getInt(0);
        geeftId = array.getString(1);
        docUserId = array.getString(2);

        Log.d(TAG, "key: " + key);
        Log.d(TAG, "geeftId:" + geeftId);
        Log.d(TAG, "doc_id: " + docUserId);
        if (docUserId.equals(""))
            docUserId = null;
        //} catch (org.json.JSONException t) {
    } catch (Exception t) {
        Log.e(TAG, "Could not parse malformed JSON: \"" + custom + "\"");
        //startMainActivity();
    }
}

From source file:de.kp.ames.web.function.role.RoleLCM.java

/**
 * A helper method to create a set of associations classified
 * by ResponsibleFor//from  w  w w.  j  a  v a 2 s .c  o m
 * 
 * @param ro
 * @param jNamespaces
 * @return
 * @throws Exception
 */
private List<AssociationImpl> setResponsibility(RegistryObjectImpl ro, JSONArray jNamespaces) throws Exception {

    /*
     * Retrieve existing responsibilities (associations)
     */
    JaxrDQM dqm = new JaxrDQM(jaxrHandle);

    String sqlString = JaxrSQL.getSQLAssociations_ResponsibleFor(ro.getId());
    List<AssociationImpl> associations = dqm.getAssociationsByQuery(sqlString);

    /*
     * Retrieve list of references to namespaces provides
     */
    ArrayList<String> folders = new ArrayList<String>();
    for (int i = 0; i < jNamespaces.length(); i++) {
        folders.add(jNamespaces.getString(i));
    }

    if ((associations.size() == 0) && (folders.size() == 0))
        return new ArrayList<AssociationImpl>();

    if (associations.size() > 0) {
        /* 
         * Delete all responsibilities registered for this responsible
         */
        ArrayList<Key> objectsToDelete = new ArrayList<Key>();
        for (AssociationImpl association : associations) {
            objectsToDelete.add(association.getKey());
        }

        deleteObjects(objectsToDelete);

    }

    /*
     * Create associations
     */
    List<AssociationImpl> responsibilities = createAssociations_ResponsibleFor(folders);
    ro.addAssociations(responsibilities);

    return responsibilities;

}

From source file:org.lafs.hdfs.LAFS.java

private FileStatus getStatusFromJSON(JSONArray ja, Path path) throws IOException {
    FileStatus stat;/*from w ww  . jav  a2s.  c  o m*/

    String flag;
    try {
        flag = ja.getString(0);

        boolean isDir = flag.equals("dirnode");

        JSONObject data = ja.getJSONObject(1);

        long mtime = 0L;
        if (data.has("metadata"))
            mtime = (long) data.getJSONObject("metadata").getJSONObject("tahoe").getDouble("linkmotime");

        // each file consists of 1 block of a size the entire length of the file

        long size = 0L;

        if (!isDir) {
            try {
                size = (long) data.getInt("size");
            } catch (JSONException joe) {
                logger.warning("size was null");
            }
        }
        //else 
        //   size = data.getJSONObject("children").length();

        stat = new FileStatus(isDir ? 0 : size, isDir, 1, size, mtime, path);
    } catch (JSONException e) {
        logger.severe(ja.toString());
        throw new IOException(e.getMessage());
    }

    return stat;
}

From source file:org.lafs.hdfs.LAFS.java

@SuppressWarnings("unchecked")
@Override//w  w  w  .  j  ava 2s  .co m
public FileStatus[] listStatus(Path path) throws IOException {
    FileStatus[] ret = null;

    JSONArray ja = getJSONForPath(path);

    try {
        String flag = ja.getString(0);
        boolean isDir = flag.equals("dirnode");

        if (isDir) { // process directory
            String pathString = path.toString();
            if (!pathString.endsWith("/"))
                pathString = pathString + "/";

            JSONObject data = ja.getJSONObject(1);

            // get the status of each child
            ArrayList<FileStatus> stats = new ArrayList<>();
            JSONObject children = data.getJSONObject("children");
            Iterator<String> items = children.keys();
            while (items.hasNext()) {
                String name = items.next();

                FileStatus stat = getStatusFromJSON(children.getJSONArray(name), new Path(pathString + name));
                stats.add(stat);
            }

            ret = new FileStatus[stats.size()];
            ret = stats.toArray(ret);
        } else { // process a file   
            FileStatus stat = getStatusFromJSON(ja, path);
            ret = new FileStatus[1];
            ret[0] = stat;
        }

    } catch (JSONException e) {
        throw new IOException(e.getMessage());
    }

    return ret;
}

From source file:com.phonegap.plugins.childbrowser.ChildBrowser.java

/**
 * Executes the request and returns boolean.
 *
 * @param action          The action to execute.
 * @param args            JSONArry of arguments for the plugin.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return                boolean//  www. j  a  va 2 s  . c  o  m
 */
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    Log.d(LOG_TAG, action);
    String result = "";

    if (action.equals("showWebPage")) {
        Log.d(LOG_TAG, args.getString(0));
        Log.d(LOG_TAG, action);

        // If the ChildBrowser is already open then throw an error
        if (dialog != null && dialog.isShowing()) {
            callbackContext.error("ChildBrowser is already open");
        } else {
            this.callbackContext = callbackContext;
            result = this.showWebPage(args.getString(0), args.optJSONObject(1));

            if (result.length() > 0) {
                callbackContext.error(result);
            } else {
                JSONObject obj = new JSONObject();
                obj.put("type", BROWSER_OPENED);
                sendUpdate(obj, true);
            }
            Log.d(LOG_TAG, result);
        }
        return true;
    } else if (action.equals("close")) {
        closeDialog();

        JSONObject obj = new JSONObject();
        obj.put("type", CLOSE_EVENT);

        sendUpdate(obj, false);
        return true;
    } else if (action.equals("openExternal")) {
        result = this.openExternal(args.getString(0), args.optBoolean(1));
        if (result.length() > 0) {
            callbackContext.error(result);
        } else {
            JSONObject obj = new JSONObject();
            obj.put("type", OPEN_EXTERNAL_EVENT);
            sendUpdate(obj, true);
        }
        return true;
    }
    return false;
}

From source file:org.mixare.data.convert.TwitterDataProcessor.java

@Override
public List<Marker> load(String rawData, int taskId, int colour) throws JSONException {
    List<Marker> markers = new ArrayList<Marker>();
    JSONObject root = convertToJSON(rawData);
    JSONArray dataArray = root.getJSONArray("results");
    int top = Math.min(MAX_JSON_OBJECTS, dataArray.length());

    for (int i = 0; i < top; i++) {
        JSONObject jo = dataArray.getJSONObject(i);

        Marker ma = null;//w w w . j  a va 2  s. c  o m
        if (jo.has("geo")) {
            Double lat = null, lon = null;

            if (!jo.isNull("geo")) {
                JSONObject geo = jo.getJSONObject("geo");
                JSONArray coordinates = geo.getJSONArray("coordinates");
                lat = Double.parseDouble(coordinates.getString(0));
                lon = Double.parseDouble(coordinates.getString(1));
            } else if (jo.has("location")) {

                // Regex pattern to match location information
                // from the location setting, like:
                // iPhone: 12.34,56.78
                // T: 12.34,56.78
                // 12.34,56.78

                Pattern pattern = Pattern.compile("\\D*([0-9.]+),\\s?([0-9.]+)");
                Matcher matcher = pattern.matcher(jo.getString("location"));

                if (matcher.find()) {
                    lat = Double.parseDouble(matcher.group(1));
                    lon = Double.parseDouble(matcher.group(2));
                }
            }
            if (lat != null) {
                Log.v(MixView.TAG, "processing Twitter JSON object");
                String user = jo.getString("from_user");
                String url = "http://twitter.com/" + user;

                //no ID is needed, since identical tweet by identical user may be safely merged into one.
                ma = new SocialMarker("", user + ": " + jo.getString("text"), lat, lon, 0, url, taskId, colour);
                markers.add(ma);
            }
        }
    }
    return markers;
}

From source file:com.google.enterprise.connector.ldap.JsonDocument.java

private static void extractAttributes(JSONObject jo, ImmutableMap.Builder<String, List<Value>> mapBuilder,
        String key) throws IllegalAccessError {
    JSONArray ja;
    try {// w  w  w.j  av a 2 s  .  co m
        ja = jo.getJSONArray(key);
    } catch (JSONException e) {
        LOG.warning("Skipping: " + key);
        return;
    }
    ImmutableList.Builder<Value> builder = new ImmutableList.Builder<Value>();
    for (int i = 0; i < ja.length(); i++) {
        String v;
        try {
            v = ja.getString(i);
        } catch (JSONException e) {
            LOG.warning("Skipping: " + key + " value: " + i);
            continue;
        }
        builder.add(Value.getStringValue(v));
    }
    ImmutableList<Value> l = builder.build();
    if (l.size() > 0) {
        mapBuilder.put(key, l);
    }
    return;
}

From source file:com.qbcps.sifterclient.SifterReader.java

private String getFilterSlug() {
    String projDetailURL;/*from ww w  . jav  a  2 s .c  o  m*/
    int issuesPerPage;
    JSONArray status;
    JSONArray priority;
    int numStatuses;
    int numPriorities;
    boolean[] filterStatus;
    boolean[] filterPriority;
    try {
        JSONObject filters = mSifterHelper.getFiltersFile();
        if (filters.length() == 0)
            return "";
        issuesPerPage = filters.getInt(IssuesActivity.PER_PAGE);
        status = filters.getJSONArray(IssuesActivity.STATUS);
        priority = filters.getJSONArray(IssuesActivity.PRIORITY);
        numStatuses = status.length();
        numPriorities = priority.length();
        filterStatus = new boolean[numStatuses];
        filterPriority = new boolean[numPriorities];
        for (int i = 0; i < numStatuses; i++)
            filterStatus[i] = status.getBoolean(i);
        for (int i = 0; i < numPriorities; i++)
            filterPriority[i] = priority.getBoolean(i);
    } catch (Exception e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString());
        return "";
    }
    projDetailURL = "?" + IssuesActivity.PER_PAGE + "=" + issuesPerPage;
    projDetailURL += "&" + IssuesActivity.GOTO_PAGE + "=1";
    JSONObject statuses;
    JSONObject priorities;
    JSONArray statusNames;
    JSONArray priorityNames;
    try {
        JSONObject sifterJSONObject = mSifterHelper.getSifterFilters();
        statuses = sifterJSONObject.getJSONObject(IssuesActivity.STATUSES);
        priorities = sifterJSONObject.getJSONObject(IssuesActivity.PRIORITIES);
        statusNames = statuses.names();
        priorityNames = priorities.names();
    } catch (Exception e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString());
        return "";
    }
    try {
        String filterSlug = "&s=";
        for (int i = 0; i < numStatuses; i++) {
            if (filterStatus[i])
                filterSlug += String.valueOf(statuses.getInt(statusNames.getString(i))) + "-";
        }
        if (filterSlug.length() > 3) {
            filterSlug = filterSlug.substring(0, filterSlug.length() - 1);
            projDetailURL += filterSlug;
        }
        filterSlug = "&p=";
        for (int i = 0; i < numPriorities; i++) {
            if (filterPriority[i])
                filterSlug += String.valueOf(priorities.getInt(priorityNames.getString(i))) + "-";
        }
        if (filterSlug.length() > 3) {
            filterSlug = filterSlug.substring(0, filterSlug.length() - 1);
            projDetailURL += filterSlug;
        }
    } catch (JSONException e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString());
        return "";
    }
    return projDetailURL;
}

From source file:com.qbcps.sifterclient.SifterReader.java

/** check if SifterAPI returned error
 * {"error":"Invalid Account","detail":"Please correct the account subdomain."}
* {"error":"Invalid Token","detail":"Please make sure that you are using the correct token."} */
private boolean getSifterError(JSONObject sifterJSONObject) {
    try {//from   w w  w .j a  v  a2s.c om
        JSONArray sifterJSONObjFieldNames = sifterJSONObject.names();
        int numKeys = sifterJSONObjFieldNames.length();
        if (numKeys == 2 && LOGIN_ERROR.equals(sifterJSONObjFieldNames.getString(0))
                && LOGIN_DETAIL.equals(sifterJSONObjFieldNames.getString(1))) {
            mLoginError = sifterJSONObject;
            return true;
        }
        mLoginError.put(LOGIN_ERROR, getResources().getString(R.string.token_accepted));
        mLoginError.put(LOGIN_DETAIL, getResources().getString(R.string.token_accepted_msg));
        return false;
    } catch (NotFoundException e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString()); // return true below
    } catch (JSONException e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString()); // return true below
    }
    return true;
}

From source file:com.solace.samples.cloudfoundry.javaapp.controller.SolaceController.java

@PostConstruct
public void init() {

    // Connect to Solace
    logger.info("************* Init Called ************");

    String vcapServices = System.getenv("VCAP_SERVICES");
    logger.info(vcapServices);//  w  w  w .  j  a v a2 s .c o m

    // Need to parse the Solace HOST from VCAP Services
    if (vcapServices == null || vcapServices.equals("") || vcapServices.equals("{}")) {
        logger.error("The VCAP_SERVICES variable wasn't set in the environment. Aborting connection.");
        logger.info("************* Aborting Solace initialization!! ************");
        return;
    }

    JSONObject vcapServicesJson = new JSONObject(vcapServices);

    JSONArray solMessagingArray = vcapServicesJson.getJSONArray("solace-messaging");

    if (solMessagingArray == null) {
        logger.error("Did not find Solace provided messaging service \"solace-messaging\"");
        logger.info("************* Aborting Solace initialization!! ************");
        return;
    }

    logger.info("Number of provided bindings: " + solMessagingArray.length());

    // Get the first Solace credentials from the array
    JSONObject solaceCredentials = null;
    if (solMessagingArray.length() > 0) {
        solaceCredentials = solMessagingArray.getJSONObject(0);
        if (solaceCredentials != null) {
            solaceCredentials = solaceCredentials.getJSONObject("credentials");
        }
    }

    if (solaceCredentials == null) {
        logger.error("Did not find Solace messaging service credentials");
        logger.info("************* Aborting Solace initialization!! ************");
        return;
    }

    logger.info("Solace client initializing and using Credentials: " + solaceCredentials.toString(2));

    final JCSMPProperties properties = new JCSMPProperties();

    // The host property is in a json array. Two hosts are provided in a
    // High Availability environment,
    // one for the primary router and one for the backup.
    JSONArray hostsArray = solaceCredentials.getJSONArray("smfHosts");

    // Make a host list (for HA and non HA)
    String host = "";
    for (int i = 0; i < hostsArray.length(); i++) {
        String newHostEntry = hostsArray.getString(i);
        if (i > 0)
            host += ",";

        host += newHostEntry;
    }

    logger.info("Using host " + host);
    properties.setProperty(JCSMPProperties.HOST, host);

    // Must be using HA to have more than 1 host.
    if (hostsArray.length() > 1) {

        // A Sample for High Availability automatic reconnects.
        JCSMPChannelProperties channelProperties = (JCSMPChannelProperties) properties
                .getProperty(JCSMPProperties.CLIENT_CHANNEL_PROPERTIES);
        channelProperties.setConnectRetries(1);
        channelProperties.setReconnectRetries(5);
        channelProperties.setReconnectRetryWaitInMillis(3000);
        channelProperties.setConnectRetriesPerHost(20);
    }

    properties.setProperty(JCSMPProperties.VPN_NAME, solaceCredentials.getString("msgVpnName"));
    properties.setProperty(JCSMPProperties.USERNAME, solaceCredentials.getString("clientUsername"));
    properties.setProperty(JCSMPProperties.PASSWORD, solaceCredentials.getString("clientPassword"));

    try {
        session = JCSMPFactory.onlyInstance().createSession(properties);
        session.connect();
    } catch (Exception e) {
        logger.error("Error connecting and setting up session.", e);
        logger.info("************* Aborting Solace initialization!! ************");
        return;
    }

    try {
        final XMLMessageConsumer cons = session.getMessageConsumer(new SimpleMessageListener());
        cons.start();

        producer = session.getMessageProducer(new SimplePublisherEventHandler());

        logger.info("************* Solace initialized correctly!! ************");
    } catch (Exception e) {
        logger.error("Error creating the consumer and producer.", e);
    }
}