Example usage for org.json JSONObject getBoolean

List of usage examples for org.json JSONObject getBoolean

Introduction

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

Prototype

public boolean getBoolean(String key) throws JSONException 

Source Link

Document

Get the boolean value associated with a key.

Usage

From source file:com.karura.framework.plugins.UI.java

@JavascriptInterface
// #endif/*from ww  w .ja va  2s.  c  o m*/
@SupportJavascriptInterface
@Description("Load the url into the webview.")
@Asynchronous(retVal = "none, will load the specified URL in the webview")
@Params({ @Param(name = "callId", description = "The method correlator between javascript and java."),
        @Param(name = "url", description = "URL to be loaded in the web browser"),
        @Param(name = "props", description = "Specifies the parameters for customizing the loadUrl experience. Look at "
                + "WAIT_KEY, OPEN_EXTR_KEY and CLEAR_HISTORY_KEY. If the OPEN_EXTR_KEY is specified then this object can also contain additional "
                + "parameters which need to be passed to the external viewer in the intent. The other keys can only be integer, boolean or string") })
public void loadUrl(final String callId, String url, JSONObject props) throws JSONException {
    Log.d(TAG, "loadUrl(" + url + "," + props + ")");
    int wait = 0;
    boolean openExternal = false;
    boolean clearHistory = false;

    // If there are properties, then set them on the Activity
    HashMap<String, Object> params = new HashMap<String, Object>();
    if (props != null) {
        JSONArray keys = props.names();
        for (int i = 0; i < keys.length(); i++) {
            String key = keys.getString(i);
            if (key.equals(WAIT_KEY)) {
                wait = props.getInt(key);
            } else if (key.equalsIgnoreCase(OPEN_EXTR_KEY)) {
                openExternal = props.getBoolean(key);
            } else if (key.equalsIgnoreCase(CLEAR_HISTORY_KEY)) {
                clearHistory = props.getBoolean(key);
            } else {
                Object value = props.get(key);
                if (value == null) {

                } else if (value.getClass().equals(String.class)) {
                    params.put(key, (String) value);
                } else if (value.getClass().equals(Boolean.class)) {
                    params.put(key, (Boolean) value);
                } else if (value.getClass().equals(Integer.class)) {
                    params.put(key, (Integer) value);
                }
            }
        }
    }

    // If wait property, then delay loading

    if (wait > 0) {
        try {
            synchronized (this) {
                this.wait(wait);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    getWebView().showWebPage(url, openExternal, clearHistory, params);
}

From source file:org.transdroid.daemon.Transmission.TransmissionAdapter.java

@Override
public DaemonTaskResult executeTask(Log log, DaemonTask task) {

    try {/*from   ww w.java2 s .c om*/

        // Get the server version
        if (rpcVersion <= -1) {
            // Get server session statistics
            JSONObject response = makeRequest(log, buildRequestObject("session-get", new JSONObject()));
            rpcVersion = response.getJSONObject("arguments").getInt("rpc-version");
        }

        JSONObject request = new JSONObject();
        switch (task.getMethod()) {
        case Retrieve:

            // Request all torrents from server
            JSONArray fields = new JSONArray();
            final String[] fieldsArray = new String[] { RPC_ID, RPC_NAME, RPC_ERROR, RPC_ERRORSTRING,
                    RPC_STATUS, RPC_DOWNLOADDIR, RPC_RATEDOWNLOAD, RPC_RATEUPLOAD, RPC_PEERSGETTING,
                    RPC_PEERSSENDING, RPC_PEERSCONNECTED, RPC_ETA, RPC_DOWNLOADSIZE1, RPC_DOWNLOADSIZE2,
                    RPC_UPLOADEDEVER, RPC_TOTALSIZE, RPC_DATEADDED, RPC_DATEDONE, RPC_AVAILABLE, RPC_COMMENT };
            for (String field : fieldsArray) {
                fields.put(field);
            }
            request.put("fields", fields);

            JSONObject result = makeRequest(log, buildRequestObject("torrent-get", request));
            return new RetrieveTaskSuccessResult((RetrieveTask) task,
                    parseJsonRetrieveTorrents(result.getJSONObject("arguments")), null);

        case GetStats:

            // Request the current server statistics
            JSONObject stats = makeRequest(log, buildRequestObject("session-get", new JSONObject()))
                    .getJSONObject("arguments");
            return new GetStatsTaskSuccessResult((GetStatsTask) task, stats.getBoolean("alt-speed-enabled"),
                    rpcVersion >= 12 ? stats.getLong("download-dir-free-space") : -1);

        case GetTorrentDetails:

            // Request fine details of a specific torrent
            JSONArray dfields = new JSONArray();
            dfields.put("trackers");
            dfields.put("trackerStats");

            JSONObject buildDGet = buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null,
                    false);
            buildDGet.put("fields", dfields);
            JSONObject getDResult = makeRequest(log, buildRequestObject("torrent-get", buildDGet));
            return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task,
                    parseJsonTorrentDetails(getDResult.getJSONObject("arguments")));

        case GetFileList:

            // Request all details for a specific torrent
            JSONArray ffields = new JSONArray();
            ffields.put("files");
            ffields.put("fileStats");

            JSONObject buildGet = buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null, false);
            buildGet.put("fields", ffields);
            JSONObject getResult = makeRequest(log, buildRequestObject("torrent-get", buildGet));
            return new GetFileListTaskSuccessResult((GetFileListTask) task,
                    parseJsonFileList(getResult.getJSONObject("arguments"), task.getTargetTorrent()));

        case AddByFile:

            // Add a torrent to the server by sending the contents of a local .torrent file
            String file = ((AddByFileTask) task).getFile();

            // Encode the .torrent file's data
            InputStream in = new Base64.InputStream(new FileInputStream(new File(URI.create(file))),
                    Base64.ENCODE);
            StringWriter writer = new StringWriter();
            int c;
            while ((c = in.read()) != -1) {
                writer.write(c);
            }
            in.close();

            // Request to add a torrent by Base64-encoded meta data
            request.put("metainfo", writer.toString());

            makeRequest(log, buildRequestObject("torrent-add", request));
            return new DaemonTaskSuccessResult(task);

        case AddByUrl:

            // Request to add a torrent by URL
            String url = ((AddByUrlTask) task).getUrl();
            request.put("filename", url);

            makeRequest(log, buildRequestObject("torrent-add", request));
            return new DaemonTaskSuccessResult(task);

        case AddByMagnetUrl:

            // Request to add a magnet link by URL
            String magnet = ((AddByMagnetUrlTask) task).getUrl();
            request.put("filename", magnet);

            makeRequest(log, buildRequestObject("torrent-add", request));
            return new DaemonTaskSuccessResult(task);

        case Remove:

            // Remove a torrent
            RemoveTask removeTask = (RemoveTask) task;
            makeRequest(log,
                    buildRequestObject("torrent-remove",
                            buildTorrentRequestObject(removeTask.getTargetTorrent().getUniqueID(),
                                    "delete-local-data", removeTask.includingData())));
            return new DaemonTaskSuccessResult(task);

        case Pause:

            // Pause a torrent
            PauseTask pauseTask = (PauseTask) task;
            makeRequest(log, buildRequestObject("torrent-stop",
                    buildTorrentRequestObject(pauseTask.getTargetTorrent().getUniqueID(), null, false)));
            return new DaemonTaskSuccessResult(task);

        case PauseAll:

            // Resume all torrents
            makeRequest(log,
                    buildRequestObject("torrent-stop", buildTorrentRequestObject(FOR_ALL, null, false)));
            return new DaemonTaskSuccessResult(task);

        case Resume:

            // Resume a torrent
            ResumeTask resumeTask = (ResumeTask) task;
            makeRequest(log, buildRequestObject("torrent-start",
                    buildTorrentRequestObject(resumeTask.getTargetTorrent().getUniqueID(), null, false)));
            return new DaemonTaskSuccessResult(task);

        case ResumeAll:

            // Resume all torrents
            makeRequest(log,
                    buildRequestObject("torrent-start", buildTorrentRequestObject(FOR_ALL, null, false)));
            return new DaemonTaskSuccessResult(task);

        case SetDownloadLocation:

            // Change the download location
            SetDownloadLocationTask sdlTask = (SetDownloadLocationTask) task;
            // Build request
            JSONObject sdlrequest = new JSONObject();
            JSONArray sdlids = new JSONArray();
            sdlids.put(Long.parseLong(task.getTargetTorrent().getUniqueID()));
            sdlrequest.put("ids", sdlids);
            sdlrequest.put("location", sdlTask.getNewLocation());
            sdlrequest.put("move", true);
            makeRequest(log, buildRequestObject("torrent-set-location", sdlrequest));
            return new DaemonTaskSuccessResult(task);

        case SetFilePriorities:

            // Set priorities of the files of some torrent
            SetFilePriorityTask prioTask = (SetFilePriorityTask) task;

            // Build request
            JSONObject prequest = new JSONObject();
            JSONArray ids = new JSONArray();
            ids.put(Long.parseLong(task.getTargetTorrent().getUniqueID()));
            prequest.put("ids", ids);
            JSONArray fileids = new JSONArray();
            for (TorrentFile forfile : prioTask.getForFiles()) {
                fileids.put(Integer.parseInt(forfile.getKey())); // The keys are the indices of the files, so always numeric
            }
            switch (prioTask.getNewPriority()) {
            case Off:
                prequest.put("files-unwanted", fileids);
                break;
            case Low:
                prequest.put("files-wanted", fileids);
                prequest.put("priority-low", fileids);
                break;
            case Normal:
                prequest.put("files-wanted", fileids);
                prequest.put("priority-normal", fileids);
                break;
            case High:
                prequest.put("files-wanted", fileids);
                prequest.put("priority-high", fileids);
                break;
            }

            makeRequest(log, buildRequestObject("torrent-set", prequest));
            return new DaemonTaskSuccessResult(task);

        case SetTransferRates:

            // Request to set the maximum transfer rates
            SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
            if (ratesTask.getUploadRate() == null) {
                request.put("speed-limit-up-enabled", false);
            } else {
                request.put("speed-limit-up-enabled", true);
                request.put("speed-limit-up", ratesTask.getUploadRate().intValue());
            }
            if (ratesTask.getDownloadRate() == null) {
                request.put("speed-limit-down-enabled", false);
            } else {
                request.put("speed-limit-down-enabled", true);
                request.put("speed-limit-down", ratesTask.getDownloadRate().intValue());
            }

            makeRequest(log, buildRequestObject("session-set", request));
            return new DaemonTaskSuccessResult(task);

        case SetAlternativeMode:

            // Request to set the alternative speed mode (Tutle Mode)
            SetAlternativeModeTask altModeTask = (SetAlternativeModeTask) task;
            request.put("alt-speed-enabled", altModeTask.isAlternativeModeEnabled());
            makeRequest(log, buildRequestObject("session-set", request));
            return new DaemonTaskSuccessResult(task);

        case ForceRecheck:

            // Verify torrent data integrity
            ForceRecheckTask verifyTask = (ForceRecheckTask) task;
            makeRequest(log, buildRequestObject("torrent-verify",
                    buildTorrentRequestObject(verifyTask.getTargetTorrent().getUniqueID(), null, false)));
            return new DaemonTaskSuccessResult(task);

        default:
            return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported,
                    task.getMethod() + " is not supported by " + getType()));
        }
    } catch (JSONException e) {
        return new DaemonTaskFailureResult(task,
                new DaemonException(ExceptionType.ParsingFailed, e.toString()));
    } catch (DaemonException e) {
        return new DaemonTaskFailureResult(task, e);
    } catch (FileNotFoundException e) {
        return new DaemonTaskFailureResult(task,
                new DaemonException(ExceptionType.FileAccessError, e.toString()));
    } catch (IOException e) {
        return new DaemonTaskFailureResult(task,
                new DaemonException(ExceptionType.FileAccessError, e.toString()));
    }
}

