Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

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

Prototype

public JSONArray(Object array) throws JSONException 

Source Link

Document

Construct a JSONArray from an array

Usage

From source file:abelymiguel.miralaprima.GetHistory.java

/**
 * Processes requests for both HTTP/*from  w w  w.j a v  a2  s  .c  om*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        _con = Utils.getConnection();
        _stmt = _con.createStatement();
    } catch (URISyntaxException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        out = response.getWriter();
    } catch (IOException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.setContentType("text/javascript;charset=UTF-8");

    String country_code;
    int limit;
    String limitStr;
    country_code = request.getParameter("country_code");
    limitStr = request.getParameter("limit");

    if (limitStr != null) {
        limit = Integer.parseInt(limitStr);
    } else {
        limit = -1;
    }

    String json_str;
    JSONArray jsonArray = new JSONArray(this.getHistory(country_code, limit));
    json_str = jsonArray.toString();

    String jsonpCallback = request.getParameter("callback");
    if (jsonpCallback != null) {
        out.write(jsonpCallback + "(" + json_str + ")");
    } else {
        out.println(json_str);
    }

    try {
        _con.close();
        _stmt.close();
        _rs.close();
    } catch (SQLException ex) {
        Logger.getLogger(GetPrima.class.getName()).log(Level.SEVERE, null, ex);
    }
    out.close();
}

From source file:at.alladin.rmbt.db.QoSTestResult.java

/**
 * // www  .  j a v a 2s. c  o  m
 * @return
 * @throws JSONException 
 */
public JSONObject toJson(UuidType exportType) throws JSONException {
    JSONObject json = new JSONObject();
    json.put("uid", getUid());
    json.put("test_type", getTestType());
    json.put("result", new JSONObject(getResults()));
    json.put("test_desc", getTestDescription());
    json.put("success_count", getSuccessCounter());
    json.put("failure_count", getFailureCounter());
    json.put("test_summary", String.valueOf(getTestSummary()));

    if (resultKeyMap != null && resultKeyMap.size() > 0) {
        json.put("test_result_keys", new JSONArray(resultKeyMap.keySet()));
        json.put("test_result_key_map", new JSONObject(resultKeyMap));
    }

    if (exportType.equals(UuidType.TEST_UUID)) {
        json.put("nn_test_uid", getQoSTestObjectiveId()); // TODO: remove backwards compatibility (<= 2.0.28/20028)
        json.put("qos_test_uid", getQoSTestObjectiveId());
        json.put("test_uid", getTestUid());
    }
    return json;
}

From source file:au.com.borner.salesforce.client.rest.domain.ContainerAsyncRequest.java

public List<CompilerError> getCompilerErrors() {
    // CompilerErrors is a JSON Array wrapped in a String ..... :-(
    String compilerErrors = getString("CompilerErrors");
    JSONArray jsonArray = new JSONArray(compilerErrors);
    List<CompilerError> result = new ArrayList<CompilerError>(jsonArray.length());
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        result.add(new CompilerError(jsonObject.toString()));
    }//from  w ww  .j ava  2 s .  com
    return result;
}

From source file:abelymiguel.miralaprima.GetPrima.java

