Example usage for org.json JSONObject has

List of usage examples for org.json JSONObject has

Introduction

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

Prototype

public boolean has(String key) 

Source Link

Document

Determine if the JSONObject contains a specific key.

Usage

From source file:com.tune.reporting.base.endpoints.EndpointBase.java

/**
 * Parse response and gather report url.
 *
 * @param response @see TuneServiceResponse
 *
 * @return String   Report URL download from Export queue.
 * @throws TuneSdkException If error within SDK.
 * @throws TuneServiceException If service fails to handle post request.
 *///ww w  . j  a  va 2 s.c o  m
public static String parseResponseReportUrl(final TuneServiceResponse response)
        throws IllegalArgumentException, TuneSdkException, TuneServiceException {

    if (null == response) {
        throw new IllegalArgumentException("Parameter 'response' is not defined.");
    }

    JSONObject jdata = (JSONObject) response.getData();
    if (null == jdata) {
        throw new TuneServiceException("Report export response failed to get data.");
    }

    if (!jdata.has("data")) {
        throw new TuneSdkException(
                String.format("Export data does not contain report 'data', response: %s", response.toString()));
    }

    JSONObject jdataInternal = null;
    try {
        jdataInternal = jdata.getJSONObject("data");
    } catch (JSONException ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    } catch (Exception ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    }

    if (null == jdataInternal) {
        throw new TuneServiceException(String
                .format("Export data response does not contain 'data', response: %s", response.toString()));
    }

    if (!jdataInternal.has("url")) {
        throw new TuneSdkException(String.format("Export response 'data' does not contain 'url', response: %s",
                response.toString()));
    }

    String jdataInternalUrl = null;
    try {
        jdataInternalUrl = jdataInternal.getString("url");
    } catch (JSONException ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    } catch (Exception ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    }

    if ((null == jdataInternalUrl) || jdataInternalUrl.isEmpty()) {
        throw new TuneSdkException(
                String.format("Export response 'url' is not defined, response: %s", response.toString()));
    }

    return jdataInternalUrl;
}

From source file:com.trk.aboutme.facebook.Request.java

private static void processGraphObjectProperty(String key, Object value, KeyValueSerializer serializer,
        boolean passByValue) throws IOException {
    Class<?> valueClass = value.getClass();
    if (GraphObject.class.isAssignableFrom(valueClass)) {
        value = ((GraphObject) value).getInnerJSONObject();
        valueClass = value.getClass();//  w  w w.j  a va  2  s  .com
    } else if (GraphObjectList.class.isAssignableFrom(valueClass)) {
        value = ((GraphObjectList<?>) value).getInnerJSONArray();
        valueClass = value.getClass();
    }

    if (JSONObject.class.isAssignableFrom(valueClass)) {
        JSONObject jsonObject = (JSONObject) value;
        if (passByValue) {
            // We need to pass all properties of this object in key[propertyName] format.
            @SuppressWarnings("unchecked")
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()) {
                String propertyName = keys.next();
                String subKey = String.format("%s[%s]", key, propertyName);
                processGraphObjectProperty(subKey, jsonObject.opt(propertyName), serializer, passByValue);
            }
        } else {
            // Normal case is passing objects by reference, so just pass the ID or URL, if any, as the value
            // for "key"
            if (jsonObject.has("id")) {
                processGraphObjectProperty(key, jsonObject.optString("id"), serializer, passByValue);
            } else if (jsonObject.has("url")) {
                processGraphObjectProperty(key, jsonObject.optString("url"), serializer, passByValue);
            }
        }
    } else if (JSONArray.class.isAssignableFrom(valueClass)) {
        JSONArray jsonArray = (JSONArray) value;
        int length = jsonArray.length();
        for (int i = 0; i < length; ++i) {
            String subKey = String.format("%s[%d]", key, i);
            processGraphObjectProperty(subKey, jsonArray.opt(i), serializer, passByValue);
        }
    } else if (String.class.isAssignableFrom(valueClass) || Number.class.isAssignableFrom(valueClass)
            || Boolean.class.isAssignableFrom(valueClass)) {
        serializer.writeString(key, value.toString());
    } else if (Date.class.isAssignableFrom(valueClass)) {
        Date date = (Date) value;
        // The "Events Timezone" platform migration affects what date/time formats Facebook accepts and returns.
        // Apps created after 8/1/12 (or apps that have explicitly enabled the migration) should send/receive
        // dates in ISO-8601 format. Pre-migration apps can send as Unix timestamps. Since the future is ISO-8601,
        // that is what we support here. Apps that need pre-migration behavior can explicitly send these as
        // integer timestamps rather than Dates.
        final SimpleDateFormat iso8601DateFormat = new SimpleDateFormat(ISO_8601_FORMAT_STRING, Locale.US);
        serializer.writeString(key, iso8601DateFormat.format(date));
    }
}