From source file:org.transdroid.daemon.Transmission.TransmissionAdapter.java

private ArrayList<TorrentFile> parseJsonFileList(JSONObject response, Torrent torrent) throws JSONException {

    // Parse response
    ArrayList<TorrentFile> torrentfiles = new ArrayList<TorrentFile>();
    JSONArray rarray = response.getJSONArray("torrents");
    if (rarray.length() > 0) {
        JSONArray files = rarray.getJSONObject(0).getJSONArray("files");
        JSONArray fileStats = rarray.getJSONObject(0).getJSONArray("fileStats");
        for (int i = 0; i < files.length(); i++) {
            JSONObject file = files.getJSONObject(i);
            JSONObject stat = fileStats.getJSONObject(i);
            // @formatter:off
            torrentfiles.add(new TorrentFile(String.valueOf(i), file.getString(RPC_FILE_NAME),
                    file.getString(RPC_FILE_NAME), torrent.getLocationDir() + file.getString(RPC_FILE_NAME),
                    file.getLong(RPC_FILE_LENGTH), file.getLong(RPC_FILE_COMPLETED),
                    convertTransmissionPriority(stat.getBoolean(RPC_FILESTAT_WANTED),
                            stat.getInt(RPC_FILESTAT_PRIORITY))));
            // @formatter:on
        }/*from  w w  w. j a  va2  s . c  o m*/
    }

    // Return the list
    return torrentfiles;

}

