Example usage for org.json JSONArray isNull

List of usage examples for org.json JSONArray isNull

Introduction

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

Prototype

public boolean isNull(int index) 

Source Link

Document

Determine if the value is null.

Usage

From source file:com.sonoport.freesound.response.mapping.PagingResponseMapper.java

@Override
public List<I> map(final JSONObject source) {
    final List<I> items = new LinkedList<>();
    final JSONArray resultsArray = extractFieldValue(source, "results", JSONArray.class);

    if (resultsArray != null) {
        for (int i = 0; i < resultsArray.length(); i++) {
            if (!resultsArray.isNull(i)) {
                final JSONObject jsonObject = resultsArray.getJSONObject(i);
                if ((jsonObject != null)) {
                    final I item = itemMapper.map(jsonObject);
                    items.add(item);//from w w  w  .j av  a  2s.  c om
                }
            }
        }
    }

    return items;
}

From source file:ch.icclab.cyclops.persistence.client.InfluxDBClient.java

public TSDBData getData(String query) {
    JSONArray resultArray;
    JSONObject resultObj;//from  ww  w  .j av a 2 s  .  c  o  m
    TSDBData dataObj = null;
    Representation output;
    ObjectMapper mapper = new ObjectMapper();

    Client client = new Client(Protocol.HTTP);
    ClientResource cr = new ClientResource(url);

    cr.addQueryParameter("q", query);
    cr.addQueryParameter("u", username);
    cr.addQueryParameter("p", password);
    cr.get(MediaType.APPLICATION_JSON);
    output = cr.getResponseEntity();

    try {
        resultArray = new JSONArray(output.getText());
        if (!resultArray.isNull(0)) {
            resultObj = new JSONObject();
            resultObj = (JSONObject) resultArray.get(0);
            dataObj = mapper.readValue(resultObj.toString(), TSDBData.class);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return dataObj;
}

From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java

/**
 * Uploads the specified file to the server URL provided using an HTTP multipart request.
 * @param source        Full path of the file on the file system
 * @param target        URL of the server to receive the file
 * @param args          JSON Array of args
 * @param callbackContext    callback id for optional progress reports
 *
 * args[2] fileKey       Name of file request parameter
 * args[3] fileName      File name to be used on server
 * args[4] mimeType      Describes file content type
 * args[5] params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 *///from  w w w .  ja v a2s.  co  m
private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    // Setup the options
    final String mimeType = getArgument(args, 4, "image/jpeg");
    final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5);
    final boolean trustEveryone = args.optBoolean(6);
    // Always use chunked mode unless set to false as per API
    final boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
    // Look for headers on the params map for backwards compatibility with older Cordova versions.
    final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers")
            : args.optJSONObject(8);
    final String objectId = args.getString(9);
    final String httpMethod = getArgument(args, 10, "POST");

    final CordovaResourceApi resourceApi = webView.getResourceApi();

    Log.d(LOG_TAG, "mimeType: " + mimeType);
    Log.d(LOG_TAG, "params: " + params);
    Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
    Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
    Log.d(LOG_TAG, "headers: " + headers);
    Log.d(LOG_TAG, "objectId: " + objectId);
    Log.d(LOG_TAG, "httpMethod: " + httpMethod);

    final Uri targetUri = resourceApi.remapUri(Uri.parse(target));
    // Accept a path or a URI for the source.
    Uri tmpSrc = Uri.parse(source);
    final Uri sourceUri = resourceApi
            .remapUri(tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source)));

    int uriType = CordovaResourceApi.getUriType(targetUri);
    final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
    if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0);
        Log.e(LOG_TAG, "Unsupported URI: " + targetUri);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
        return;
    }

    final RequestContext context = new RequestContext(source, target, callbackContext);
    synchronized (activeRequests) {
        activeRequests.put(objectId, context);
    }

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            if (context.aborted) {
                return;
            }
            HttpURLConnection conn = null;
            HostnameVerifier oldHostnameVerifier = null;
            SSLSocketFactory oldSocketFactory = null;
            int totalBytes = 0;
            int fixedLength = -1;
            try {
                // Create return object
                PSFileUploadResult result = new PSFileUploadResult();
                PSFileProgressResult progress = new PSFileProgressResult();

                //------------------ CLIENT REQUEST
                // Open a HTTP connection to the URL based on protocol
                conn = resourceApi.createHttpConnection(targetUri);
                if (useHttps && trustEveryone) {
                    // Setup the HTTPS connection class to trust everyone
                    HttpsURLConnection https = (HttpsURLConnection) conn;
                    oldSocketFactory = trustAllHosts(https);
                    // Save the current hostnameVerifier
                    oldHostnameVerifier = https.getHostnameVerifier();
                    // Setup the connection not to verify hostnames
                    https.setHostnameVerifier(DO_NOT_VERIFY);
                }

                // Allow Inputs
                conn.setDoInput(true);

                // Allow Outputs
                conn.setDoOutput(true);

                // Don't use a cached copy.
                conn.setUseCaches(false);

                // Use a post method.
                conn.setRequestMethod(httpMethod);
                conn.setRequestProperty("Content-Type", mimeType);

                // Set the cookies on the response
                String cookie = CookieManager.getInstance().getCookie(target);
                if (cookie != null) {
                    conn.setRequestProperty("Cookie", cookie);
                }

                // Handle the other headers
                if (headers != null) {
                    addHeadersToRequest(conn, headers);
                }

                // Get a input stream of the file on the phone
                OpenForReadResult readResult = resourceApi.openForRead(sourceUri);

                if (readResult.length >= 0) {
                    fixedLength = (int) readResult.length;
                    progress.setLengthComputable(true);
                    progress.setTotal(fixedLength);
                }
                Log.d(LOG_TAG, "Content Length: " + fixedLength);
                // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices.
                // http://code.google.com/p/android/issues/detail?id=3164
                // It also causes OOM if HTTPS is used, even on newer devices.
                boolean useChunkedMode = chunkedMode
                        && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps);
                useChunkedMode = useChunkedMode || (fixedLength == -1);

                if (useChunkedMode) {
                    conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);
                    // Although setChunkedStreamingMode sets this header, setting it explicitly here works
                    // around an OutOfMemoryException when using https.
                    conn.setRequestProperty("Transfer-Encoding", "chunked");
                } else {
                    conn.setFixedLengthStreamingMode(fixedLength);
                }

                conn.connect();

                OutputStream sendStream = null;
                try {
                    sendStream = conn.getOutputStream();
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.currentOutputStream = sendStream;
                    }
                    //We don't want to change encoding, we just want this to write for all Unicode.

                    // create a buffer of maximum size
                    int bytesAvailable = readResult.inputStream.available();
                    int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                    byte[] buffer = new byte[bufferSize];

                    // read file and write it into form...
                    int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                    long prevBytesRead = 0;
                    while (bytesRead > 0) {
                        result.setBytesSent(totalBytes);
                        sendStream.write(buffer, 0, bytesRead);
                        totalBytes += bytesRead;
                        if (totalBytes > prevBytesRead + 102400) {
                            prevBytesRead = totalBytes;
                            Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");
                        }
                        bytesAvailable = readResult.inputStream.available();
                        bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                        bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                        // Send a progress event.
                        progress.setLoaded(totalBytes);
                        PluginResult progressResult = new PluginResult(PluginResult.Status.OK,
                                progress.toJSONObject());
                        progressResult.setKeepCallback(true);
                        context.sendPluginResult(progressResult);
                    }

                    sendStream.flush();
                } finally {
                    safeClose(readResult.inputStream);
                    safeClose(sendStream);
                }
                context.currentOutputStream = null;
                Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);

                //------------------ read the SERVER RESPONSE
                String responseString;
                int responseCode = conn.getResponseCode();
                Log.d(LOG_TAG, "response code: " + responseCode);
                Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields());
                TrackingInputStream inStream = null;
                try {
                    inStream = getInputStream(conn);
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.currentInputStream = inStream;
                    }

                    ByteArrayOutputStream out = new ByteArrayOutputStream(
                            Math.max(1024, conn.getContentLength()));
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    // write bytes to file
                    while ((bytesRead = inStream.read(buffer)) > 0) {
                        out.write(buffer, 0, bytesRead);
                    }
                    responseString = out.toString("UTF-8");
                } finally {
                    context.currentInputStream = null;
                    safeClose(inStream);
                }

                Log.d(LOG_TAG, "got response from server");
                Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length())));

                // send request and retrieve response
                result.setResponseCode(responseCode);
                result.setResponse(responseString);

                context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject()));
            } catch (FileNotFoundException e) {
                JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (IOException e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), e);
                Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
            } catch (Throwable t) {
                // Shouldn't happen, but will
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), t);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } finally {
                synchronized (activeRequests) {
                    activeRequests.remove(objectId);
                }

                if (conn != null) {
                    // Revert back to the proper verifier and socket factories
                    // Revert back to the proper verifier and socket factories
                    if (trustEveryone && useHttps) {
                        HttpsURLConnection https = (HttpsURLConnection) conn;
                        https.setHostnameVerifier(oldHostnameVerifier);
                        https.setSSLSocketFactory(oldSocketFactory);
                    }
                }
            }
        }
    });
}