From source file:org.loklak.server.Authorization.java

public int getRequestFrequency(String path) {
    if (!this.json.has("frequency"))
        return -1;
    JSONObject paths = this.json.getJSONObject("frequency");
    if (!paths.has(path))
        return -1;
    return paths.getInt(path);
}

From source file:org.loklak.server.Authorization.java

public ClientService getService(String serviceId) {
    if (!this.json.has("services"))
        this.json.put("services", new JSONObject());
    JSONObject services = this.json.getJSONObject("services");
    if (!services.has(serviceId))
        return null;
    JSONObject s = services.getJSONObject(serviceId);
    ClientService service = new ClientService(serviceId);
    service.setMetadata(s.getJSONObject("meta"));
    return service;
}

From source file:com.habzy.syncontacts.platform.User.java

/**
 * Creates and returns an instance of the user from the provided JSON data.
 * //from w w w  .  j  a v  a2 s.co  m
 * @param user The JSONObject containing user data
 * @return user The new instance of Voiper user created from the JSON data.
 */
public static User valueOf(JSONObject user) {
    try {
        final String userName = user.getString("u");
        final String firstName = user.has("f") ? user.getString("f") : null;
        final String lastName = user.has("l") ? user.getString("l") : null;
        final String cellPhone = user.has("m") ? user.getString("m") : null;
        final String officePhone = user.has("o") ? user.getString("o") : null;
        final String homePhone = user.has("h") ? user.getString("h") : null;
        final String email = user.has("e") ? user.getString("e") : null;
        final boolean deleted = user.has("d") ? user.getBoolean("d") : false;
        final int userId = user.getInt("i");
        return new User(userName, firstName, lastName, cellPhone, officePhone, homePhone, email, deleted,
                userId);
    } catch (final Exception ex) {
        Log.i("User", "Error parsing JSON user object" + ex.toString());

    }
    return null;

}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

