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.easy.facebook.android.apicall.GraphApi.java

private String uploadPhotoCall(String message, String friendIDorAlbumID, String urlPicture)
        throws EasyFacebookError {

    String postID = null;/* w  w  w  .j  av a 2 s  .com*/

    Bundle params = new Bundle();
    params.putString("format", "json");
    params.putString("access_token", facebook.getAccessToken());
    params.putString("message", message);

    if (urlPicture != null) {
        String pictureName = urlPicture.substring(urlPicture.lastIndexOf('/'), urlPicture.length());
        params.putByteArray(pictureName, Util.loadPicture(urlPicture));
    }

    if (friendIDorAlbumID == null)
        friendIDorAlbumID = "me";

    try {

        String jsonResponse = Util.openUrl("https://graph.facebook.com/" + friendIDorAlbumID + "/photos",
                "POST", params);

        JSONObject objectJSONErrorCheck = new JSONObject(jsonResponse);

        if (!objectJSONErrorCheck.isNull("error")) {
            throw new EasyFacebookError(jsonResponse);

        }

        JSONObject json = new JSONObject(jsonResponse);

        if (json.has("id"))
            postID = json.get("id").toString();

    } catch (MalformedURLException e) {

        throw new EasyFacebookError(e.toString(), "MalformedURLException");
    } catch (IOException e) {

        throw new EasyFacebookError(e.toString(), "IOException");
    } catch (JSONException e) {

        throw new EasyFacebookError(e.toString(), "JSONException");
    }

    return postID;

}

From source file:com.easy.facebook.android.apicall.GraphApi.java

private String createEventsCall(long startTime, long endTime, String name, String urlPicture, String privacy,
        String description, String location, String street, String city, String state, String country,
        String latitude, String longitude, String zip) throws EasyFacebookError {

    String eventID = null;/*from   ww  w .  j a  va  2 s . c  o m*/

    Bundle params = new Bundle();
    params.putString("format", "json");
    params.putString("access_token", facebook.getAccessToken());
    params.putString("start_time", Long.toString(startTime).substring(0, 10));
    params.putString("end_time", Long.toString(endTime).substring(0, 10));
    params.putString("name", name);
    params.putString("description", description);
    params.putString("location", location);
    params.putString("street", street);
    params.putString("city", city);
    params.putString("state", state);
    params.putString("country", country);
    params.putString("latitude", latitude);
    params.putString("longitude", longitude);
    params.putString("zip", zip);
    params.putString("privacy", privacy);

    if (urlPicture != null) {
        String pictureName = urlPicture.substring(urlPicture.lastIndexOf('/'), urlPicture.length());
        params.putByteArray(pictureName, Util.loadPicture(urlPicture));
    }

    try {

        String jsonResponse = Util.openUrl("https://graph.facebook.com/me/events", "POST", params);

        JSONObject objectJSONErrorCheck = new JSONObject(jsonResponse);

        if (!objectJSONErrorCheck.isNull("error")) {
            throw new EasyFacebookError(jsonResponse);

        }

        JSONObject json = new JSONObject(jsonResponse);

        if (json.has("id"))
            eventID = json.get("id").toString();

    } catch (MalformedURLException e) {

        throw new EasyFacebookError(e.toString(), "MalformedURLException");
    } catch (IOException e) {

        throw new EasyFacebookError(e.toString(), "IOException");
    } catch (JSONException e) {

        throw new EasyFacebookError(e.toString(), "JSONException");
    }

    return eventID;

}

From source file:com.easy.facebook.android.apicall.GraphApi.java

private String createAlbumCall(String albumName, String description, String location) throws EasyFacebookError {
    String albumID = "";
    Bundle params = new Bundle();
    params.putString("format", "json");
    params.putString("access_token", facebook.getAccessToken());

    params.putString("name", albumName);
    params.putString("message", description);
    params.putString("location", location);

    String jsonResponse;/*from   w ww  .  j av a 2 s  .co m*/
    try {
        jsonResponse = Util.openUrl("https://graph.facebook.com/me/albums", "POST", params);

        JSONObject objectJSONErrorCheck = new JSONObject(jsonResponse);

        if (!objectJSONErrorCheck.isNull("error")) {
            throw new EasyFacebookError(jsonResponse);

        }

        JSONObject json = new JSONObject(jsonResponse);

        if (json.has("id"))
            albumID = json.get("id").toString();

    } catch (MalformedURLException e) {

        throw new EasyFacebookError(e.toString(), "MalformedURLException");
    } catch (IOException e) {

        throw new EasyFacebookError(e.toString(), "IOException");
    } catch (JSONException e) {

        throw new EasyFacebookError(e.toString(), "JSONException");
    }

    return albumID;
}