From source file:com.dubsar_dictionary.Dubsar.model.Sense.java

@Override
public void parseData(Object jsonResponse) throws JSONException {
    JSONArray response = (JSONArray) jsonResponse;

    JSONArray _word = response.getJSONArray(1);
    JSONArray _synset = response.getJSONArray(2);

    int wordId = _word.getInt(0);
    String wordName = _word.getString(1);
    String wordPos = _word.getString(2);

    int synsetId = _synset.getInt(0);

    mGloss = new String(_synset.getString(1));
    setPos(wordPos);/*from   w ww  .  ja  v a2s.  com*/

    mWord = new Word(wordId, wordName, getPartOfSpeech());
    mName = new String(wordName);
    mSynset = new Synset(synsetId, mGloss, getPartOfSpeech());

    mIsWeakWordReference = mIsWeakSynsetReference = false;
    mWordReference = null;
    mSynsetReference = null;

    setLexname(response.getString(3));
    getSynset().setLexname(getLexname());

    if (!response.isNull(4)) {
        setMarker(response.getString(4));
    }

    setFreqCnt(response.getInt(5));

    JSONArray _synonyms = response.getJSONArray(6);
    mSynonyms = new ArrayList<Sense>(_synonyms.length());

    int j;
    int senseId;
    String senseName;
    for (j = 0; j < _synonyms.length(); ++j) {
        JSONArray _synonym = _synonyms.getJSONArray(j);

        senseId = _synonym.getInt(0);
        senseName = _synonym.getString(1);
        String marker = null;
        if (!_synonym.isNull(2)) {
            marker = _synonym.getString(2);
        }
        int freqCnt = _synonym.getInt(3);

        Sense synonym = new Sense(senseId, senseName, getSynset());
        synonym.setMarker(marker);
        synonym.setFreqCnt(freqCnt);

        mSynonyms.add(synonym);
    }

    JSONArray _verbFrames = response.getJSONArray(7);
    mVerbFrames = new ArrayList<String>(_verbFrames.length());

    for (j = 0; j < _verbFrames.length(); ++j) {
        String frame = _verbFrames.getString(j);

        // Replace %s in verb frames with the name of the word
        // TODO: Make that a bold span.
        StringBuffer buffer = new StringBuffer();
        Formatter formatter = new Formatter(buffer);
        formatter.format(frame, new Object[] { getName() });
        formatter.close();

        mVerbFrames.add(buffer.toString());
    }

    JSONArray _samples = response.getJSONArray(8);
    mSamples = new ArrayList<String>(_samples.length());

    for (j = 0; j < _samples.length(); ++j) {
        mSamples.add(_samples.getString(j));
    }

    parsePointers(response.getJSONArray(9));
}