@Override
public Iterable<VirtualMachineProduct> listProducts(VirtualMachineProductFilterOptions options,
        Architecture architecture) throws InternalException, CloudException {
    ProviderContext ctx = getProvider().getContext();
    if (ctx == null) {
        throw new CloudException("No context was set for this request");
    }//from w w  w  .j  av a2  s .  com
    // FIXME: until core fixes the annotation for architecture let's assume it's nullable
    String cacheName = "productsALL";
    if (architecture != null) {
        cacheName = "products" + architecture.name();
    }
    Cache<VirtualMachineProduct> cache = Cache.getInstance(getProvider(), cacheName,
            VirtualMachineProduct.class, CacheLevel.REGION, new TimePeriod<Day>(1, TimePeriod.DAY));
    Iterable<VirtualMachineProduct> products = cache.get(ctx);

    if (products == null) {
        List<VirtualMachineProduct> list = new ArrayList<VirtualMachineProduct>();

        try {
            InputStream input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts.json");

            if (input != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder json = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    json.append(line);
                    json.append("\n");
                }
                JSONArray arr = new JSONArray(json.toString());
                JSONObject toCache = null;

                for (int i = 0; i < arr.length(); i++) {
                    JSONObject productSet = arr.getJSONObject(i);
                    String cloud, providerName;

                    if (productSet.has("cloud")) {
                        cloud = productSet.getString("cloud");
                    } else {
                        continue;
                    }
                    if (productSet.has("provider")) {
                        providerName = productSet.getString("provider");
                    } else {
                        continue;
                    }
                    if (!productSet.has("products")) {
                        continue;
                    }
                    if (toCache == null || (providerName.equals("AWS") && cloud.equals("AWS"))) {
                        toCache = productSet;
                    }
                    if (providerName.equalsIgnoreCase(getProvider().getProviderName())
                            && cloud.equalsIgnoreCase(getProvider().getCloudName())) {
                        toCache = productSet;
                        break;
                    }
                }
                if (toCache == null) {
                    logger.warn("No products were defined");
                    return Collections.emptyList();
                }
                JSONArray plist = toCache.getJSONArray("products");

                for (int i = 0; i < plist.length(); i++) {
                    JSONObject product = plist.getJSONObject(i);
                    boolean supported = false;

                    if (architecture != null) {
                        if (product.has("architectures")) {
                            JSONArray architectures = product.getJSONArray("architectures");

                            for (int j = 0; j < architectures.length(); j++) {
                                String a = architectures.getString(j);

                                if (architecture.name().equals(a)) {
                                    supported = true;
                                    break;
                                }
                            }
                        }
                        if (!supported) {
                            continue;
                        }
                    }
                    if (product.has("excludesRegions")) {
                        JSONArray regions = product.getJSONArray("excludesRegions");

                        for (int j = 0; j < regions.length(); j++) {
                            String r = regions.getString(j);

                            if (r.equals(ctx.getRegionId())) {
                                supported = false;
                                break;
                            }
                        }
                    }
                    if (!supported) {
                        continue;
                    }
                    VirtualMachineProduct prd = toProduct(product);

                    if (prd != null) {
                        if (options != null) {
                            if (options.matches(prd)) {
                                list.add(prd);
                            }
                        } else {
                            list.add(prd);
                        }
                    }

                }

            } else {
                logger.warn("No standard products resource exists for /org/dasein/cloud/aws/vmproducts.json");
            }
            input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts-custom.json");
            if (input != null) {
                ArrayList<VirtualMachineProduct> customList = new ArrayList<VirtualMachineProduct>();
                TreeSet<String> discard = new TreeSet<String>();
                boolean discardAll = false;

                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder json = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    json.append(line);
                    json.append("\n");
                }
                JSONArray arr = new JSONArray(json.toString());
                JSONObject toCache = null;

                for (int i = 0; i < arr.length(); i++) {
                    JSONObject listing = arr.getJSONObject(i);
                    String cloud, providerName, endpoint = null;

                    if (listing.has("cloud")) {
                        cloud = listing.getString("cloud");
                    } else {
                        continue;
                    }
                    if (listing.has("provider")) {
                        providerName = listing.getString("provider");
                    } else {
                        continue;
                    }
                    if (listing.has("endpoint")) {
                        endpoint = listing.getString("endpoint");
                    }
                    if (!cloud.equals(getProvider().getCloudName())
                            || !providerName.equals(getProvider().getProviderName())) {
                        continue;
                    }
                    if (endpoint != null && endpoint.equals(ctx.getCloud().getEndpoint())) {
                        toCache = listing;
                        break;
                    }
                    if (endpoint == null && toCache == null) {
                        toCache = listing;
                    }
                }
                if (toCache != null) {
                    if (toCache.has("discardDefaults")) {
                        discardAll = toCache.getBoolean("discardDefaults");
                    }
                    if (toCache.has("discard")) {
                        JSONArray dlist = toCache.getJSONArray("discard");

                        for (int i = 0; i < dlist.length(); i++) {
                            discard.add(dlist.getString(i));
                        }
                    }
                    if (toCache.has("products")) {
                        JSONArray plist = toCache.getJSONArray("products");

                        for (int i = 0; i < plist.length(); i++) {
                            JSONObject product = plist.getJSONObject(i);
                            boolean supported = false;
                            if (architecture != null) {

                                if (product.has("architectures")) {
                                    JSONArray architectures = product.getJSONArray("architectures");

                                    for (int j = 0; j < architectures.length(); j++) {
                                        String a = architectures.getString(j);

                                        if (architecture.name().equals(a)) {
                                            supported = true;
                                            break;
                                        }
                                    }
                                }
                                if (!supported) {
                                    continue;
                                }
                            }
                            if (product.has("excludesRegions")) {
                                JSONArray regions = product.getJSONArray("excludesRegions");

                                for (int j = 0; j < regions.length(); j++) {
                                    String r = regions.getString(j);

                                    if (r.equals(ctx.getRegionId())) {
                                        supported = false;
                                        break;
                                    }
                                }
                            }
                            if (!supported) {
                                continue;
                            }
                            VirtualMachineProduct prd = toProduct(product);

                            if (prd != null) {
                                customList.add(prd);
                            }
                        }
                    }
                    if (!discardAll) {
                        for (VirtualMachineProduct product : list) {
                            if (!discard.contains(product.getProviderProductId())) {
                                customList.add(product);
                            }
                        }
                    }
                    list = customList;
                }
            }
            products = list;
            cache.put(ctx, products);

        } catch (IOException e) {
            throw new InternalException(e);
        } catch (JSONException e) {
            throw new InternalException(e);
        }
    }
    return products;
}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