From source file:com.easy.facebook.android.apicall.GraphApi.java

public String createFriendList(String frirndListName) throws EasyFacebookError {
    String frirndListID = "";
    Bundle params = new Bundle();
    params.putString("format", "json");
    params.putString("access_token", facebook.getAccessToken());

    params.putString("name", frirndListName);

    String jsonResponse;//w  w w. ja va2s  .  c  om
    try {
        jsonResponse = Util.openUrl("https://graph.facebook.com/me/friendlists", "POST", params);

        JSONObject json = new JSONObject(jsonResponse);

        if (json.has("id"))
            frirndListID = json.get("id").toString();

    } catch (MalformedURLException e) {

        throw new EasyFacebookError(e.toString(), "MalformedURLException");
    } catch (IOException e) {

        throw new EasyFacebookError(e.toString(), "IOException");
    } catch (JSONException e) {

        throw new EasyFacebookError(e.toString(), "JSONException");
    }

    return frirndListID;
}

From source file:cn.code.notes.gtask.data.SqlConn.java

public void setContent(JSONObject js) throws JSONException {

    String dataGUID = js.has(ConnectColumns.NOTE_GUID) ? js.getString(ConnectColumns.NOTE_GUID) : "";
    if (mIsCreate || mGuid.equals(dataGUID))
        mDiffDataValues.put(ConnectColumns.NOTE_GUID, dataGUID);
    mGuid = dataGUID;//from w w w.  ja  va2s. co m

    long dataId = js.has(ConnectColumns.NOTE_ID) ? js.getLong(ConnectColumns.NOTE_ID) : INVALID_ID;
    if (mIsCreate || mId != dataId) {
        mDiffDataValues.put(ConnectColumns.NOTE_ID, dataId);
    }
    mId = dataId;

    String dataMD5 = js.has(ConnectColumns.NOTE_DATA_MD5) ? js.getString(ConnectColumns.NOTE_DATA_MD5) : "";
    if (mIsCreate || mDataMD5.equals(dataMD5))
        mDiffDataValues.put(ConnectColumns.NOTE_GUID, dataMD5);
    mGuid = dataMD5;
}

From source file:com.yayandroid.utility.MapHelperFragment.java

/**
 * GoogleApis returns an address as jsonObject according to given
 * coordinate, and here we parse it to find necessary fields
 *//*from w  w  w  .j a v  a2s.  c om*/
private void fetchInformationUsingGoogleMap() {

    final AndroidHttpClient ANDROID_HTTP_CLIENT = AndroidHttpClient
            .newInstance(MapHelperFragment.class.getName());
    String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + myLocation.getLatitude()
            + "," + myLocation.getLongitude() + "&sensor=false&language=tr";
    try {
        JSONObject googleMapResponse = new JSONObject(
                ANDROID_HTTP_CLIENT.execute(new HttpGet(googleMapUrl), new BasicResponseHandler()));

        // many nested loops.. not great -> use expression instead
        // loop among all results
        JSONArray results = (JSONArray) googleMapResponse.get("results");
        for (int i = 0; i < results.length(); i++) {
            // loop among all addresses within this result
            JSONObject result = results.getJSONObject(i);
            if (result.has("address_components")) {
                JSONArray addressComponents = result.getJSONArray("address_components");

                for (int j = 0; j < addressComponents.length(); j++) {
                    JSONObject addressComponent = addressComponents.getJSONObject(j);
                    if (result.has("types")) {
                        JSONArray types = addressComponent.getJSONArray("types");

                        for (int k = 0; k < requiredInformations.length; k++) {

                            for (int l = 0; l < types.length(); l++) {
                                if (requiredInformations[k].type.value.equals(types.getString(l))) {
                                    if (addressComponent.has("long_name")) {
                                        PostInformation(requiredInformations[k].type,
                                                addressComponent.getString("long_name"));
                                    } else if (addressComponent.has("short_name")) {
                                        PostInformation(requiredInformations[k].type,
                                                addressComponent.getString("short_name"));
                                    }
                                }

                            }

                        }

                    }
                }
            }
        }
    } catch (Exception ignored) {
        ignored.printStackTrace();
    }
    ANDROID_HTTP_CLIENT.close();
}

