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.yoncabt.ebr.util.ResultSetDeserializer.java

public List<Object[]> getData() {
    List<Object[]> ret = new ArrayList<>();
    JSONArray arr = jo.getJSONArray("values");
    for (int i = 0; i < arr.length(); i++) {
        List<Object> column = new ArrayList<>();
        JSONArray row = arr.getJSONArray(i);
        for (int j = 0; j < types.size(); j++) {
            if (row.isNull(j)) {
                column.add(null);//from   w  w w .j  a va  2 s  .  c om
            } else {
                switch (types.get(j)) {
                case DATE:
                    column.add(new Date(row.getLong(j)));
                    break;
                case STRING:
                    column.add(row.getString(j));
                    break;
                case INTEGER:
                    column.add(row.getInt(j));
                    break;
                case LONG:
                    column.add(row.getLong(j));
                    break;
                case DOUBLE:
                    column.add(row.getDouble(j));
                    break;
                default:
                    throw new AssertionError();
                }
            }
        }
        ret.add(column.toArray());
    }
    return ret;
}

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

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

    setPos(response.getString(1));/*from w ww . jav a  2 s.  c o m*/
    setLexname(response.getString(2));
    mGloss = response.getString(3);

    JSONArray samples = response.getJSONArray(4);
    mSamples = new ArrayList<String>(samples.length());
    int j;
    for (j = 0; j < samples.length(); ++j) {
        mSamples.add(samples.getString(j));
    }

    JSONArray senses = response.getJSONArray(5);
    mSenses = new ArrayList<Sense>(senses.length());
    for (j = 0; j < senses.length(); ++j) {
        JSONArray _sense = senses.getJSONArray(j);

        int senseId = _sense.getInt(0);
        String senseName = _sense.getString(1);

        Sense sense = new Sense(senseId, senseName, this);
        sense.setLexname(getLexname());
        if (!_sense.isNull(2)) {
            sense.setMarker(_sense.getString(2));
        }
        sense.setFreqCnt(_sense.getInt(3));

        mSenses.add(sense);
    }

    mFreqCnt = response.getInt(6);

    parsePointers(response.getJSONArray(7));
}

From source file:com.baroq.pico.google.PlayServices.java