From source file:net.dv8tion.jda.core.handle.ReadyHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    EntityBuilder builder = api.getEntityBuilder();

    //Core//ww  w. jav a2 s. com
    JSONArray guilds = content.getJSONArray("guilds");
    JSONObject selfJson = content.getJSONObject("user");

    builder.createSelfUser(selfJson);

    if (api.getAccountType() == AccountType.CLIENT && !content.isNull("user_settings")) {
        // handle user settings
        JSONObject userSettingsJson = content.getJSONObject("user_settings");
        UserSettingsImpl userSettingsObj = (UserSettingsImpl) api.asClient().getSettings();
        userSettingsObj
                // TODO: set all information and handle updates
                .setStatus(userSettingsJson.isNull("status") ? OnlineStatus.ONLINE
                        : OnlineStatus.fromKey(userSettingsJson.getString("status")));
        // update presence information unless the status is ONLINE
        if (userSettingsObj.getStatus() != OnlineStatus.ONLINE)
            ((PresenceImpl) api.getPresence()).setCacheStatus(userSettingsObj.getStatus());
    }

    //Keep a list of all guilds in incompleteGuilds that need to be setup (GuildMemberChunk / GuildSync)
    //Send all guilds to the EntityBuilder's first pass to setup caching for when GUILD_CREATE comes
    // or, for Client accounts, to start the setup process (since we already have guild info)
    //Callback points to guildSetupComplete so that when MemberChunking and GuildSync processes are done, we can
    // "check off" the completed guild from the set of guilds in incompleteGuilds.

    for (int i = 0; i < guilds.length(); i++) {
        JSONObject guild = guilds.getJSONObject(i);
        incompleteGuilds.add(guild.getLong("id"));
    }

    //We use two different for-loops here so that we cache all of the ids before sending them off to the EntityBuilder
    //  due to the checks in checkIfReadyToSendRequests and guildSetupComplete triggering too soon otherwise.
    // Specifically: incompleteGuilds.size() == acknowledgedGuilds.size() and
    //  incompleteGuilds.size() == unavailableGuilds.size() respectively.

    for (int i = 0; i < guilds.length(); i++) {
        JSONObject guild = guilds.getJSONObject(i);

        //If a Guild isn't unavailable, then it is possible that we were given all information
        // needed to fully load the guild. In this case, we provide the method `guildSetupComplete`
        // as the secondPassCallback so it can immediately be called to signify that the provided guild
        // is loaded and ready to go.
        //If a Guild is unavailable it won't have the information needed, so we pass null as the secondPassCallback
        // for now and wait for the GUILD_CREATE event to give us the required information.
        if (guild.has("unavailable") && guild.getBoolean("unavailable"))
            builder.createGuildFirstPass(guild, null);
        else
            builder.createGuildFirstPass(guild, this::guildSetupComplete);
    }

    if (guilds.length() == 0)
        guildLoadComplete(content);

    return null;
}

