Example usage for org.json JSONArray get

List of usage examples for org.json JSONArray get

Introduction

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

Prototype

public Object get(int index) throws JSONException 

Source Link

Document

Get the object value associated with an index.

Usage

From source file:org.loklak.api.iot.AbstractPushServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query post = RemoteAccess.evaluate(request);
    String remoteHash = Integer.toHexString(Math.abs(post.getClientHost().hashCode()));

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;/*from w  w  w  .j  ava2 s  .  c  om*/
    }

    String url = post.get("url", "");
    if (url == null || url.length() == 0) {
        response.sendError(400, "your request does not contain an url to your data object");
        return;
    }
    String screen_name = post.get("screen_name", "");
    if (screen_name == null || screen_name.length() == 0) {
        response.sendError(400, "your request does not contain required screen_name parameter");
        return;
    }

    JSONObject map;
    String jsonString = "";
    try {
        jsonString = new String(ClientConnection.download(url), StandardCharsets.UTF_8);
        map = new JSONObject(jsonString);
    } catch (Exception e) {
        response.sendError(400, "error reading json file from url");
        return;
    }

    // validation phase
    ProcessingReport report = this.validator.validate(jsonString);
    if (!report.isSuccess()) {
        response.sendError(400,
                "json does not conform to schema : " + this.getValidatorSchema().name() + "\n" + report);
        return;
    }

    // conversion phase
    Object extractResults = extractMessages(map);
    JSONArray messages;
    if (extractResults instanceof JSONArray) {
        messages = (JSONArray) extractResults;
    } else if (extractResults instanceof JSONObject) {
        messages = new JSONArray();
        messages.put((JSONObject) extractResults);
    } else {
        throw new IOException("extractMessages must return either a List or a Map. Get "
                + (extractResults == null ? "null" : extractResults.getClass().getCanonicalName())
                + " instead");
    }
    JSONArray convertedMessages = this.converter.convert(messages);

    PushReport nodePushReport = new PushReport();
    ObjectWriter ow = new ObjectMapper().writerWithDefaultPrettyPrinter();
    // custom treatment for each message
    for (int i = 0; i < messages.length(); i++) {
        JSONObject message = (JSONObject) convertedMessages.get(i);
        message.put("source_type", this.getSourceType().toString());
        message.put("location_source", LocationSource.USER.name());
        message.put("place_context", PlaceContext.ABOUT.name());
        if (message.get("text") == null) {
            message.put("text", "");
        }

        // append rich-text attachment
        String jsonToText = ow.writeValueAsString(messages.get(i));
        message.put("text", message.get("text") + MessageEntry.RICH_TEXT_SEPARATOR + jsonToText);
        customProcessing(message);

        if (message.get("mtime") == null) {
            String existed = PushServletHelper.checkMessageExistence(message);
            // message known
            if (existed != null) {
                messages.remove(i);
                nodePushReport.incrementKnownCount(existed);
                continue;
            }
            // updated message -> save with new mtime value
            message.put("mtime", Long.toString(System.currentTimeMillis()));
        }

        try {
            message.put("id_str", PushServletHelper.computeMessageId(message, getSourceType()));
        } catch (Exception e) {
            DAO.log("Problem computing id : " + e.getMessage());
        }
    }
    try {
        PushReport savingReport = PushServletHelper.saveMessagesAndImportProfile(convertedMessages,
                jsonString.hashCode(), post, getSourceType(), screen_name);
        nodePushReport.combine(savingReport);
    } catch (IOException e) {
        response.sendError(404, e.getMessage());
        return;
    }
    String res = PushServletHelper.buildJSONResponse(post.get("callback", ""), nodePushReport);

    post.setResponse(response, "application/javascript");
    response.getOutputStream().println(res);
    DAO.log(request.getServletPath() + " -> records = " + nodePushReport.getRecordCount() + ", new = "
            + nodePushReport.getNewCount() + ", known = " + nodePushReport.getKnownCount() + ", error = "
            + nodePushReport.getErrorCount() + ", from host hash " + remoteHash);
}

From source file:com.norman0406.slimgress.API.Knobs.Knobs.java

protected static List<Integer> getIntArray(JSONObject json, String key) throws JSONException {
    JSONArray jsonArray = json.getJSONArray(key);
    List<Integer> ret = new ArrayList<Integer>();
    for (int i = 0; i < jsonArray.length(); i++) {
        Object obj = jsonArray.get(i);
        if (obj instanceof Integer)
            ret.add((Integer) obj);
    }//w ww.ja va  2  s .  c  o  m
    return ret;
}

From source file:oculus.aperture.common.JSONProperties.java