/**
 * Processes requests for both HTTP/* w ww .j av  a2  s. co m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        _con = Utils.getConnection();
        _stmt = _con.createStatement();

    } catch (URISyntaxException ex) {
        Logger.getLogger(GetPrima.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(GetPrima.class.getName()).log(Level.SEVERE, null, ex);
    }
    PrintWriter out = response.getWriter();
    response.setContentType("text/javascript;charset=UTF-8");

    String country_code;
    country_code = request.getParameter("country_code");

    JSONObject jsonObject;
    JSONArray jsonArray;
    String json_str;
    if (country_code != null) {
        jsonObject = new JSONObject(this.getCountry(country_code));
        json_str = jsonObject.toString();
    } else {
        jsonArray = new JSONArray(this.getAllCountries());
        json_str = jsonArray.toString();
    }

    String jsonpCallback = request.getParameter("callback");
    if (jsonpCallback != null) {
        out.write(jsonpCallback + "(" + json_str + ")");
    } else {
        out.println(json_str);
    }
    try {
        _con.close();
        _stmt.close();
        _rs.close();
    } catch (SQLException ex) {
        Logger.getLogger(GetPrima.class.getName()).log(Level.SEVERE, null, ex);
    }
    out.close();
}

From source file:au.com.borner.salesforce.client.rest.domain.AbstractJSONArrayAdaptor.java

public AbstractJSONArrayAdaptor(String string) throws JSONException {
    super("{}");
    this.jsonArray = new JSONArray(string);
}

From source file:abelymiguel.miralaprima.GetMoza.java

/**
 * Processes requests for both HTTP/* www  . j  a  va 2s . com*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html;charset=UTF-8");
    try {
        _con = Utils.getConnection();
        _stmt = _con.createStatement();
    } catch (URISyntaxException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    }

    PrintWriter out = null;
    try {
        out = response.getWriter();
    } catch (IOException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.setContentType("text/javascript;charset=UTF-8");

    String country_code;
    int limit;
    String limitStr;
    country_code = request.getParameter("country_code");
    limitStr = request.getParameter("limit");

    if (limitStr != null) {
        limit = Integer.parseInt(limitStr);
    } else {
        limit = -1;
    }

    String json_str;
    JSONArray jsonArray = new JSONArray(this.searchInDB(country_code, limit));
    json_str = jsonArray.toString();

    String jsonpCallback = request.getParameter("callback");
    if (jsonpCallback != null) {
        out.write(jsonpCallback + "(" + json_str + ")");
    } else {
        out.println(json_str);
    }

    try {
        _con.close();
        _stmt.close();
        _rs.close();
    } catch (SQLException ex) {
        Logger.getLogger(GetPrima.class.getName()).log(Level.SEVERE, null, ex);
    }
    out.close();
}

From source file:at.alladin.rmbt.db.QoSTestObjective.java

@SuppressWarnings("unchecked")
public String toHtml() {
    StringBuilder sb = new StringBuilder();
    sb.append("<h3>QoS-Test (uid: " + getUid() + ", test_class: " + getTestClass() + ")</h3>");
    if (getObjective() != null) {
        try {// w ww . j  a v a2  s  . co  m
            JSONObject objectives = new JSONObject(getObjective());
            Iterator<String> keys = objectives.keys();
            sb.append("<b>Test objectives (as plain text):</b> <ul>");
            while (keys.hasNext()) {
                String key = keys.next();
                sb.append("<li><i>" + key + "</i>: " + objectives.optString(key) + "</li>");
            }
            sb.append("</ul>");
            sb.append("<b>Test objectives (as hstore representation):</b> "
                    + Helperfunctions.json2hstore(objectives, null) + "<br><br>");
            if (testSummary != null) {
                sb.append("<b>Test summary (test_summary):</b> <a href=\"#"
                        + testSummary.replaceAll("[\\-\\+\\.\\^:,]", "_") + "\">" + testSummary
                        + "</a><br><br>");
            } else {
                sb.append("<b>Test summary (test_summary):</b> <i>NULL</i><br><br>");
            }
            if (testDescription != null) {
                sb.append("<b>Test description (test_desc):</b> <a href=\"#"
                        + testDescription.replaceAll("[\\-\\+\\.\\^:,]", "_") + "\">" + testDescription
                        + "</a><br><br>");
            } else {
                sb.append("<b>Test description (test_desc):</b> <i>NULL</i><br><br>");
            }
        } catch (JSONException e) {
            sb.append(
                    "<b><i>incorrect test objectives format:</i></b><ul><li>" + getObjective() + "</li></ul>");
            e.printStackTrace();
        }
    } else {
        sb.append("<b><i>no objectives set for this test</i></b>");
    }

    sb.append("<b>Expected test results (as hstore representation):</b><ul>");
    if (getResults() != null) {
        JSONArray resultsJson;
        try {
            resultsJson = new JSONArray(getResults());
            for (int i = 0; i < resultsJson.length(); i++) {
                try {
                    final JSONObject expected = resultsJson.getJSONObject(i);
                    sb.append("<li>" + Helperfunctions.json2htmlWithLinks(expected) + "</li>");
                } catch (Exception e) {
                    e.printStackTrace();
                    sb.append("<li>incorrect expected test result format</li>");
                }
            }
        } catch (JSONException e1) {
            sb.append("<li>incorrect expected test result format</li>");
        }
    } else {
        sb.append("<li><i>No expected results set for this test</i></li>");
    }
    sb.append("</ul>");
    return sb.toString();
}

From source file:com.clevertrail.mobile.findtrail.Activity_FindTrail_ByName.java

private int submitSearch() {
    JSONArray jsonArray = null;/*w ww  .  ja  v a 2 s .  com*/

    HttpURLConnection urlConnection = null;
    try {
        //api call to find trails by name
        String requestURL = "http://clevertrail.com/ajax/handleGetArticles.php";
        String sSearch = mActivity.sSearchText;
        sSearch = sSearch.replace(" ", "%20");
        sSearch = sSearch.replace("'", "\'");

        requestURL = requestURL.concat("?name=").concat(sSearch);

        URL url = new URL(requestURL);
        urlConnection = (HttpURLConnection) url.openConnection();

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        BufferedReader r = new BufferedReader(new InputStreamReader(in));
        String line;
        //did we get a match from clevertrail.com?
        if ((line = r.readLine()) != null) {
            jsonArray = new JSONArray(line);
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return R.string.error_contactingclevertrail;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        // could not connect to clevertrail.com
        e.printStackTrace();
        return R.string.error_contactingclevertrail;
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return R.string.error_corrupttrailinfo;
    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
    }

    //clear the static object that holds the trails
    Object_TrailList.clearTrails();
    if (jsonArray != null && jsonArray.length() > 0) {
        int len = jsonArray.length();
        try {
            //add each trail to the array of trails
            for (int i = 0; i < len && i < 20; ++i) {
                JSONObject trail = jsonArray.getJSONObject(i);
                Object_TrailList.addTrailWithJSON(trail);
            }
        } catch (JSONException e) {
            return R.string.error_corrupttrailinfo;
        }
    }

    //prepare the extras before starting the trail list activity
    int icon = R.drawable.ic_viewtrailtab_details_unselected;
    Intent i = new Intent(mActivity, Activity_ListTrails.class);
    i.putExtra("icon", icon);
    i.putExtra("title", mActivity.getString(R.string.title_foundtrails));
    mActivity.startActivity(i);

    return 0;
}