From source file:com.appdynamics.monitors.nginx.statsExtractor.CachesStatsExtractor.java

private Map<String, String> getCachesStats(JSONObject caches) {
    Map<String, String> cachesStats = new HashMap<String, String>();
    Set<String> cacheNames = caches.keySet();

    for (String cacheName : cacheNames) {
        JSONObject cache = caches.getJSONObject(cacheName);

        long size = cache.getLong("size");
        cachesStats.put("caches|" + cacheName + "|size", String.valueOf(size));

        long max_size = cache.getLong("max_size");
        cachesStats.put("caches|" + cacheName + "|max_size", String.valueOf(max_size));

        boolean cold = cache.getBoolean("cold");
        cachesStats.put("caches|" + cacheName + "|cold", String.valueOf(cold ? 0 : 1));

        for (String s : new String[] { "hit", "stale", "updating", "revalidated" }) {
            JSONObject jsonObject = cache.getJSONObject(s);
            long responses = jsonObject.getLong("responses");
            cachesStats.put("caches|" + cacheName + "|" + s + "|responses", String.valueOf(responses));

            long bytes = jsonObject.getLong("bytes");
            cachesStats.put("caches|" + cacheName + "|" + s + "|bytes", String.valueOf(bytes));
        }//  w  ww  .  ja  v a  2  s .c  om

        for (String s : new String[] { "miss", "expired", "bypass" }) {
            JSONObject jsonObject = cache.getJSONObject(s);
            long responses = jsonObject.getLong("responses");
            cachesStats.put("caches|" + cacheName + "|" + s + "|responses", String.valueOf(responses));

            long bytes = jsonObject.getLong("bytes");
            cachesStats.put("caches|" + cacheName + "|" + s + "|bytes", String.valueOf(bytes));

            long responses_written = jsonObject.getLong("responses_written");
            cachesStats.put("caches|" + cacheName + "|" + s + "|responses_written",
                    String.valueOf(responses_written));

            long bytes_written = jsonObject.getLong("bytes_written");
            cachesStats.put("caches|" + cacheName + "|" + s + "|bytes_written", String.valueOf(bytes_written));
        }
    }
    return cachesStats;
}