private @Nullable VirtualMachineProduct toProduct(@Nonnull JSONObject json) throws InternalException {
    /*//from  w  w w  .  j  av  a  2 s .  co m
            {
        "architectures":["I32"],
        "id":"m1.small",
        "name":"Small Instance (m1.small)",
        "description":"Small Instance (m1.small)",
        "cpuCount":1,
        "rootVolumeSizeInGb":160,
        "ramSizeInMb": 1700
    },
     */
    VirtualMachineProduct prd = new VirtualMachineProduct();

    try {
        if (json.has("id")) {
            prd.setProviderProductId(json.getString("id"));
        } else {
            return null;
        }
        if (json.has("name")) {
            prd.setName(json.getString("name"));
        } else {
            prd.setName(prd.getProviderProductId());
        }
        if (json.has("description")) {
            prd.setDescription(json.getString("description"));
        } else {
            prd.setDescription(prd.getName());
        }
        if (json.has("cpuCount")) {
            prd.setCpuCount(json.getInt("cpuCount"));
        } else {
            prd.setCpuCount(1);
        }
        if (json.has("rootVolumeSizeInGb")) {
            prd.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("rootVolumeSizeInGb"), Storage.GIGABYTE));
        } else {
            prd.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE));
        }
        if (json.has("ramSizeInMb")) {
            prd.setRamSize(new Storage<Megabyte>(json.getInt("ramSizeInMb"), Storage.MEGABYTE));
        } else {
            prd.setRamSize(new Storage<Megabyte>(512, Storage.MEGABYTE));
        }
        if (json.has("generation") && json.getString("generation").equalsIgnoreCase("previous")) {
            prd.setStatusDeprecated();
        }
        if (json.has("standardHourlyRates")) {
            JSONArray rates = json.getJSONArray("standardHourlyRates");

            for (int i = 0; i < rates.length(); i++) {
                JSONObject rate = rates.getJSONObject(i);

                if (rate.has("rate")) {
                    prd.setStandardHourlyRate((float) rate.getDouble("rate"));
                }
            }
        }
    } catch (JSONException e) {
        throw new InternalException(e);
    }
    return prd;
}

From source file:com.android.browser.GearsBaseDialog.java

/**
 * Utility method to set elements' text indicated in
 * the dialogs' arguments.// ww  w.  j a v  a2  s.c o  m
 */
void setLabel(JSONObject json, String name, int rsc) {
    try {
        if (json.has(name)) {
            String text = json.getString(name);
            View view = findViewById(rsc);
            if (view != null && text != null) {
                TextView textView = (TextView) view;
                textView.setText(text);
                textView.setVisibility(View.VISIBLE);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "json exception", e);
    }
}

From source file:org.wso2.carbon.connector.integration.test.meetup.boards.BoardsIntegrationTest.java

/**
 * Test getDiscussionBoards API operation for Mandatory fields.
 * Expecting Response header '200' and 'post_count' JSONObject in returned
 * JSONArray.//from   w  w w .  j  a  va2  s.c om
 *
 * @throws Exception if test fails.
 */
@Test(enabled = true, groups = {
        "wso2.esb" }, description = "Boards's getDiscussionBoards operation integration test for Mandatory fields")
public void testGetDiscussionBoardsMandatory() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "boards_getDiscussionBoards_mandatory.txt";
    String methodName = "boards_getBoard";

    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    String modifiedJsonString = String.format(jsonString,
            meetupConnectorProperties.getProperty("access_token"));
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {

        int responseHeader = ConnectorIntegrationUtil
                .sendRequestToRetriveHeaders(getProxyServiceURL(methodName), modifiedJsonString);
        Assert.assertTrue(responseHeader == 200);

        JSONArray jsonArray = ConnectorIntegrationUtil.sendRequestJSONArray(getProxyServiceURL(methodName),
                modifiedJsonString);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        Assert.assertTrue(jsonObject.has("post_count"));

    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.meetup.boards.BoardsIntegrationTest.java

/**
 * Test getDiscussionBoards API operation for negative scenario.
 * Expecting '401' request header and 'errors' element in returned
 * JSONObject.//  w  w w  . java2  s.  c om
 *
 * @throws Exception if test fails.
 */
@Test(enabled = true, groups = {
        "wso2.esb" }, description = "Board's getDiscussionBoards operation integration test for negative scenario.")
public void testGetDiscussionBoardsNegative() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "boards_getDiscussionBoards_negative.txt";
    String methodName = "boards_getBoard";

    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    /*
     * String modifiedJsonString = String.format(jsonString,
     * meetupConnectorProperties.getProperty("access_token"),
     * meetupConnectorProperties.getProperty("urlname")
     * );
     */
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {

        int responseHeader = ConnectorIntegrationUtil
                .sendRequestToRetriveHeaders(getProxyServiceURL(methodName), jsonString);
        Assert.assertTrue(responseHeader == 401);

        JSONObject jsonObject = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName),
                jsonString);
        Assert.assertTrue(jsonObject.has("errors"));

    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}