List of usage examples for org.json JSONObject isNull
public boolean isNull(String key)
From source file:de.fahrgemeinschaft.FahrgemeinschaftConnector.java
@Override public String publish(Ride offer) throws Exception { HttpURLConnection post;// w w w .ja v a 2 s . com if (offer.getRef() == null) { post = (HttpURLConnection) new URL(endpoint + TRIP).openConnection(); post.setRequestMethod(POST); } else { post = (HttpURLConnection) new URL( new StringBuffer().append(endpoint).append(TRIP).append(ID).append(offer.getRef()).toString()) .openConnection(); post.setRequestMethod(PUT); } post.setRequestProperty("User-Agent", USER_AGENT); post.setRequestProperty(APIKEY, Secret.APIKEY); if (getAuth() != null) post.setRequestProperty(AUTHKEY, getAuth()); post.setDoOutput(true); JSONObject json = new JSONObject(); // json.put("Smoker", "no"); json.put(TRIPTYPE, OFFER); json.put(TRIP_ID, offer.getRef()); json.put(ID_USER, get(USER)); if (offer.getMode() != null && offer.getMode().equals(Mode.TRAIN)) { json.put(PLATE, BAHN); } else { json.put(PLATE, offer.get(PLATE)); } if (offer.isActive()) { json.put(RELEVANCE, 10); } else { json.put(RELEVANCE, 0); } json.put(PLACES, offer.getSeats()); json.put(PRICE, offer.getPrice() / 100); json.put(CONTACTMAIL, offer.get(EMAIL)); json.put(CONTACTMOBILE, offer.get(MOBILE)); json.put(CONTACTLANDLINE, offer.get(LANDLINE)); String dep = fulldf.format(offer.getDep()); json.put(STARTDATE, dep.subSequence(0, 8)); json.put(STARTTIME, dep.subSequence(8, 12)); json.put(DESCRIPTION, offer.get(COMMENT)); if (!offer.getDetails().isNull(PRIVACY)) json.put(PRIVACY, offer.getDetails().getJSONObject(PRIVACY)); if (!offer.getDetails().isNull(REOCCUR)) json.put(REOCCUR, offer.getDetails().getJSONObject(REOCCUR)); ArrayList<JSONObject> routings = new ArrayList<JSONObject>(); List<Place> stops = offer.getPlaces(); int max = stops.size() - 1; for (int dest = max; dest >= 0; dest--) { for (int orig = 0; orig < dest; orig++) { int idx = (orig == 0 ? (dest == max ? 0 : dest) : -dest); JSONObject route = new JSONObject(); route.put(ROUTING_INDEX, idx); route.put(ORIGIN, place(stops.get(orig))); route.put(DESTINATION, place(stops.get(dest))); routings.add(route); } } json.put(ROUTINGS, new JSONArray(routings)); OutputStreamWriter out = new OutputStreamWriter(post.getOutputStream()); out.write(json.toString()); out.flush(); out.close(); JSONObject response = loadJson(post); if (!response.isNull(TRIP_ID_WITH_SMALL_t)) { offer.ref(response.getString(TRIP_ID_WITH_SMALL_t)); } return offer.getRef(); }
From source file:org.dasein.cloud.cloudsigma.compute.image.BootDriveSupport.java
public @Nonnull JSONObject cloneDrive(@Nonnull String driveId, @Nonnull String name, Platform os) throws CloudException, InternalException { JSONObject currentDrive = getDrive(driveId); if (currentDrive == null) { throw new CloudException("No such drive: " + driveId); }// ww w. j a v a 2s. c om try { logger.debug("Cloning volume: " + driveId + " with new name " + name); JSONObject newDrive = new JSONObject(); newDrive.put("name", name.replaceAll("\n", " ")); CloudSigmaMethod method = new CloudSigmaMethod(provider); JSONObject jDrive = null; //dmayne 20130529: determine if this is private or library drive boolean publicImage = false; if (currentDrive.has("image_type")) { publicImage = true; //library image: now check it is definitely a disk and not CDROM if (currentDrive.has("media") && !currentDrive.isNull("media")) { String media = currentDrive.getString("media"); if (media.equalsIgnoreCase("cdrom")) { logger.info("Can't clone drive as image is cdrom"); throw new InternalException("Can't clone drive as image is cdrom"); } } else { throw new CloudException("Can't clone drive: unknown media " + driveId); } } JSONObject obj; if (publicImage) { obj = new JSONObject( method.postString(toPublicImageURL(driveId, "action/?do=clone"), newDrive.toString())); } else { obj = new JSONObject( method.postString(toDriveURL(driveId, "action/?do=clone"), newDrive.toString())); } if (obj != null) { jDrive = (JSONObject) obj; } if (jDrive == null) { throw new CloudException("Clone supposedly succeeded, but no drive information was provided"); } return jDrive; } catch (JSONException e) { throw new InternalException(e); } }
From source file:org.dasein.cloud.cloudsigma.compute.image.BootDriveSupport.java
public @Nullable JSONObject getDrive(String driveId) throws CloudException, InternalException { CloudSigmaMethod method = new CloudSigmaMethod(provider); String body = method.getString(toDriveURL(driveId, "")); try {//from w w w . j a v a 2 s . com JSONObject jDrive = null; if (body != null) { jDrive = new JSONObject(body); //dmayne 20130529: library drive can be returned in above call // check if owner is null and if so, call the library endpoint if (!jDrive.has("owner") || jDrive.isNull("owner")) { jDrive = null; } } if (jDrive == null) { logger.debug("Failed " + driveId + ", looking in library..."); body = method.getString(toPublicImageURL(driveId, "")); if (body != null) { jDrive = new JSONObject(body); } logger.debug("SUCCESS: " + (jDrive != null)); } return jDrive; } catch (JSONException e) { throw new InternalException(e); } }
From source file:org.dasein.cloud.cloudsigma.compute.image.BootDriveSupport.java
private @Nonnull Iterable<MachineImage> listImagesComplete(@Nullable String accountId) throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new NoContextException(); }/*w w w .j av a 2 s . c o m*/ String me = ctx.getAccountNumber(); if (me.equals(accountId)) { return listImages(ImageClass.MACHINE); } else if (accountId == null || accountId.equals("")) { accountId = "00000000-0000-0000-0000-000000000001"; } ArrayList<MachineImage> list = new ArrayList<MachineImage>(); CloudSigmaMethod method = new CloudSigmaMethod(provider); boolean moreData = true; String baseTarget = "/libdrives/detail/?limit=0"; String target = ""; // while(moreData) { - commented out as it seems paging is no longer supported // but who knows when the api will change back again //dmayne 20130218: JSON Parsing target = baseTarget + target; JSONObject jObj = method.list(target); try { if (jObj == null) { throw new CloudException("Could not identify drive endpoint for CloudSigma"); } if (jObj.has("objects")) { JSONArray objects = jObj.getJSONArray("objects"); for (int i = 0; i < objects.length(); i++) { JSONObject jImage = objects.getJSONObject(i); String id = null; if (jImage.has("owner") && jImage.isNull("owner")) { id = "00000000-0000-0000-0000-000000000001"; } if (accountId.equals(id)) { MachineImage img = toPublicMachineImage(jImage); if (img != null) { list.add(img); } } } } /* //dmayne 20130314: check if there are more pages - commented out as it seems paging is no longer supported but who knows when the api will change back again if (jObj.has("meta")) { JSONObject meta = jObj.getJSONObject("meta"); if (meta.has("next") && !(meta.isNull("next")) && !meta.getString("next").equals("")) { target = meta.getString("next"); target = target.substring(target.indexOf("?")); moreData = true; } else { moreData = false; } } */ } catch (JSONException e) { throw new InternalException(e); } // } return list; }
From source file:org.dasein.cloud.cloudsigma.compute.image.BootDriveSupport.java
@Override public @Nonnull Iterable<MachineImage> searchPublicImages(@Nonnull ImageFilterOptions options) throws InternalException, CloudException { if (options.getImageClass() != null && !ImageClass.MACHINE.equals(options.getImageClass())) { return Collections.emptyList(); }/*from w w w . j a v a 2s. c om*/ ArrayList<MachineImage> matches = new ArrayList<MachineImage>(); CloudSigmaMethod method = new CloudSigmaMethod(provider); boolean moreData = true; String baseTarget = "/libdrives/detail/?limit=0"; String target = ""; // while(moreData) { - commented out as it seems paging is no longer supported // but who knows when the api will change back again target = baseTarget + target; JSONObject jObject = method.list(target); try { if (jObject == null) { throw new CloudException("Could not identify drive endpoint for CloudSigma"); } if (jObject.has("objects")) { JSONArray objects = jObject.getJSONArray("objects"); for (int i = 0; i < objects.length(); i++) { JSONObject jImage = objects.getJSONObject(i); String id = null; if (jImage.has("owner") && jImage.isNull("owner")) { id = "00000000-0000-0000-0000-000000000001"; } if (id == null || id.equals("00000000-0000-0000-0000-000000000001")) { MachineImage img = toPublicMachineImage(jImage); if (img != null && options.matches(img)) { matches.add(img); } } } } /*//dmayne 20130314: check if there are more pages - commented out as it seems paging is no longer supported but who knows when the api will change back again if (jObject.has("meta")) { JSONObject meta = jObject.getJSONObject("meta"); if (meta.has("next") && !(meta.isNull("next")) && !meta.getString("next").equals("")) { target = meta.getString("next"); target = target.substring(target.indexOf("?")); moreData = true; } else { moreData = false; } } */ } catch (JSONException e) { throw new InternalException(e); } // } return matches; }
From source file:org.dasein.cloud.cloudsigma.compute.image.BootDriveSupport.java
private @Nullable MachineImage toMachineImage(@Nullable JSONObject drive) throws CloudException, InternalException { if (drive == null) { logger.debug("drive is null"); return null; }/*from w ww . j a v a 2 s. c o m*/ try { if (drive.has("image_type")) { //dmayne 20130529: this is a library drive return toPublicMachineImage(drive); } ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new NoContextException(); } String regionId = ctx.getRegionId(); if (regionId == null) { throw new CloudSigmaConfigurationException("No region was specified for this request"); } MachineImage image = new MachineImage(); image.setProviderRegionId(regionId); image.setCurrentState(MachineImageState.PENDING); image.setType(MachineImageType.VOLUME); image.setImageClass(ImageClass.MACHINE); String id = drive.getString("uuid"); if (id != null && !id.equals("")) { image.setProviderMachineImageId(id); } String name = drive.getString("name"); if (name != null && !name.equals("")) { image.setName(name); } String description = null; String os = null; String install_notes = null; if (drive.has("meta")) { JSONObject meta = drive.getJSONObject("meta"); //dmayne 20130220: look for description tag and if not available check install_notes if (meta != null) { if (meta.has("description")) { description = meta.getString("description"); } if (description == null || description.length() == 0) { if (meta.has("install_notes")) { install_notes = meta.getString("install_notes"); } } if (meta.has("os")) { os = meta.getString("os"); } String bits = null; if (meta.has("arch")) { bits = meta.getString("arch"); } if (bits != null && bits.contains("32")) { image.setArchitecture(Architecture.I32); } else { image.setArchitecture(Architecture.I64); } } if (description != null && !description.equals("")) { image.setDescription(description); } else if (install_notes != null && !install_notes.equals("")) { image.setDescription(install_notes); } } String user = null; if (drive.has("owner") && !drive.isNull("owner")) { JSONObject owner = drive.getJSONObject("owner"); if (owner != null && owner.has("uuid")) { user = owner.getString("uuid"); } } if (user != null && !user.equals("")) { image.setProviderOwnerId(user); } else { image.setProviderOwnerId("00000000-0000-0000-0000-000000000001"); } String s = drive.getString("status"); if (s != null) { if (s.equalsIgnoreCase("unmounted") || s.equals("mounted")) { image.setCurrentState(MachineImageState.ACTIVE); } else if (s.equalsIgnoreCase("copying")) { image.setCurrentState(MachineImageState.PENDING); } else if (s.equalsIgnoreCase("unavailable")) { image.setCurrentState(MachineImageState.DELETED); } else { logger.warn("WARN: Unknown drive state for CloudSigma: " + s); } /* if (s.equalsIgnoreCase("mounted") ) { image.setCurrentState(MachineImageState.ACTIVE); } else if (s.equalsIgnoreCase("unmounted") || s.equalsIgnoreCase("unavailable")) { image.setCurrentState(MachineImageState.DELETED); } else if (s.startsWith("copying")) { image.setCurrentState(MachineImageState.PENDING); } else { logger.warn("WARN: Unknown drive state for CloudSigma: " + s); } */ } if (MachineImageState.ACTIVE.equals(image.getCurrentState())) { s = null; //todo: dmayne 20130305: not implemented by cloudsigma yet if (drive.has("imaging")) { s = drive.getString("imaging"); } if (s != null) { image.setCurrentState(MachineImageState.PENDING); } } String size = null; size = drive.getString("size"); if (size != null) { try { image.setTag("size", new Storage<org.dasein.util.uom.storage.Byte>(Long.parseLong(size), Storage.BYTE) .toString()); } catch (NumberFormatException ignore) { logger.warn("Unknown size value: " + size); } } String media = drive.getString("media"); image.setTag("media", media); String software = null; if (drive.has("licenses")) { JSONArray licences = drive.getJSONArray("licenses"); for (int i = 0; i < licences.length(); i++) { JSONObject jlicense = licences.getJSONObject(i); if (jlicense.has("licenses")) { software = jlicense.getString("licenses"); } if (software != null) { image.setSoftware(software); break; } else { image.setSoftware(""); } } } if (image.getSoftware() == null) { image.setSoftware(""); } Platform platform = Platform.UNKNOWN; if (os != null && !os.equals("")) { platform = Platform.guess(os); } if (platform.equals(Platform.UNKNOWN)) { platform = Platform.guess(image.getName()); if (platform.equals(Platform.UNKNOWN)) { //check description followed by install notes platform = Platform.guess(image.getDescription()); if (platform.equals(Platform.UNKNOWN)) { platform = Platform.guess(install_notes); } } } else if (platform.equals(Platform.UNIX)) { Platform p = Platform.guess(image.getName()); if (!p.equals(Platform.UNKNOWN)) { platform = p; } } image.setPlatform(platform); if (image.getProviderOwnerId() == null) { image.setProviderOwnerId(ctx.getAccountNumber()); } if (image.getProviderMachineImageId() == null) { return null; } if (image.getName() == null) { image.setName(image.getProviderMachineImageId()); } if (image.getDescription() == null) { image.setDescription(image.getName()); } return image; } catch (JSONException e) { throw new InternalException(e); } }
From source file:org.dasein.cloud.cloudsigma.compute.image.BootDriveSupport.java
private @Nullable MachineImage toPublicMachineImage(@Nullable JSONObject drive) throws CloudException, InternalException { if (drive == null) { logger.debug("drive is null"); return null; }//from ww w. ja v a 2 s . c om try { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new NoContextException(); } String regionId = ctx.getRegionId(); if (regionId == null) { throw new CloudSigmaConfigurationException("No region was specified for this request"); } MachineImage image = new MachineImage(); image.setProviderRegionId(regionId); image.setCurrentState(MachineImageState.PENDING); image.setType(MachineImageType.VOLUME); image.setImageClass(ImageClass.MACHINE); String id = drive.getString("uuid"); if (id != null && !id.equals("")) { image.setProviderMachineImageId(id); } String name = drive.getString("name"); if (name != null && !name.equals("")) { image.setName(name); } String description = null; String os = null; String install_notes = null; if (drive.has("description")) { description = drive.getString("description"); } if (drive.has("install_notes")) { install_notes = drive.getString("install_notes"); } if (drive.has("os")) { os = drive.getString("os"); } String bits = null; if (drive.has("arch")) { bits = drive.getString("arch"); } if (bits != null && bits.contains("32")) { image.setArchitecture(Architecture.I32); } else { image.setArchitecture(Architecture.I64); } if (description != null && !description.equals("")) { image.setDescription(description); } else if (install_notes != null && !install_notes.equals("")) { image.setDescription(install_notes); } String user = null; if (drive.has("owner") && !drive.isNull("owner")) { JSONObject owner = drive.getJSONObject("owner"); if (owner != null && owner.has("uuid")) { user = owner.getString("uuid"); } } if (user != null && !user.equals("")) { image.setProviderOwnerId(user); } else { image.setProviderOwnerId("00000000-0000-0000-0000-000000000001"); } String s = drive.getString("status"); if (s != null) { if (s.equalsIgnoreCase("unmounted") || s.equals("mounted")) { image.setCurrentState(MachineImageState.ACTIVE); } else if (s.equalsIgnoreCase("copying")) { image.setCurrentState(MachineImageState.PENDING); } else if (s.equalsIgnoreCase("unavailable")) { image.setCurrentState(MachineImageState.DELETED); } else { logger.warn("WARN: Unknown drive state for CloudSigma: " + s); } } String size = null; size = drive.getString("size"); if (size != null) { try { image.setTag("size", new Storage<org.dasein.util.uom.storage.Byte>(Long.parseLong(size), Storage.BYTE) .toString()); } catch (NumberFormatException ignore) { logger.warn("Unknown size value: " + size); } } String media = drive.getString("media"); image.setTag("media", media); String software = null; if (drive.has("licenses") && !drive.isNull("licenses")) { JSONArray licences = drive.getJSONArray("licenses"); for (int i = 0; i < licences.length(); i++) { JSONObject jlicense = licences.getJSONObject(i); if (jlicense.has("license") && !jlicense.isNull("license")) { JSONObject li = jlicense.getJSONObject("license"); if (li.has("long_name") && !li.isNull("long_name")) { software = li.getString("long_name"); } } if (software != null) { image.setSoftware(software); break; } else { image.setSoftware(""); } } } if (image.getSoftware() == null) { image.setSoftware(""); } Platform platform = Platform.UNKNOWN; if (os != null && !os.equals("")) { platform = Platform.guess(os); } if (platform.equals(Platform.UNKNOWN)) { platform = Platform.guess(image.getName()); if (platform.equals(Platform.UNKNOWN)) { //check description followed by install notes platform = Platform.guess(image.getDescription()); if (platform.equals(Platform.UNKNOWN)) { platform = Platform.guess(install_notes); } } } else if (platform.equals(Platform.UNIX)) { Platform p = Platform.guess(image.getName()); if (!p.equals(Platform.UNKNOWN)) { platform = p; } } image.setPlatform(platform); if (image.getProviderOwnerId() == null) { image.setProviderOwnerId(ctx.getAccountNumber()); } if (image.getProviderMachineImageId() == null) { return null; } if (image.getName() == null) { image.setName(image.getProviderMachineImageId()); } if (image.getDescription() == null) { image.setDescription(image.getName()); } return image; } catch (JSONException e) { throw new InternalException(e); } }
From source file:com.ammobyte.radioreddit.api.GetSongInfo.java
@Override protected Boolean doInBackground(String... params) { final String cookie = params[0]; // This will be null if not logged in // Prepare GET with cookie, execute it, parse response as JSON JSONObject response = null;/* w w w . j a v a2s. c om*/ try { final HttpClient httpClient = new DefaultHttpClient(); final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("url", mSong.reddit_url)); final HttpGet httpGet = new HttpGet( "http://www.reddit.com/api/info.json?" + URLEncodedUtils.format(nameValuePairs, "utf-8")); if (cookie != null) { // Using HttpContext, CookieStore, and friends didn't work httpGet.setHeader("Cookie", "reddit_session=" + cookie); } httpGet.setHeader("User-Agent", RedditApi.USER_AGENT); final HttpResponse httpResponse = httpClient.execute(httpGet); response = new JSONObject(EntityUtils.toString(httpResponse.getEntity())); } catch (UnsupportedEncodingException e) { Log.i(RedditApi.TAG, "UnsupportedEncodingException while getting song info", e); } catch (ClientProtocolException e) { Log.i(RedditApi.TAG, "ClientProtocolException while getting song info", e); } catch (IOException e) { Log.i(RedditApi.TAG, "IOException while getting song info", e); } catch (ParseException e) { Log.i(RedditApi.TAG, "ParseException while getting song info", e); } catch (JSONException e) { Log.i(RedditApi.TAG, "JSONException while getting song info", e); } // Check for failure if (response == null) { Log.i(RedditApi.TAG, "Response is null"); return false; } // Get the info we want final JSONObject data1 = response.optJSONObject("data"); if (data1 == null) { Log.i(RedditApi.TAG, "First data is null"); return false; } final String modhash = data1.optString("modhash", ""); if (modhash.length() > 0) { mService.setModhash(modhash); } final JSONArray children = data1.optJSONArray("children"); if (children == null) { Log.i(RedditApi.TAG, "Children is null"); return false; } final JSONObject child = children.optJSONObject(0); if (child == null) { // This is common if the song hasn't been submitted to reddit yet // so we intentionally don't log this case return false; } final String kind = child.optString("kind"); if (kind == null) { Log.i(RedditApi.TAG, "Kind is null"); return false; } final JSONObject data2 = child.optJSONObject("data"); if (data2 == null) { Log.i(RedditApi.TAG, "Second data is null"); return false; } final String id = data2.optString("id"); if (id == null) { Log.i(RedditApi.TAG, "Id is null"); return false; } final int score = data2.optInt("score"); Boolean likes = null; if (!data2.isNull("likes")) { likes = data2.optBoolean("likes"); } final boolean saved = data2.optBoolean("saved"); // Modify song with collected info if (kind != null && id != null) { mSong.reddit_id = kind + "_" + id; } else { mSong.reddit_id = null; } mSong.upvoted = (likes != null && likes == true); mSong.downvoted = (likes != null && likes == false); mSong.votes = score; mSong.saved = saved; return true; }
From source file:edu.isi.misd.tagfiler.download.FileDownloadImplementation.java
/** * Sets the values for the custom tags of the dataset to be downloaded. * /*w w w .j av a 2 s . c o m*/ * @throws UnsupportedEncodingException */ private void setCustomTags() throws UnsupportedEncodingException, FatalException { JSONObject tagsValues = getDatasetTagValues(); Set<String> tags = customTagMap.getTagNames(); StringBuffer buffer = new StringBuffer(); for (String tag : tags) { String value = ""; try { if (!tagsValues.isNull(tag)) { value = tagsValues.getString(tag); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } buffer.append(tag).append("<br/>").append(value).append("<br/>"); customTagMap.setValue(tag, value); } String values = buffer.toString().replaceAll("'", "\\\\'"); applet.eval("setTags", values); }
From source file:edu.isi.misd.tagfiler.download.FileDownloadImplementation.java
/** * Gets the files to be downloaded.//from w w w . j a v a 2 s . c om */ private boolean getDataSet() throws Exception { boolean result = false; try { // get the "bytes" and "sha256sum" tags of the files JSONArray tagsValues = getFilesTagValues(applet, fileDownloadListener); if (tagsValues != null) { // get the number of files to be downloaded // by replacing a file with an URL, we might have have fewer files to be downloaded int totalFiles = tagsValues.length(); for (int i = 0; i < tagsValues.length(); i++) { if (tagsValues.getJSONObject(i).isNull(BYTES)) { totalFiles--; } } if (totalFiles > 0) { fileDownloadListener.notifyRetrieveStart(totalFiles); for (int i = 0; i < tagsValues.length(); i++) { JSONObject fileTags = tagsValues.getJSONObject(i); // make sure we have a file if (fileTags.isNull(BYTES)) { continue; } // get the file name String file = fileTags.getString(NAME).substring(dataset.length() + 1); fileNames.add(file); // get the bytes long bytes = fileTags.getLong(BYTES); datasetSize += bytes; bytesMap.put(file, bytes); // get the version String vname = fileTags.getString(VNAME); int version = Integer.parseInt(vname.substring(vname.lastIndexOf("@") + 1)); versionMap.put(file, version); // get the checksum if (!fileTags.isNull(SHA256SUM)) { String checksum = fileTags.getString(SHA256SUM); checksumMap.put(file, checksum); } fileDownloadListener.notifyFileRetrieveComplete(file); } } } result = true; } catch (Exception e) { e.printStackTrace(); fileDownloadListener.notifyError(e); result = false; } return result; }