@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {

    try {//  ww w.j a v a  2  s  . c o  m
        if (!ACTION_SETUP.equals(action) && !ACTION_SIGNIN.equals(action)
                && (null == mHelper || !mHelper.isConnected())) {
            callbackContext.error("Please setup and signin to use PlayServices plugin");
            return false;
        }
        if (ACTION_SETUP.equals(action)) {
            int l = data.length();
            if (0 == l) {
                callbackContext.error("Expecting at least 1 parameter for action: " + action);
                return false;
            }
            clientTypes = data.getInt(0);
            String[] extraScopes = new String[l - 1];
            for (int i = 1; i < l; i++) {
                extraScopes[i - 1] = data.getString(i);
            }
            setup(clientTypes, extraScopes, callbackContext);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        } else if (ACTION_SIGNIN.equals(action)) {
            mHelper.beginUserInitiatedSignIn();
            callbackContext.success();
        } else if (ACTION_SIGNOUT.equals(action)) {
            signout();
            callbackContext.success();
        } else if (ACTION_AS_MAX_KEYS.equals(action)) {
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                    mHelper.getAppStateClient().getMaxNumKeys());
            pluginResult.setKeepCallback(false);
            callbackContext.sendPluginResult(pluginResult);
        } else if (ACTION_AS_MAX_SIZE.equals(action)) {
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                    mHelper.getAppStateClient().getMaxStateSize());
            pluginResult.setKeepCallback(false);
            callbackContext.sendPluginResult(pluginResult);
        } else if (ACTION_AS_DEL.equals(action)) {
            int key = data.getInt(0);
            mHelper.getAppStateClient().deleteState(this, key);
            callbackContext.success();
        } else if (ACTION_AS_LIST.equals(action)) {
            mHelper.getAppStateClient().listStates(this);
            callbackContext.success();
        } else if (ACTION_AS_LOAD.equals(action)) {
            int key = data.getInt(0);
            mHelper.getAppStateClient().loadState(this, key);
            callbackContext.success();
        } else if (ACTION_AS_RESOLVE.equals(action)) {
            int key = data.getInt(0);
            String resolvedVersion = data.getString(1);
            String value = data.getString(2);
            mHelper.getAppStateClient().resolveState(this, key, resolvedVersion, value.getBytes());
            callbackContext.success();
        } else if (ACTION_AS_UPDATE.equals(action)) {
            int key = data.getInt(0);
            String value = data.getString(1);
            mHelper.getAppStateClient().updateState(key, value.getBytes());
            callbackContext.success();
        } else if (ACTION_AS_UPDATE_NOW.equals(action)) {
            int key = data.getInt(0);
            String value = data.getString(1);
            mHelper.getAppStateClient().updateStateImmediate(this, key, value.getBytes());
            callbackContext.success();
        } else if (ACTION_GAME_SHOW_ACHIEVEMENTS.equals(action)) {
            cordova.startActivityForResult((CordovaPlugin) this,
                    mHelper.getGamesClient().getAchievementsIntent(), RC_UNUSED);
            callbackContext.success();
        } else if (ACTION_GAME_SHOW_LEADERBOARDS.equals(action)) {
            cordova.startActivityForResult((CordovaPlugin) this,
                    mHelper.getGamesClient().getAllLeaderboardsIntent(), RC_UNUSED);
            callbackContext.success();
        } else if (ACTION_GAME_SHOW_LEADERBOARD.equals(action)) {
            String id = data.getString(0);
            cordova.startActivityForResult((CordovaPlugin) this,
                    mHelper.getGamesClient().getLeaderboardIntent(id), RC_UNUSED);
            callbackContext.success();
        } else if (ACTION_GAME_INCR_ACHIEVEMENT.equals(action)) {
            String id = data.getString(0);
            int numSteps = data.getInt(1);
            mHelper.getGamesClient().incrementAchievement(id, numSteps);
            callbackContext.success();
        } else if (ACTION_GAME_INCR_ACHIEVEMENT_NOW.equals(action)) {
            String id = data.getString(0);
            int numSteps = data.getInt(1);
            mHelper.getGamesClient().incrementAchievementImmediate(this, id, numSteps);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_ACHIEVEMENTS.equals(action)) {
            boolean forceReload = data.getBoolean(0);
            mHelper.getGamesClient().loadAchievements(this, forceReload);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_GAME.equals(action)) {
            mHelper.getGamesClient().loadGame(this);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_LEADERBOARD_METADATA.equals(action)) {
            if (1 == data.length()) {
                mHelper.getGamesClient().loadLeaderboardMetadata(this, data.getBoolean(0));
            } else {
                mHelper.getGamesClient().loadLeaderboardMetadata(this, data.getString(0), data.getBoolean(1));
            }
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_MORE_SCORES.equals(action)) {
            if (null == scoreBuffer) {
                callbackContext.error("Get a leaderboard fist before calling: " + action);
                return false;
            }
            int maxResults = data.getInt(0);
            int pageDirection = data.getInt(0);
            mHelper.getGamesClient().loadMoreScores(this, scoreBuffer, maxResults, pageDirection);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_PLAYER.equals(action)) {
            String playerId = data.getString(0);
            mHelper.getGamesClient().loadPlayer(this, playerId);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_PLAYER_CENTERED_SCORES.equals(action)) {
            String leaderboardId = data.getString(0);
            int span = data.getInt(1);
            int leaderboardCollection = data.getInt(2);
            int maxResults = data.getInt(3);
            if (data.isNull(4)) {
                mHelper.getGamesClient().loadPlayerCenteredScores(this, leaderboardId, span,
                        leaderboardCollection, maxResults);
            } else {
                boolean forceReload = data.getBoolean(4);
                mHelper.getGamesClient().loadPlayerCenteredScores(this, leaderboardId, span,
                        leaderboardCollection, maxResults, forceReload);
            }
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_TOP_SCORES.equals(action)) {
            String leaderboardId = data.getString(0);
            int span = data.getInt(1);
            int leaderboardCollection = data.getInt(2);
            int maxResults = data.getInt(3);
            if (data.isNull(4)) {
                mHelper.getGamesClient().loadTopScores(this, leaderboardId, span, leaderboardCollection,
                        maxResults);
            } else {
                boolean forceReload = data.getBoolean(4);
                mHelper.getGamesClient().loadTopScores(this, leaderboardId, span, leaderboardCollection,
                        maxResults, forceReload);
            }
            callbackContext.success();
        } else if (ACTION_GAME_REVEAL_ACHIEVEMENT.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().revealAchievement(id);
            callbackContext.success();
        } else if (ACTION_GAME_REVEAL_ACHIEVEMENT_NOW.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().revealAchievementImmediate(this, id);
            callbackContext.success();
        } else if (ACTION_GAME_SUBMIT_SCORE.equals(action)) {
            String leaderboardId = data.getString(0);
            int score = data.getInt(1);
            mHelper.getGamesClient().submitScore(leaderboardId, score);
            callbackContext.success();
        } else if (ACTION_GAME_SUBMIT_SCORE_NOW.equals(action)) {
            String leaderboardId = data.getString(0);
            int score = data.getInt(1);
            mHelper.getGamesClient().submitScoreImmediate(this, leaderboardId, score);
            callbackContext.success();
        } else if (ACTION_GAME_UNLOCK_ACHIEVEMENT.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().unlockAchievement(id);
            callbackContext.success();
        } else if (ACTION_GAME_UNLOCK_ACHIEVEMENT_NOW.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().unlockAchievementImmediate(this, id);
            callbackContext.success();
        } else {
            callbackContext.error("Unknown action: " + action);
            return false;
        }
    } catch (JSONException ex) {
        callbackContext.error(ex.getMessage());
        return false;
    }

    return true;
}