From source file:com.aerhard.oxygen.plugin.dbtagger.util.JsonUtil.java

/**
 * Converts a JSON array to from the JSON server response.
 * //from w  w w  . ja v a  2  s.  co  m
 * @param columns
 *            The number of columns.
 * @param rows
 *            The number of rows.
 * @param dataArray
 *            the input data.
 * 
 * @return the body content
 */
private String[][] convertArray(int rows, int columns, JSONArray dataArray) {
    String[][] resultTable = new String[rows][];
    for (int i = 0; i < rows; i++) {
        JSONArray arr = dataArray.getJSONArray(i);
        List<String> list = new ArrayList<String>();
        if (arr.length() < columns) {
            throw new ArrayStoreException(i18n.getString("jsonUtil.dataColumnError"));
        }
        for (int j = 0; j < columns; j++) {
            list.add(arr.isNull(j) ? "" : arr.getString(j));
        }
        resultTable[i] = list.toArray(new String[columns]);
    }
    return resultTable;
}

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

/**
 * Converts a parameter from JSON into a Java Object.
 * /*ww  w .j ava2  s. c  om*/
 * @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:vOS.controller.socket.IOConnection.java

/**
 * Transport message. {@link IOTransport} calls this, when a message has
 * been received./*ww  w  .  j  av a 2s  . co  m*/
 * 
 * @param text
 *            the text
 */