From source file:org.wso2.appmanager.integration.utils.restapi.base.AppMIntegrationBaseTest.java

/**
 * Cleaning up the API manager by removing all APIs and applications other than default application
 *
 * @throws AppManagerIntegrationTestException - occurred when calling the apis
 * @throws org.json.JSONException             - occurred when reading the json
 *///  w w  w  .j  ava2  s .c  o m
//  protected void cleanUp() throws Exception {
/*
AppMStoreRestClient apiStore = new AppMStoreRestClient(getStoreURLHttp());
apiStore.login(user.getUserName(), user.getPassword());
AppMPublisherRestClient publisherRestClient = new AppMPublisherRestClient(getPublisherURLHttp());
publisherRestClient.login(user.getUserName(), user.getPassword());
        
String apiData = apiStore.getAPI().getData();
JSONObject jsonAPIData = new JSONObject(apiData);
JSONArray jsonAPIArray = jsonAPIData.getJSONArray(AppMIntegrationConstants.API_RESPONSE_ELEMENT_NAME_APIS);
        
//delete all APIs
for (int i = 0; i < jsonAPIArray.length(); i++) {
    JSONObject api = jsonAPIArray.getJSONObject(i);
    publisherRestClient.deleteAPI(api.getString(AppMIntegrationConstants.API_RESPONSE_ELEMENT_NAME_API_NAME)
            , api.getString(AppMIntegrationConstants.API_RESPONSE_ELEMENT_NAME_API_VERSION),
                                  user.getUserName());
}
        
        
HttpResponse subscriptionDataResponse = apiStore.getAllSubscriptions();
verifyResponse(subscriptionDataResponse);
JSONObject jsonSubscription = new JSONObject(subscriptionDataResponse.getData());
        
if (!jsonSubscription.getBoolean(AppMIntegrationConstants.API_RESPONSE_ELEMENT_NAME_ERROR)) {
    JSONObject jsonSubscriptionsObject = jsonSubscription.getJSONObject(
            AppMIntegrationConstants.API_RESPONSE_ELEMENT_NAME_SUBSCRIPTION);
    JSONArray jsonApplicationsArray = jsonSubscriptionsObject.getJSONArray(
            AppMIntegrationConstants.API_RESPONSE_ELEMENT_NAME_APPLICATIONS);
        
    //Remove API Subscriptions
    for (int i = 0; i < jsonApplicationsArray.length(); i++) {
        JSONObject appObject = jsonApplicationsArray.getJSONObject(i);
        int id = appObject.getInt(AppMIntegrationConstants.API_RESPONSE_ELEMENT_NAME_ID);
        JSONArray subscribedAPIJSONArray = appObject.getJSONArray(
                AppMIntegrationConstants.API_RESPONSE_ELEMENT_NAME_SUBSCRIPTION);
        for (int j = 0; j < subscribedAPIJSONArray.length(); j++) {
            JSONObject subscribedAPI = subscribedAPIJSONArray.getJSONObject(j);
            verifyResponse(apiStore.removeAPISubscription(subscribedAPI.getString(
                                                                  AppMIntegrationConstants
                                                                          .API_RESPONSE_ELEMENT_NAME_API_NAME)
                    , subscribedAPI.getString(AppMIntegrationConstants.API_RESPONSE_ELEMENT_NAME_API_VERSION),
                                                          subscribedAPI.getString(
                                                                  AppMIntegrationConstants
                                                                          .API_RESPONSE_ELEMENT_NAME_API_PROVIDER),
                                                          String.valueOf(id)));
        }
    }
}
        
*/
//   }
protected void verifyResponse(HttpResponse httpResponse) throws JSONException {
    Assert.assertNotNull(httpResponse, "Response object is null");
    log.info("Response Code : " + httpResponse.getResponseCode());
    log.info("Response Message : " + httpResponse.getData());
    Assert.assertEquals(httpResponse.getResponseCode(), HttpStatus.SC_OK, "Response code is not as expected");
    JSONObject responseData = new JSONObject(httpResponse.getData());
    Assert.assertFalse(responseData.getBoolean(AppMIntegrationConstants.API_RESPONSE_ELEMENT_NAME_ERROR),
            "Error message received " + httpResponse.getData());

}