From source file:org.dasein.cloud.joyent.compute.Machine.java

@Override
public @Nonnull Iterable<VirtualMachineProduct> listProducts(VirtualMachineProductFilterOptions options,
        Architecture architecture) throws InternalException, CloudException {
    Cache<VirtualMachineProduct> cache = Cache.getInstance(getProvider(), "VM.listProducts",
            VirtualMachineProduct.class, CacheLevel.REGION_ACCOUNT, TimePeriod.valueOf(1, "day"));
    final Iterable<VirtualMachineProduct> cachedProducts = cache.get(getContext());
    if (cachedProducts != null && cachedProducts.iterator().hasNext()) {
        return cachedProducts;
    }//from w ww. j  a  v a  2s. c  om
    JoyentMethod method = new JoyentMethod(provider);
    String json = method.doGetJson(provider.getEndpoint(), "packages");

    if (json == null) {
        return Collections.emptyList();
    }
    try {
        ArrayList<VirtualMachineProduct> products = new ArrayList<VirtualMachineProduct>();
        JSONArray list = new JSONArray(json);

        for (int i = 0; i < list.length(); i++) {
            JSONObject ob = list.getJSONObject(i);
            VirtualMachineProduct prd = new VirtualMachineProduct();

            if (ob.has("name")) {
                prd.setName(ob.getString("name"));
            }
            if (ob.has("memory")) {
                prd.setRamSize(new Storage<Megabyte>(ob.getInt("memory"), Storage.MEGABYTE));
            }
            if (ob.has("disk")) {
                prd.setRootVolumeSize(new Storage<Megabyte>(ob.getInt("disk"), Storage.MEGABYTE));
            }
            if (ob.has("vcpus")) {
                prd.setCpuCount(ob.getInt("vcpus"));
            }
            // SmartOS products are returned with 0 vCPUs as this metric doesn't apply
            // to them according to Joyent. In SmartOS you get some burstable capacity.
            // We will set them to 1 CPU anyway, as zero CPU is no CPU.
            if (prd.getCpuCount() == 0) {
                prd.setCpuCount(1);
            }
            if (ob.has("description")) {
                prd.setDescription(ob.getString("description"));
            } else {
                prd.setDescription(prd.getName());
            }
            prd.setProviderProductId(ob.getString("id"));
            if (options != null) {
                if (options.matches(prd))
                    products.add(prd);
            } else {
                products.add(prd);
            }
        }
        cache.put(getContext(), products);
        return products;
    } catch (JSONException e) {
        throw new CloudException(e);
    }
}

From source file:org.dasein.cloud.joyent.compute.Machine.java

@Override
public @Nullable String getPassword(@Nonnull String vmId) throws InternalException, CloudException {
    final String[] adminUsernames = { "root", "administrator", "admin" };
    JoyentMethod method = new JoyentMethod(provider);
    try {//from   w  w w .ja  v  a  2  s . co m
        JSONObject ob = new JSONObject(
                method.doGetJson(provider.getEndpoint(), "machines/" + vmId + "/metadata?credentials=true"));
        if (ob.has("credentials")) {
            JSONObject credentials = ob.getJSONObject("credentials");
            for (String username : adminUsernames) {
                if (ob.has(username)) {
                    return ob.getString(username);
                }
            }
        }
    } catch (JSONException e) {
        throw new InternalException("Unable to parse the response", e);
    }
    return null;
}

From source file:org.dasein.cloud.joyent.compute.Machine.java

@Override
public @Nullable String getUserData(@Nonnull String vmId) throws InternalException, CloudException {
    JoyentMethod method = new JoyentMethod(provider);
    try {/*  w  ww.  ja va 2  s  .  c o  m*/
        JSONObject ob = new JSONObject(
                method.doGetJson(provider.getEndpoint(), "machines/" + vmId + "/metadata"));
        if (ob.has("user-script")) {
            return ob.getString("user-script");
        }
    } catch (JSONException e) {
        throw new InternalException("Unable to parse the response", e);
    }
    return null;
}

From source file:org.dasein.cloud.joyent.compute.Machine.java