public void transportMessage(String text) {
    logger.info("< " + text);
    IOMessage message;
    try {
        message = new IOMessage(text);
    } catch (Exception e) {
        error(new SocketIOException("Garbage from server: " + text, e));
        return;
    }
    resetTimeout();
    switch (message.getType()) {
    case IOMessage.TYPE_DISCONNECT:
        try {
            findCallback(message).onDisconnect();
        } catch (Exception e) {
            error(new SocketIOException("Exception was thrown in onDisconnect()", e));
        }
        break;
    case IOMessage.TYPE_CONNECT:
        try {
            if (firstSocket != null && "".equals(message.getEndpoint())) {
                if (firstSocket.getNamespace().equals("")) {
                    firstSocket.getCallback().onConnect();
                } else {
                    IOMessage connect = new IOMessage(IOMessage.TYPE_CONNECT, firstSocket.getNamespace(), "");
                    sendPlain(connect.toString());
                }
            } else {
                findCallback(message).onConnect();
            }
            firstSocket = null;
        } catch (Exception e) {
            error(new SocketIOException("Exception was thrown in onConnect()", e));
        }
        break;
    case IOMessage.TYPE_HEARTBEAT:
        sendPlain("2::");
        break;
    case IOMessage.TYPE_MESSAGE:
        try {
            findCallback(message).onMessage(message.getData(), remoteAcknowledge(message));
        } catch (Exception e) {
            error(new SocketIOException(
                    "Exception was thrown in onMessage(String).\n" + "Message was: " + message.toString(), e));
        }
        break;
    case IOMessage.TYPE_JSON_MESSAGE:
        try {
            JSONObject obj = null;
            String data = message.getData();
            if (data.trim().equals("null") == false)
                obj = new JSONObject(data);
            try {
                findCallback(message).onMessage(obj, remoteAcknowledge(message));
            } catch (Exception e) {
                error(new SocketIOException("Exception was thrown in onMessage(JSONObject).\n" + "Message was: "
                        + message.toString(), e));
            }
        } catch (JSONException e) {
            logger.warning("Malformated JSON received");
        }
        break;
    case IOMessage.TYPE_EVENT:
        try {
            JSONObject event = new JSONObject(message.getData());
            Object[] argsArray;
            if (event.has("args")) {
                JSONArray args = event.getJSONArray("args");
                argsArray = new Object[args.length()];
                for (int i = 0; i < args.length(); i++) {
                    if (args.isNull(i) == false)
                        argsArray[i] = args.get(i);
                }
            } else
                argsArray = new Object[0];
            String eventName = event.getString("name");
            try {
                findCallback(message).on(eventName, remoteAcknowledge(message), argsArray);
            } catch (Exception e) {
                error(new SocketIOException("Exception was thrown in on(String, JSONObject[]).\n"
                        + "Message was: " + message.toString(), e));
            }
        } catch (JSONException e) {
            logger.warning("Malformated JSON received");
        }
        break;

    case IOMessage.TYPE_ACK:
        String[] data = message.getData().split("\\+", 2);
        if (data.length == 2) {
            try {
                int id = Integer.parseInt(data[0]);
                IOAcknowledge ack = acknowledge.get(id);
                if (ack == null)
                    logger.warning("Received unknown ack packet");
                else {
                    JSONArray array = new JSONArray(data[1]);
                    Object[] args = new Object[array.length()];
                    for (int i = 0; i < args.length; i++) {
                        args[i] = array.get(i);
                    }
                    ack.ack(args);
                }
            } catch (NumberFormatException e) {
                logger.warning(
                        "Received malformated Acknowledge! This is potentially filling up the acknowledges!");
            } catch (JSONException e) {
                logger.warning("Received malformated Acknowledge data!");
            }
        } else if (data.length == 1) {
            sendPlain("6:::" + data[0]);
        }
        break;
    case IOMessage.TYPE_ERROR:
        try {
            findCallback(message).onError(new SocketIOException(message.getData()));
        } catch (SocketIOException e) {
            error(e);
        }
        if (message.getData().endsWith("+0")) {
            // We are advised to disconnect
            cleanup();
        }
        break;
    case IOMessage.TYPE_NOOP:
        break;
    default:
        logger.warning("Unkown type received" + message.getType());
        break;
    }
}

From source file:com.github.sommeri.sourcemap.SourceMapConsumerV3.java

private String[] getJavaStringArray(JSONArray array) throws JSONException {
    int len = array.length();
    String[] result = new String[len];
    for (int i = 0; i < len; i++) {
        result[i] = array.isNull(i) ? null : array.getString(i);
    }/*w w w .  ja  v  a 2  s .c o  m*/
    return result;
}

From source file:com.cmackay.plugins.googleanalytics.GoogleAnalyticsPlugin.java

private void set(String rawArgs, CallbackContext callbackContext) {
    if (hasTracker(callbackContext)) {
        try {//from  www  .  j  a  va2 s .c  o  m
            JSONArray args = new JSONArray(rawArgs);
            String key = args.getString(0);
            String value = args.isNull(1) ? null : args.getString(1);
            tracker.set(key, value);
            callbackContext.success();
        } catch (JSONException e) {
            callbackContext.error(e.toString());
        }
    }
}

From source file:com.ezartech.ezar.videooverlay.ezAR.java

private static int getIntOrNull(JSONArray args, int i) {
    if (args.isNull(i)) {
        return Integer.MIN_VALUE;
    }//w w w.ja  v a  2s.com

    try {
        return args.getInt(i);
    } catch (JSONException e) {
        Log.e(TAG, "Can't get double", e);
        throw new RuntimeException(e);
    }
}