From source file:org.alfresco.integrations.google.docs.webscripts.DiscardContent.java

private Map<String, Serializable> parseContent(final WebScriptRequest req) {
    final Map<String, Serializable> result = new HashMap<String, Serializable>();
    Content content = req.getContent();/*w  w w  .j  a  v a2 s  .c o  m*/
    String jsonStr = null;
    JSONObject json = null;

    try {
        if (content == null || content.getSize() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        jsonStr = content.getContent();
        log.debug("Parsed JSON: " + jsonStr);

        if (jsonStr == null || jsonStr.trim().length() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        json = new JSONObject(jsonStr);

        if (!json.has(JSON_KEY_NODEREF)) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                    "Key " + JSON_KEY_NODEREF + " is missing from JSON: " + jsonStr);
        } else {
            NodeRef nodeRef = new NodeRef(json.getString(JSON_KEY_NODEREF));
            result.put(JSON_KEY_NODEREF, nodeRef);

            if (json.has(JSON_KEY_OVERRIDE)) {
                result.put(JSON_KEY_OVERRIDE, json.getBoolean(JSON_KEY_OVERRIDE));
            } else {
                result.put(JSON_KEY_OVERRIDE, false);
            }
        }
    } catch (final IOException ioe) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage(), ioe);
    } catch (final JSONException je) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON: " + jsonStr);
    } catch (final WebScriptException wse) {
        throw wse; // Ensure WebScriptExceptions get rethrown verbatim
    } catch (final Exception e) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON '" + jsonStr + "'.", e);
    }

    return result;
}

From source file:com.transistorsoft.cordova.bggeo.CDVBackgroundGeolocation.java