From source file:org.apache.cordova.filetransfer.FileTransfer.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  ww w .  j  a  v a 2 s .c o  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 fileKey = getArgument(args, 2, "file");
    final String fileName = getArgument(args, 3, "image.jpg");
    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, "fileKey: " + fileKey);
    Log.d(LOG_TAG, "fileName: " + fileName);
    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, null);
        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
                FileUploadResult result = new FileUploadResult();
                FileProgressResult progress = new FileProgressResult();

                //------------------ 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);

                // if we specified a Content-Type header, don't do multipart form upload
                boolean multipartFormUpload = (headers == null) || !headers.has("Content-Type");
                if (multipartFormUpload) {
                    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
                }

                // Set the cookies on the response
                String cookie = getCookies(target);

                if (cookie != null) {
                    conn.setRequestProperty("Cookie", cookie);
                }

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

                /*
                * Store the non-file portions of the multipart data as a string, so that we can add it
                * to the contentSize, since it is part of the body of the HTTP request.
                */
                StringBuilder beforeData = new StringBuilder();
                try {
                    for (Iterator<?> iter = params.keys(); iter.hasNext();) {
                        Object key = iter.next();
                        if (!String.valueOf(key).equals("headers")) {
                            beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
                            beforeData.append("Content-Disposition: form-data; name=\"").append(key.toString())
                                    .append('"');
                            beforeData.append(LINE_END).append(LINE_END);
                            beforeData.append(params.getString(key.toString()));
                            beforeData.append(LINE_END);
                        }
                    }
                } catch (JSONException e) {
                    Log.e(LOG_TAG, e.getMessage(), e);
                }

                beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
                beforeData.append("Content-Disposition: form-data; name=\"").append(fileKey).append("\";");
                beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END);
                beforeData.append("Content-Type: ").append(mimeType).append(LINE_END).append(LINE_END);
                byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8");
                byte[] tailParamsBytes = (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END)
                        .getBytes("UTF-8");

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

                int stringLength = beforeDataBytes.length + tailParamsBytes.length;
                if (readResult.length >= 0) {
                    fixedLength = (int) readResult.length;
                    if (multipartFormUpload)
                        fixedLength += stringLength;
                    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.connection = conn;
                    }

                    if (multipartFormUpload) {
                        //We don't want to change encoding, we just want this to write for all Unicode.
                        sendStream.write(beforeDataBytes);
                        totalBytes += beforeDataBytes.length;
                    }

                    // 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);
                    }

                    if (multipartFormUpload) {
                        // send multipart form data necessary after file data...
                        sendStream.write(tailParamsBytes);
                        totalBytes += tailParamsBytes.length;
                    }
                    sendStream.flush();
                } finally {
                    safeClose(readResult.inputStream);
                    safeClose(sendStream);
                }
                synchronized (context) {
                    context.connection = 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.connection = conn;
                    }

                    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 {
                    synchronized (context) {
                        context.connection = 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, e);
                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, e);
                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, t);
                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:no.barentswatch.implementation.FiskInfoUtility.java

/**
 * Appends a item from a JsonArray to a <code>ExpandableListAdapater</code>
 * /* ww w  .  java 2 s  . c  o m*/
 * @param subscriptions
 *            A JSON array containing all the available subscriptions
 * @param field
 *            The field name in the <code>ExpandableListAdapater</code>
 * @param fieldsToExtract
 *            The fields from the subscriptions to retrieve and store in the
 *            <code>ExpandableListAdapater</code>
 */