From source file:de.kp.ames.web.function.domain.model.ImageObject.java

/**
 * Create RegistryObject representation of ImageObject
 * /*from  w  w w. j  av  a  2s  .c o m*/
 * @param data
 * @return
 * @throws Exception
 */
public RegistryObjectImpl create(JSONObject jForm) throws Exception {

    /* 
     * Create extrinsic object that serves as a wrapper 
     * for the respective image
     */
    // 
    ExtrinsicObjectImpl eo = jaxrLCM.createExtrinsicObject();
    if (eo == null)
        throw new JAXRException("[ImageObject] Creation of ExtrinsicObject failed.");

    /* 
     * Identifier
     */
    String eid = JaxrIdentity.getInstance().getPrefixUID(FncConstants.IMAGE_PRE);

    eo.setLid(eid);
    eo.getKey().setId(eid);

    /* 
     * Home url
     */
    String home = jaxrHandle.getEndpoint().replace("/saml", "");
    eo.setHome(home);

    /* 
     * The document is actually transient and managed by the image cache
     */

    ImageCacheManager cacheManager = ImageCacheManager.getInstance();

    String key = jForm.getString(JsonConstants.J_KEY);
    DmsImage image = (DmsImage) cacheManager.getFromCache(key);

    if (image == null)
        throw new Exception("[ImageObject] Image with id <" + key + "> not found.");

    /*
     * Name & description
     */
    String name = jForm.has(RIM_NAME) ? jForm.getString(RIM_NAME) : null;
    String desc = jForm.has(RIM_DESC) ? jForm.getString(RIM_DESC) : null;

    name = (name == null) ? image.getName() : name;

    int pos = name.lastIndexOf(".");
    if (pos != -1)
        name = name.substring(0, pos);

    eo.setName(jaxrLCM.createInternationalString(name));

    desc = (desc == null) ? FncMessages.NO_DESCRIPTION_DESC : desc;
    eo.setDescription(jaxrLCM.createInternationalString(desc));

    /*
     * Classifications
     */
    JSONArray jClases = jForm.has(RIM_CLAS) ? new JSONArray(jForm.getString(RIM_CLAS)) : null;
    if (jClases != null) {

        List<ClassificationImpl> classifications = createClassifications(jClases);
        /*
         * Set composed object
         */
        eo.addClassifications(classifications);

    }

    /*
     * Mimetype & repository item
     */
    String mimetype = image.getMimetype();
    DataHandler handler = new DataHandler(FileUtil.createByteArrayDataSource(image.getBytes(), mimetype));

    eo.setMimeType(mimetype);
    eo.setRepositoryItem(handler);

    /*
     * Indicate as created
     */
    this.created = true;

    return eo;

}

From source file:ch.lom.clemens.android.bibliography.data.JSONWebConnector.java

public MCollection[] getCollections() {

    if (!isConnected()) {
        StartActivity.singleton.doAuthentication(StartActivity.MENDELEY_RETRIEVE_COLLECTIONS);
        return null;
    }/* w w  w. j a v  a  2 s . c o m*/

    MCollection[] collections = null;

    try {
        String strResponse = connect(
                "http://www.mendeley.com/oapi/library/collections?consumer_key=" + m_consumerkey);

        Log.i("MendeleyComm", strResponse);

        JSONArray jcols = new JSONArray(strResponse);

        collections = new MCollection[jcols.length()];

        for (int i = 0; i < jcols.length(); i++) {
            JSONObject collection = jcols.getJSONObject(i);

            collections[i] = new MCollection(null);

            collections[i].id = collection.getString("id");
            collections[i].name = collection.getString("name");
            collections[i].type = collection.getString("type");
            collections[i].size = collection.getInt("size");
        }
    } catch (Exception e) {
        Log.e("MendeleyConnector", "Got exception when parsing online collection data");
        Log.e("MendeleyConnector", e.getClass().getSimpleName() + ": " + e.getMessage());
    }
    return collections;

}