private void addGeofence(CallbackContext callbackContext, JSONObject config) {
    try {/* w  ww  . j  a  va  2  s  .  co  m*/
        String identifier = config.getString("identifier");
        final Bundle event = new Bundle();
        event.putString("name", BackgroundGeolocationService.ACTION_ADD_GEOFENCE);
        event.putBoolean("request", true);
        event.putFloat("radius", (float) config.getLong("radius"));
        event.putDouble("latitude", config.getDouble("latitude"));
        event.putDouble("longitude", config.getDouble("longitude"));
        event.putString("identifier", identifier);

        if (config.has("notifyOnEntry")) {
            event.putBoolean("notifyOnEntry", config.getBoolean("notifyOnEntry"));
        }
        if (config.has("notifyOnExit")) {
            event.putBoolean("notifyOnExit", config.getBoolean("notifyOnExit"));
        }
        if (config.has("notifyOnDwell")) {
            event.putBoolean("notifyOnDwell", config.getBoolean("notifyOnDwell"));
        }
        if (config.has("loiteringDelay")) {
            event.putInt("loiteringDelay", config.getInt("loiteringDelay"));
        }
        addGeofenceCallbacks.put(identifier, callbackContext);

        postEvent(event);

    } catch (JSONException e) {
        e.printStackTrace();
        callbackContext.error(e.getMessage());
    }
}

From source file:com.dnastack.bob.rest.BasicTest.java

private static String readField(JSONObject field, List<String> path) {
    for (int i = 1; i < path.size(); i++) {
        field = field.getJSONObject(path.get(i - 1));
    }//from   w ww  .j  a va2 s. co  m

    String loc = path.get(path.size() - 1);
    String res;
    try {
        res = field.getString(loc);
    } catch (JSONException je) {
        try {
            res = String.valueOf(field.getLong(loc));
        } catch (JSONException je2) {
            try {
                res = String.valueOf(field.getInt(loc));
            } catch (JSONException je3) {
                try {
                    res = String.valueOf(field.getBoolean(loc));
                } catch (JSONException je4) {
                    res = null;
                }
            }
        }
    }

    return res;
}

From source file:com.phonegap.ContactAccessorSdk5.java

/** 
 * This method takes the fields required and search options in order to produce an 
 * array of contacts that matches the criteria provided.
 * @param fields an array of items to be used as search criteria
 * @param options that can be applied to contact searching
 * @return an array of contacts /*from   w  w  w .j  ava2s  . co  m*/
 */