@Override
public Iterable<Object> getObjects(String key) {
    try {// w ww . ja  va 2 s. c om
        final JSONArray array = obj.getJSONArray(key);

        return new Iterable<Object>() {
            @Override
            public Iterator<Object> iterator() {
                return new Iterator<Object>() {
                    private final int n = array.length();
                    private int i = 0;

                    @Override
                    public boolean hasNext() {
                        return n > i;
                    }

                    @Override
                    public Object next() {
                        try {
                            return (n > i) ? array.get(i++) : null;
                        } catch (JSONException e) {
                            return null;
                        }
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };

    } catch (JSONException e) {
        return EmptyIterable.instance();
    }
}

From source file:io.cslinmiso.line.utils.Utility.java

public static List toList(JSONArray array) throws JSONException {
    List list = new ArrayList();
    for (int i = 0; i < array.length(); i++) {
        list.add(fromJson(array.get(i)));
    }//from   ww  w . ja v  a2  s .c o  m
    return list;
}

From source file:net.majorkernelpanic.spydroid.api.RequestHandler.java

/**
 * Executes a batch of requests and returns all the results
 * @param request Contains a json containing one or more requests
 * @return A JSON to send back//  w w  w .ja va  2  s  .com
 */
static public String handle(String request) {
    StringBuilder response = new StringBuilder();
    JSONTokener tokener = new JSONTokener(request);

    try {
        Object token = tokener.nextValue();

        response.append("{");

        // More than one request to execute
        if (token instanceof JSONArray) {
            JSONArray array = (JSONArray) token;
            for (int i = 0; i < array.length(); i++) {
                JSONObject object = (JSONObject) array.get(i);
                response.append("\"" + object.getString("action") + "\":");
                exec(object, response);
                if (i != array.length() - 1)
                    response.append(",");
            }
            // Only One request
        } else if (token instanceof JSONObject) {
            JSONObject object = (JSONObject) token;
            response.append("\"" + object.getString("action") + "\":");
            exec(object, response);
        }

        response.append("}");

    } catch (Exception e) {
        // Pokemon, gotta catch'em all !
        Log.e(TAG, "Invalid request: " + request);
        e.printStackTrace();
        return "INVALID REQUEST";
    }

    Log.d(TAG, "Request: " + request);
    Log.d(TAG, "Answer: " + response.toString());

    return response.toString();
}

From source file:sandeep.kb.android.remote.android.AndroidWebDriver.java

private List<Object> convertJsonArrayToList(final JSONArray json) {
    List<Object> toReturn = Lists.newArrayList();
    for (int i = 0; i < json.length(); i++) {
        try {// w w w  .  java2  s  . c  o m
            toReturn.add(convertJsonToJavaObject(json.get(i)));
        } catch (JSONException e) {
            throw new RuntimeException("Failed to parse JSON: " + json.toString(), e);
        }
    }
    return toReturn;
}

From source file:sandeep.kb.android.remote.android.AndroidWebDriver.java

private List<Object> convertJsonArray2List(JSONArray arr) throws JSONException {
    List<Object> list = new ArrayList<Object>();
    for (int i = 0; i < arr.length(); i++) {
        list.add(processJsonObject(arr.get(i)));
    }/*w  ww  .j a  v a 2 s  .  c o  m*/
    return list;
}

From source file:com.mm.yamingapp.core.MethodDescriptor.java

/**
 * Converts a parameter from JSON into a Java Object.
 * //from   ww w .  j av a2  s .c  o  m
 * @return TODO
 */
// TODO(damonkohler): This signature is a bit weird (auto-refactored). The obvious alternative
// would be to work on one supplied parameter and return the converted parameter. However, that's
// problematic because you lose the ability to call the getXXX methods on the JSON array.
@VisibleForTesting
static Object convertParameter(final JSONArray parameters, int index, Type type)
        throws JSONException, RpcError {
    try {
        // We must handle null and numbers explicitly because we cannot magically cast them. We
        // also need to convert implicitly from numbers to bools.
        if (parameters.isNull(index)) {
            return null;
        } else if (type == Boolean.class) {
            try {
                return parameters.getBoolean(index);
            } catch (JSONException e) {
                return new Boolean(parameters.getInt(index) != 0);
            }
        } else if (type == Long.class) {
            return parameters.getLong(index);
        } else if (type == Double.class) {
            return parameters.getDouble(index);
        } else if (type == Integer.class) {
            return parameters.getInt(index);
        } else {
            // Magically cast the parameter to the right Java type.
            return ((Class<?>) type).cast(parameters.get(index));
        }
    } catch (ClassCastException e) {
        throw new RpcError(
                "Argument " + (index + 1) + " should be of type " + ((Class<?>) type).getSimpleName() + ".");
    }
}

From source file:com.facebook.android.FieldsConnectionsDialog.java

public void sortConnections(JSONArray jsonConnectionsArray) {
    this.connectionsArray = new ArrayList<String>(jsonConnectionsArray.length());
    for (int i = 0; i < jsonConnectionsArray.length(); i++) {
        try {/* w ww.j av  a  2 s. c o  m*/
            this.connectionsArray.add(jsonConnectionsArray.get(i).toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    Collections.sort(this.connectionsArray);
}

From source file:org.protorabbit.json.DefaultSerializer.java

@SuppressWarnings("unchecked")
private Object genericDeserialize(Object o, Object targetObject, String key) throws JSONException {

    if (o instanceof JSONObject) {
        JSONObject jo = (JSONObject) o;/*from   ww  w  .  j  a v a 2s. c  om*/
        Map<String, Object> jaoo = new HashMap<String, Object>();

        // only add if we are not top level
        if (targetObject != null) {
            addValue(targetObject, jaoo, key);
        }
        Iterator<String> it = jo.keys();

        while (it.hasNext()) {
            String k = it.next();
            Object value = jo.get(k);
            genericDeserialize(value, jaoo, k);
        }
        // if we are the top level object return self
        if (targetObject == null) {
            return jaoo;
        }

    } else if (o instanceof JSONArray) {

        JSONArray ja = (JSONArray) o;

        List<Object> jal = new ArrayList<Object>();

        // only add if we are not top level
        if (targetObject != null) {
            addValue(targetObject, jal, key);
        }
        for (int i = 0; i < ja.length(); i++) {
            Object jao = ja.get(i);
            genericDeserialize(jao, jal, null);
        }
        // if we are the top level object return self
        if (targetObject == null) {
            return jal;
        }
        // primitives
    } else if (o instanceof Date) {
        Object value = ((Date) o).getTime();
        addValue(targetObject, value, key);
    } else {
        addValue(targetObject, o, key);
    }
    return null;
}