private VirtualMachine toVirtualMachine(JSONObject ob) throws CloudException, InternalException {
    if (ob == null) {
        return null;
    }//from w  ww .  j a  va  2  s  .  c  om
    try {
        VirtualMachine vm = new VirtualMachine();

        vm.setClonable(false);
        vm.setImagable(false);
        vm.setLastPauseTimestamp(-1L);
        vm.setPersistent(true);
        vm.setProviderDataCenterId(provider.getContext().getRegionId() + "a");
        vm.setProviderOwnerId(provider.getContext().getAccountNumber());
        vm.setProviderRegionId(provider.getContext().getRegionId());
        vm.setTerminationTimestamp(-1L);

        if (ob.has("id")) {
            vm.setProviderVirtualMachineId(ob.getString("id"));
        }
        if (ob.has("name")) {
            vm.setName(ob.getString("name"));
        }
        if (ob.has("ips")) {
            JSONArray ips = ob.getJSONArray("ips");
            ArrayList<String> pubIp = new ArrayList<String>();
            ArrayList<String> privIp = new ArrayList<String>();

            for (int i = 0; i < ips.length(); i++) {
                String addr = ips.getString(i);
                boolean pub = false;

                if (!addr.startsWith("10.") && !addr.startsWith("192.168.")) {
                    if (addr.startsWith("172.")) {
                        String[] nums = addr.split("\\.");

                        if (nums.length != 4) {
                            pub = true;
                        } else {
                            try {
                                int x = Integer.parseInt(nums[1]);

                                if (x < 16 || x > 31) {
                                    pub = true;
                                }
                            } catch (NumberFormatException ignore) {
                                // ignore
                            }
                        }
                    } else {
                        pub = true;
                    }
                }
                if (pub) {
                    pubIp.add(addr);
                } else {
                    privIp.add(addr);
                }
            }
            if (!pubIp.isEmpty()) {
                vm.setPublicIpAddresses(pubIp.toArray(new String[pubIp.size()]));
            }
            if (!privIp.isEmpty()) {
                vm.setPrivateIpAddresses(privIp.toArray(new String[privIp.size()]));
            }
        }
        if (ob.has("metadata")) {
            JSONObject md = ob.getJSONObject("metadata");
            JSONArray names = md.names();

            if (names != null) {
                for (int i = 0; i < names.length(); i++) {
                    String name = names.getString(i);

                    if (name.equals("dsnDescription")) {
                        vm.setDescription(md.getString(name));
                    } else if (name.equals("dsnTrueImage")) {
                        vm.setProviderMachineImageId(md.getString(name));
                    } else if (name.equals("dsnTrueProduct")) {
                        vm.setProductId(md.getString(name));
                    } else {
                        vm.addTag(name, md.getString(name));
                    }
                }
            }
        }
        if (vm.getProviderMachineImageId() == null && ob.has("dataset")) {
            vm.setProviderMachineImageId(getImageIdFromUrn(ob.getString("dataset")));
        }
        if (ob.has("created")) {
            vm.setCreationTimestamp(provider.parseTimestamp(ob.getString("created")));
        }
        vm.setPausable(false); // can't ever pause/resume joyent vms
        vm.setRebootable(false);
        if (ob.has("state")) {
            vm.setCurrentState(toState(ob.getString("state")));

            if (VmState.RUNNING.equals(vm.getCurrentState())) {
                vm.setRebootable(true);
            } else if (VmState.STOPPED.equals(vm.getCurrentState())) {
                vm.setImagable(true);
            }
        }
        vm.setLastBootTimestamp(vm.getCreationTimestamp());
        if (vm.getName() == null) {
            vm.setName(vm.getProviderVirtualMachineId());
        }
        if (vm.getDescription() == null) {
            vm.setDescription(vm.getName());
        }
        discover(vm);
        boolean isVMSmartOs = (vm.getPlatform().equals(Platform.SMARTOS));
        if (vm.getProductId() == null) {
            VirtualMachineProduct d = null;
            int disk, ram;

            disk = ob.getInt("disk");
            ram = ob.getInt("memory");
            for (VirtualMachineProduct prd : listProducts(vm.getArchitecture())) {
                d = prd;
                boolean isProductSmartOs = prd.getName().contains("smartos");
                if (prd.getRootVolumeSize().convertTo(Storage.MEGABYTE).intValue() == disk
                        && prd.getRamSize().intValue() == ram) {
                    if (isVMSmartOs && !isProductSmartOs) {
                        continue;
                    }
                    if (!isVMSmartOs && isProductSmartOs) {
                        continue;
                    }
                    vm.setProductId(prd.getProviderProductId());
                    break;
                }
            }
            if (vm.getProductId() == null) {
                vm.setProductId(d.getProviderProductId());
            }
        }
        return vm;
    } catch (JSONException e) {
        throw new CloudException(e);
    }
}