@Override
public JSONArray search(JSONArray fields, JSONObject options) {
    long totalEnd;
    long totalStart = System.currentTimeMillis();

    // Get the find options
    String searchTerm = "";
    int limit = Integer.MAX_VALUE;
    boolean multiple = true;

    if (options != null) {
        searchTerm = options.optString("filter");
        if (searchTerm.length() == 0) {
            searchTerm = "%";
        } else {
            searchTerm = "%" + searchTerm + "%";
        }
        try {
            multiple = options.getBoolean("multiple");
            if (!multiple) {
                limit = 1;
            }
        } catch (JSONException e) {
            // Multiple was not specified so we assume the default is true.
        }
    } else {
        searchTerm = "%";
    }

    //Log.d(LOG_TAG, "Search Term = " + searchTerm);
    //Log.d(LOG_TAG, "Field Length = " + fields.length());
    //Log.d(LOG_TAG, "Fields = " + fields.toString());

    // Loop through the fields the user provided to see what data should be returned.
    HashMap<String, Boolean> populate = buildPopulationSet(fields);

    // Build the ugly where clause and where arguments for one big query.
    WhereOptions whereOptions = buildWhereClause(fields, searchTerm);

    // Get all the id's where the search term matches the fields passed in.
    Cursor idCursor = mApp.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
            new String[] { ContactsContract.Data.CONTACT_ID }, whereOptions.getWhere(),
            whereOptions.getWhereArgs(), ContactsContract.Data.CONTACT_ID + " ASC");

    // Create a set of unique ids
    //Log.d(LOG_TAG, "ID cursor query returns = " + idCursor.getCount());
    Set<String> contactIds = new HashSet<String>();
    while (idCursor.moveToNext()) {
        contactIds.add(idCursor.getString(idCursor.getColumnIndex(ContactsContract.Data.CONTACT_ID)));
    }
    idCursor.close();

    // Build a query that only looks at ids
    WhereOptions idOptions = buildIdClause(contactIds, searchTerm);

    // Do the id query
    Cursor c = mApp.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, idOptions.getWhere(),
            idOptions.getWhereArgs(), ContactsContract.Data.CONTACT_ID + " ASC");

    //Log.d(LOG_TAG, "Cursor length = " + c.getCount());

    String contactId = "";
    String rawId = "";
    String oldContactId = "";
    boolean newContact = true;
    String mimetype = "";

    JSONArray contacts = new JSONArray();
    JSONObject contact = new JSONObject();
    JSONArray organizations = new JSONArray();
    JSONArray addresses = new JSONArray();
    JSONArray phones = new JSONArray();
    JSONArray emails = new JSONArray();
    JSONArray ims = new JSONArray();
    JSONArray websites = new JSONArray();
    JSONArray photos = new JSONArray();

    if (c.getCount() > 0) {
        while (c.moveToNext() && (contacts.length() <= (limit - 1))) {
            try {
                contactId = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
                rawId = c.getString(c.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));

                // If we are in the first row set the oldContactId
                if (c.getPosition() == 0) {
                    oldContactId = contactId;
                }

                // When the contact ID changes we need to push the Contact object 
                // to the array of contacts and create new objects.
                if (!oldContactId.equals(contactId)) {
                    // Populate the Contact object with it's arrays
                    // and push the contact into the contacts array
                    contacts.put(populateContact(contact, organizations, addresses, phones, emails, ims,
                            websites, photos));

                    // Clean up the objects
                    contact = new JSONObject();
                    organizations = new JSONArray();
                    addresses = new JSONArray();
                    phones = new JSONArray();
                    emails = new JSONArray();
                    ims = new JSONArray();
                    websites = new JSONArray();
                    photos = new JSONArray();

                    // Set newContact to true as we are starting to populate a new contact
                    newContact = true;
                }

                // When we detect a new contact set the ID and display name.
                // These fields are available in every row in the result set returned.
                if (newContact) {
                    newContact = false;
                    contact.put("id", contactId);
                    contact.put("rawId", rawId);
                    contact.put("displayName", c.getString(
                            c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME)));
                }

                // Grab the mimetype of the current row as it will be used in a lot of comparisons
                mimetype = c.getString(c.getColumnIndex(ContactsContract.Data.MIMETYPE));

                if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                        && isRequired("name", populate)) {
                    contact.put("name", nameQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                        && isRequired("phoneNumbers", populate)) {
                    phones.put(phoneQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                        && isRequired("emails", populate)) {
                    emails.put(emailQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
                        && isRequired("addresses", populate)) {
                    addresses.put(addressQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                        && isRequired("organizations", populate)) {
                    organizations.put(organizationQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
                        && isRequired("ims", populate)) {
                    ims.put(imQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
                        && isRequired("note", populate)) {
                    contact.put("note",
                            c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE)));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
                        && isRequired("nickname", populate)) {
                    contact.put("nickname",
                            c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME)));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
                        && isRequired("urls", populate)) {
                    websites.put(websiteQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)) {
                    if (ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY == c
                            .getInt(c.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE))
                            && isRequired("birthday", populate)) {
                        contact.put("birthday", c.getString(
                                c.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE)));
                    }
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                        && isRequired("photos", populate)) {
                    photos.put(photoQuery(c, contactId));
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }

            // Set the old contact ID 
            oldContactId = contactId;
        }

        // Push the last contact into the contacts array
        if (contacts.length() < limit) {
            contacts.put(
                    populateContact(contact, organizations, addresses, phones, emails, ims, websites, photos));
        }
    }
    c.close();

    totalEnd = System.currentTimeMillis();
    Log.d(LOG_TAG, "Total time = " + (totalEnd - totalStart));
    return contacts;
}