public void appendSubscriptionItemsToView(JSONArray subscriptions, List<String> field,
        List<String> fieldsToExtract) {
    if ((subscriptions == null) || (subscriptions.isNull(0))) {
        return;
    }

    String title = "";
    for (int i = 0; i < subscriptions.length(); i++) {
        try {
            JSONObject currentSubscription = subscriptions.getJSONObject(i);
            for (String fieldValue : fieldsToExtract) {

                title += (fieldValue.equals("LastUpdated")
                        ? currentSubscription.getString(fieldValue).replace('T', ' ')
                        : currentSubscription.getString(fieldValue)) + "\n";
            }
            title = title.substring(0, title.length() - 1);
            field.add(title);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        title = "";
    }
}

From source file:com.apecat.shoppingadvisor.scan.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException {

    CharSequence contents = HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;/*from w  w  w  .j a v a 2 s .  co  m*/
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>(authorsArray.length());
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

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

    Collection<String> newTexts = new ArrayList<String>();
    maybeAddText(title, newTexts);
    maybeAddTextSeries(authors, newTexts);
    maybeAddText(pages == null || pages.isEmpty() ? null : pages + "pp.", newTexts);

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:com.smartchair.socketio.IOConnection.java

/**
 * Transport message. {@link IOTransport} calls this, when a message has
 * been received.//from w ww  .  j a  v  a 2 s.  com
 * 
 * @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
            //            handshake();
            cleanup();
        }
        break;
    case IOMessage.TYPE_NOOP:
        break;
    default:
        logger.warning("Unkown type received" + message.getType());
        break;
    }
}

From source file:com.polychrom.cordova.AccountManagerPlugin.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (manager == null) {
        manager = AccountManager.get(cordova.getActivity());
    }//w w  w . java 2  s  .  c  o  m

    try {
        if ("getAccountsByType".equals(action)) {
            Account[] account_list = manager.getAccountsByType(args.isNull(0) ? null : args.getString(0));
            JSONArray result = new JSONArray();

            for (Account account : account_list) {
                Integer index = indexForAccount(account);
                accounts.put(index, account);

                JSONObject account_object = new JSONObject();
                account_object.put("_index", (int) index);
                account_object.put("name", account.name);
                account_object.put("type", account.type);
                result.put(account_object);
            }

            callbackContext.success(result);
            return true;
        } else if ("addAccountExplicitly".equals(action)) {
            if (args.isNull(0) || args.getString(0).length() == 0) {
                callbackContext.error("accountType can not be null or empty");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("username can not be null or empty");
                return true;
            } else if (args.isNull(2) || args.getString(2).length() == 0) {
                callbackContext.error("password can not be null or empty");
                return true;
            }

            Account account = new Account(args.getString(1), args.getString(0));
            Integer index = indexForAccount(account);

            Bundle userdata = new Bundle();
            if (!args.isNull(3)) {
                JSONObject userdata_json = args.getJSONObject(3);
                if (userdata_json != null) {
                    Iterator<String> keys = userdata_json.keys();
                    while (keys.hasNext()) {
                        String key = keys.next();
                        userdata.putString(key, userdata_json.getString(key));
                    }
                }
            }

            if (false == manager.addAccountExplicitly(account, args.getString(2), userdata)) {
                callbackContext.error("Account with username already exists!");
                return true;
            }

            accounts.put(index, account);

            JSONObject result = new JSONObject();
            result.put("_index", (int) index);
            result.put("name", account.name);
            result.put("type", account.type);

            callbackContext.success(result);
            return true;
        } else if ("updateCredentials".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            callbackContext.error("Not yet implemented");
            return true;
        } else if ("clearPassword".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.clearPassword(account);
            callbackContext.success();
            return true;
        } else if ("removeAccount".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            int index = args.getInt(0);
            Account account = accounts.get(index);
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            // TODO: Add support for AccountManager (callback)
            AccountManagerFuture<Boolean> future = manager.removeAccount(account, null, null);
            try {
                if (future.getResult() == true) {
                    accounts.remove(index);
                    callbackContext.success();
                } else {
                    callbackContext.error("Failed to remove account");
                }
            } catch (OperationCanceledException e) {
                callbackContext.error("Operation canceled: " + e.getLocalizedMessage());
            } catch (AuthenticatorException e) {
                callbackContext.error("Authenticator error: " + e.getLocalizedMessage());
            } catch (IOException e) {
                callbackContext.error("IO error: " + e.getLocalizedMessage());
            }

            return true;
        } else if ("setAuthToken".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("authTokenType can not be null or empty");
                return true;
            } else if (args.isNull(2) || args.getString(2).length() == 0) {
                callbackContext.error("authToken can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.setAuthToken(account, args.getString(1), args.getString(2));
            callbackContext.success();
            return true;
        } else if ("peekAuthToken".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("authTokenType can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            JSONObject result = new JSONObject();
            result.put("value", manager.peekAuthToken(account, args.getString(1)));
            callbackContext.success(result);
            return true;
        } else if ("getAuthToken".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("authTokenType can not be null or empty");
                return true;
            } else if (args.isNull(3)) {
                callbackContext.error("notifyAuthFailure can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            Bundle options = new Bundle();
            // TODO: Options support (will be relevent when we support AccountManagers)

            // TODO: AccountManager support
            AccountManagerFuture<Bundle> future = manager.getAuthToken(account, args.getString(1), options,
                    args.getBoolean(3), null, null);
            try {
                JSONObject result = new JSONObject();
                result.put("value", future.getResult().getString(AccountManager.KEY_AUTHTOKEN));
                callbackContext.success(result);
            } catch (OperationCanceledException e) {
                callbackContext.error("Operation canceled: " + e.getLocalizedMessage());
            } catch (AuthenticatorException e) {
                callbackContext.error("Authenticator error: " + e.getLocalizedMessage());
            } catch (IOException e) {
                callbackContext.error("IO error: " + e.getLocalizedMessage());
            }

            return true;
        } else if ("setPassword".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("password can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.setPassword(account, args.getString(1));
            callbackContext.success();
            return true;
        } else if ("getPassword".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            JSONObject result = new JSONObject();
            result.put("value", manager.getPassword(account));
            callbackContext.success(result);
            return true;
        } else if ("setUserData".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("key can not be null or empty");
                return true;
            } else if (args.isNull(2) || args.getString(2).length() == 0) {
                callbackContext.error("value can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.setUserData(account, args.getString(1), args.getString(2));
            callbackContext.success();
            return true;
        } else if ("getUserData".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("key can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            JSONObject result = new JSONObject();
            result.put("value", manager.getUserData(account, args.getString(1)));
            callbackContext.success(result);
            return true;
        }
    } catch (SecurityException e) {
        callbackContext.error("Access denied");
        return true;
    }

    return false;
}

From source file:io.github.data4all.handler.TagSuggestionHandler.java

/**
 * Get a list of locations near by the given location.
 * //from w  w w . j  a v a  2  s. c o  m
 * @param location
 * @return locations near by a given Location
 */
private static List<Location> getNearestLocations(Location location) {
    final List<Location> locations = new LinkedList<Location>();
    try {
        final double boundingbox[] = getBoundingBox(location.getLatitude(), location.getLongitude(), 0.020);
        StringBuilder url = new StringBuilder("http://overpass-api.de/api/interpreter?data=[out:json];");
        StringBuilder param = new StringBuilder("");
        param.append("node(").append(boundingbox[0]).append(",").append(boundingbox[1]).append(",");
        param.append(boundingbox[2]).append(",").append(boundingbox[3]).append(");out;");
        final String urlParam = url.toString() + Uri.encode(param.toString(), "UTF-8");
        final JSONObject jsonObj = getJSONfromURL(urlParam);
        final JSONArray elements = jsonObj.getJSONArray("elements");
        int index = 0;
        while (!elements.isNull(index)) {
            final JSONObject obj = elements.getJSONObject(index);
            final String lat = getJsonValue(obj, "lat");
            final String lon = getJsonValue(obj, "lon");
            if (!lat.isEmpty() && !lon.isEmpty()) {
                final Location loc = new Location("");
                loc.setLatitude(Double.valueOf(lat));
                loc.setLongitude(Double.valueOf(lon));
                locations.add(loc);
            }
            index++;
        }

        Log.i(TAG, "getNear: " + index);
    } catch (Exception e) {
        Log.i(TAG, "getNear: ", e);
    }
    return locations;
}

From source file:com.norman0406.slimgress.API.Game.GameState.java

public void intGetNicknamesFromUserGUIDs(final String[] guids, final Handler handler) {
    try {/*from  ww  w .j  a  v a 2  s.c  om*/
        checkInterface();

        // create params (don't know why there are two nested arrays)
        JSONObject params = new JSONObject();

        JSONArray playerGuids = new JSONArray();
        for (String guid : guids)
            playerGuids.put(guid);

        JSONArray playerIds = new JSONArray();
        playerIds.put(playerGuids);
        params.put("params", playerIds);

        mInterface.request(mHandshake, "playerUndecorated/getNickNamesFromPlayerIds", null, params,
                new RequestResult(handler) {
                    @Override
                    public void handleResult(JSONArray result) {
                        try {
                            // retrieve nicknames for user ids
                            if (result != null && result.length() > 0) {
                                for (int i = 0; i < result.length(); i++) {
                                    if (!result.isNull(i))
                                        getData().putString(guids[i], result.getString(i));
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}