Example usage for org.json JSONObject isNull

List of usage examples for org.json JSONObject isNull

Introduction

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

Prototype

public boolean isNull(String key) 

Source Link

Document

Determine if the value associated with the key is null or if there is no value.

Usage

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

private static Geocache parseCache(final JSONObject response) {
    final Geocache cache = new Geocache();
    cache.setReliableLatLon(true);// w w w .  j  a  v a  2  s .com
    try {

        parseCoreCache(response, cache);

        // not used: url
        final JSONObject owner = response.getJSONObject(CACHE_OWNER);
        cache.setOwnerDisplayName(parseUser(owner));

        cache.getLogCounts().put(LogType.FOUND_IT, response.getInt(CACHE_FOUNDS));
        cache.getLogCounts().put(LogType.DIDNT_FIND_IT, response.getInt(CACHE_NOTFOUNDS));

        if (!response.isNull(CACHE_RATING)) {
            cache.setRating((float) response.getDouble(CACHE_RATING));
        }
        cache.setVotes(response.getInt(CACHE_VOTES));

        cache.setFavoritePoints(response.getInt(CACHE_RECOMMENDATIONS));
        // not used: req_password
        // Prepend gc-link to description if available
        final StringBuilder description = new StringBuilder(500);
        if (!response.isNull("gc_code")) {
            final String gccode = response.getString("gc_code");
            description
                    .append(CgeoApplication.getInstance().getResources().getString(R.string.cache_listed_on,
                            GCConnector.getInstance().getName()))
                    .append(": <a href=\"http://coord.info/").append(gccode).append("\">").append(gccode)
                    .append("</a><br /><br />");
        }
        description.append(response.getString(CACHE_DESCRIPTION));
        cache.setDescription(description.toString());

        // currently the hint is delivered as HTML (contrary to OKAPI documentation), so we can store it directly
        cache.setHint(response.getString(CACHE_HINT));
        // not used: hints

        final JSONArray images = response.getJSONArray(CACHE_IMAGES);
        if (images != null) {
            for (int i = 0; i < images.length(); i++) {
                final JSONObject imageResponse = images.getJSONObject(i);
                final String title = imageResponse.getString(CACHE_IMAGE_CAPTION);
                final String url = absoluteUrl(imageResponse.getString(CACHE_IMAGE_URL), cache.getGeocode());
                // all images are added as spoiler images, although OKAPI has spoiler and non spoiler images
                cache.addSpoiler(new Image(url, title));
            }
        }

        cache.setAttributes(parseAttributes(response.getJSONArray(CACHE_ATTRNAMES),
                response.optJSONArray(CACHE_ATTR_ACODES)));
        cache.setLogs(parseLogs(response.getJSONArray(CACHE_LATEST_LOGS)));
        //TODO: Store license per cache
        //cache.setLicense(response.getString("attribution_note"));
        cache.setWaypoints(parseWaypoints(response.getJSONArray(CACHE_WPTS)), false);
        if (!response.isNull(CACHE_IS_WATCHED)) {
            cache.setOnWatchlist(response.getBoolean(CACHE_IS_WATCHED));
        }
        if (!response.isNull(CACHE_MY_NOTES)) {
            cache.setPersonalNote(response.getString(CACHE_MY_NOTES));
            cache.parseWaypointsFromNote();
        }
        cache.setLogPasswordRequired(response.getBoolean(CACHE_REQ_PASSWORD));

        cache.setDetailedUpdatedNow();
        // save full detailed caches
        DataStore.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
    } catch (final JSONException e) {
        Log.e("OkapiClient.parseCache", e);
    }
    return cache;
}

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

private static void parseCoreCache(final JSONObject response, final Geocache cache) throws JSONException {
    cache.setGeocode(response.getString(CACHE_CODE));
    cache.setName(response.getString(CACHE_NAME));
    // not used: names
    setLocation(cache, response.getString(CACHE_LOCATION));
    cache.setType(getCacheType(response.getString(CACHE_TYPE)));

    final String status = response.getString(CACHE_STATUS);
    cache.setDisabled(status.equalsIgnoreCase(CACHE_STATUS_DISABLED));
    cache.setArchived(status.equalsIgnoreCase(CACHE_STATUS_ARCHIVED));

    cache.setSize(getCacheSize(response));
    cache.setDifficulty((float) response.getDouble(CACHE_DIFFICULTY));
    cache.setTerrain((float) response.getDouble(CACHE_TERRAIN));

    if (!response.isNull(CACHE_IS_FOUND)) {
        cache.setFound(response.getBoolean(CACHE_IS_FOUND));
    }//ww  w.  j  a  v a 2s  .  c  o m
    cache.setHidden(parseDate(response.getString(CACHE_HIDDEN)));
}

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

private static CacheSize getCacheSize(final JSONObject response) {
    if (response.isNull(CACHE_SIZE2)) {
        return getCacheSizeDeprecated(response);
    }/*from   ww w  .ja  v  a  2s .c  o m*/
    try {
        final String size = response.getString(CACHE_SIZE2);
        return CacheSize.getById(size);
    } catch (JSONException e) {
        Log.e("OkapiClient.getCacheSize", e);
        return getCacheSizeDeprecated(response);
    }
}

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

private static CacheSize getCacheSizeDeprecated(final JSONObject response) {
    if (response.isNull(CACHE_SIZE_DEPRECATED)) {
        return CacheSize.NOT_CHOSEN;
    }//from  w  ww  . jav a 2  s  .com
    double size = 0;
    try {
        size = response.getDouble(CACHE_SIZE_DEPRECATED);
    } catch (final JSONException e) {
        Log.e("OkapiClient.getCacheSize", e);
    }
    switch ((int) Math.round(size)) {
    case 1:
        return CacheSize.MICRO;
    case 2:
        return CacheSize.SMALL;
    case 3:
        return CacheSize.REGULAR;
    case 4:
        return CacheSize.LARGE;
    case 5:
        return CacheSize.VERY_LARGE;
    default:
        break;
    }
    return CacheSize.NOT_CHOSEN;
}

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

public static @Nullable String getUserUUID(final OCApiConnector connector, final String userName) {
    final Parameters params = new Parameters("fields", USER_UUID, USER_USERNAME, userName);

    final JSONResult result = request(connector, OkapiService.SERVICE_USER_BY_USERNAME, params);
    if (!result.isSuccess) {
        final OkapiError error = new OkapiError(result.data);
        Log.e("OkapiClient.getUserUUID: error getting user info: '" + error.getMessage() + "'");
        return null;
    }/*from   www. j  a  va2s  . c om*/

    JSONObject data = result.data;
    if (!data.isNull(USER_UUID)) {
        try {
            return data.getString(USER_UUID);
        } catch (final JSONException e) {
            Log.e("OkapiClient.getUserUUID - uuid", e);
        }
    }

    return null;
}

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

public static UserInfo getUserInfo(final OCApiLiveConnector connector) {
    final Parameters params = new Parameters("fields", USER_INFO_FIELDS);

    final JSONResult result = request(connector, OkapiService.SERVICE_USER, params);

    if (!result.isSuccess) {
        final OkapiError error = new OkapiError(result.data);
        Log.e("OkapiClient.getUserInfo: error getting user info: '" + error.getMessage() + "'");
        return new UserInfo(StringUtils.EMPTY, 0, UserInfoStatus.getFromOkapiError(error.getResult()));
    }//from w  w w . j a v a2 s .c  om

    JSONObject data = result.data;

    String name = StringUtils.EMPTY;
    boolean successUserName = false;

    if (!data.isNull(USER_USERNAME)) {
        try {
            name = data.getString(USER_USERNAME);
            successUserName = true;
        } catch (final JSONException e) {
            Log.e("OkapiClient.getUserInfo - name", e);
        }
    }

    int finds = 0;
    boolean successFinds = false;

    if (!data.isNull(USER_CACHES_FOUND)) {
        try {
            finds = data.getInt(USER_CACHES_FOUND);
            successFinds = true;
        } catch (final JSONException e) {
            Log.e("OkapiClient.getUserInfo - finds", e);
        }
    }

    return new UserInfo(name, finds,
            successUserName && successFinds ? UserInfoStatus.SUCCESSFUL : UserInfoStatus.FAILED);
}

From source file:com.balch.mocktrade.finance.QuoteGoogleFinance.java

public static QuoteGoogleFinance fromJSONObject(JSONObject jsonObject) throws Exception {
    QuoteGoogleFinance quote = new QuoteGoogleFinance();
    Iterator iter = jsonObject.keys();
    while (iter.hasNext()) {
        String key = (String) iter.next();
        if (!jsonObject.isNull(key)) {
            quote.data.put(key, jsonObject.getString(key));
        }//from  w  ww  .  j av  a 2  s.c om
    }

    return quote;

}

From source file:com.aokyu.dev.pocket.AccessToken.java

AccessToken(JSONObject jsonObj) throws PocketException {
    try {/*from  w w  w  . j a  v a2  s  .c o  m*/
        if (!jsonObj.isNull(KEY_TOKEN)) {
            mToken = jsonObj.getString(KEY_TOKEN);
        }

        if (!jsonObj.isNull(KEY_USERNAME)) {
            mUsername = jsonObj.getString(KEY_USERNAME);
        }
    } catch (JSONException e) {
        throw new PocketException();
    }

    if (mToken == null || mUsername == null) {
        throw new PocketException();
    }
}

From source file:edu.mbl.jif.imaging.mmtiff.OMEMetadata.java

private void startSeriesMetadata(JSONObject firstImageTags, int seriesIndex, String baseFileName)
        throws JSONException, MMScriptException {
    series_.put(seriesIndex, new Indices());
    //Last one is samples per pixel
    JSONObject summaryMD = mptStorage_.getSummaryMetadata();
    MetadataTools.populateMetadata(metadata_, seriesIndex, baseFileName,
            MultipageTiffWriter.BYTE_ORDER.equals(ByteOrder.LITTLE_ENDIAN),
            mptStorage_.slicesFirst() ? "XYZCT" : "XYCZT", "uint" + (MDUtils.isGRAY8(summaryMD) ? "8" : "16"),
            MDUtils.getWidth(summaryMD), MDUtils.getHeight(summaryMD), MDUtils.getNumSlices(summaryMD),
            MDUtils.getNumChannels(summaryMD), MDUtils.getNumFrames(summaryMD), 1);

    if (summaryMD.has("PixelSize_um") && !summaryMD.isNull("PixelSize_um")) {
        double pixelSize = summaryMD.getDouble("PixelSize_um");
        if (pixelSize > 0) {
            metadata_.setPixelsPhysicalSizeX(new PositiveFloat(pixelSize), seriesIndex);
            metadata_.setPixelsPhysicalSizeY(new PositiveFloat(pixelSize), seriesIndex);
        }//  www .ja  va2  s .c  om
    }
    if (summaryMD.has("z-step_um") && !summaryMD.isNull("z-step_um")) {
        double zStep = summaryMD.getDouble("z-step_um");
        if (zStep > 0) {
            metadata_.setPixelsPhysicalSizeZ(new PositiveFloat(zStep), seriesIndex);
        }
    }

    String positionName;
    try {
        positionName = MDUtils.getPositionName(firstImageTags);
    } catch (JSONException ex) {
        ReportingUtils.logError("Couldn't find position name in image metadata");
        positionName = "pos" + MDUtils.getPositionIndex(firstImageTags);
    }
    metadata_.setStageLabelName(positionName, seriesIndex);

    String instrumentID = MetadataTools.createLSID("Microscope");
    metadata_.setInstrumentID(instrumentID, 0);
    // link Instrument and Image
    metadata_.setImageInstrumentRef(instrumentID, seriesIndex);

    JSONObject comments = mptStorage_.getDisplayAndComments().getJSONObject("Comments");
    if (comments.has("Summary") && !comments.isNull("Summary")) {
        metadata_.setImageDescription(comments.getString("Summary"), seriesIndex);
    }

    JSONArray channels = mptStorage_.getDisplayAndComments().getJSONArray("Channels");
    for (int channelIndex = 0; channelIndex < channels.length(); channelIndex++) {
        JSONObject channel = channels.getJSONObject(channelIndex);
        metadata_.setChannelColor(new Color(channel.getInt("Color")), seriesIndex, channelIndex);
        metadata_.setChannelName(channel.getString("Name"), seriesIndex, channelIndex);
    }
    //used to estimate the final length of the OME xml string
    if (omeXMLBaseLength_ == -1) {
        try {
            OMEXMLService service = new ServiceFactory().getInstance(OMEXMLService.class);
            omeXMLBaseLength_ = service.getOMEXML(metadata_).length();
        } catch (Exception ex) {
            ReportingUtils.logError("Unable to calculate OME XML Base length");
        }
    }
}

From source file:edu.mbl.jif.imaging.mmtiff.OMEMetadata.java

public void addImageTagsToOME(JSONObject tags, int ifdCount, String baseFileName, String currentFileName)
        throws JSONException, MMScriptException {
    int seriesIndex;
    try {//  w  w  w  .j ava 2  s  . co m
        seriesIndex = MDUtils.getPositionIndex(tags);
    } catch (Exception e) {
        seriesIndex = 0;
    }
    if (!series_.containsKey(seriesIndex)) {
        startSeriesMetadata(tags, seriesIndex, baseFileName);
        try {
            //Add these tags in only once, but need to get them from image rather than summary metadata
            setOMEDetectorMetadata(tags);
            if (tags.has("Time") && !tags.isNull("Time")) {
                metadata_.setImageAcquisitionDate(
                        new Timestamp(DateTools.formatDate(tags.getString("Time"), "yyyy-MM-dd HH:mm:ss")),
                        seriesIndex);
            }
        } catch (Exception e) {
            ReportingUtils.logError("Problem adding System state cahce metadata to OME Metadata");
        }
    }

    Indices indices = series_.get(seriesIndex);

    //Required tags: Channel, slice, and frame index
    try {
        int slice = MDUtils.getSliceIndex(tags);
        int frame = MDUtils.getFrameIndex(tags);
        int channel = MDUtils.getChannelIndex(tags);

        //New tiff data if unexpected index, or new file
        boolean newTiffData = !mptStorage_.hasExpectedImageOrder() || ifdCount == 0
                || indices.tiffDataPlaneCount_ == 0;
        // ifdCount is 0 when a new file started, tiff data plane count is 0 at a new position
        if (newTiffData) { //create new tiff data element
            indices.tiffDataIndex_++;
            metadata_.setTiffDataFirstZ(new NonNegativeInteger(slice), seriesIndex, indices.tiffDataIndex_);
            metadata_.setTiffDataFirstC(new NonNegativeInteger(channel), seriesIndex, indices.tiffDataIndex_);
            metadata_.setTiffDataFirstT(new NonNegativeInteger(frame), seriesIndex, indices.tiffDataIndex_);
            metadata_.setTiffDataIFD(new NonNegativeInteger(ifdCount), seriesIndex, indices.tiffDataIndex_);
            metadata_.setUUIDFileName(currentFileName, seriesIndex, indices.tiffDataIndex_);
            indices.tiffDataPlaneCount_ = 1;
        } else { //continue adding to previous tiffdata element
            indices.tiffDataPlaneCount_++;
        }
        metadata_.setTiffDataPlaneCount(new NonNegativeInteger(indices.tiffDataPlaneCount_), seriesIndex,
                indices.tiffDataIndex_);

        metadata_.setPlaneTheZ(new NonNegativeInteger(slice), seriesIndex, indices.planeIndex_);
        metadata_.setPlaneTheC(new NonNegativeInteger(channel), seriesIndex, indices.planeIndex_);
        metadata_.setPlaneTheT(new NonNegativeInteger(frame), seriesIndex, indices.planeIndex_);
    } catch (JSONException ex) {
        ReportingUtils.showError("Image Metadata missing ChannelIndex, SliceIndex, or FrameIndex");
    } catch (Exception e) {
        ReportingUtils.logError("Couldn't add to OME metadata");
    }

    //Optional tags
    try {

        if (tags.has("Exposure-ms") && !tags.isNull("Exposure-ms")) {
            metadata_.setPlaneExposureTime(tags.getDouble("Exposure-ms") / 1000.0, seriesIndex,
                    indices.planeIndex_);
        }
        if (tags.has("XPositionUm") && !tags.isNull("XPositionUm")) {
            metadata_.setPlanePositionX(tags.getDouble("XPositionUm"), seriesIndex, indices.planeIndex_);
            if (indices.planeIndex_ == 0) { //should be set at start, but dont have position coordinates then
                metadata_.setStageLabelX(tags.getDouble("XPositionUm"), seriesIndex);
            }
        }
        if (tags.has("YPositionUm") && !tags.isNull("YPositionUm")) {
            metadata_.setPlanePositionY(tags.getDouble("YPositionUm"), seriesIndex, indices.planeIndex_);
            if (indices.planeIndex_ == 0) {
                metadata_.setStageLabelY(tags.getDouble("YPositionUm"), seriesIndex);
            }
        }
        if (tags.has("ZPositionUm") && !tags.isNull("ZPositionUm")) {
            metadata_.setPlanePositionZ(tags.getDouble("ZPositionUm"), seriesIndex, indices.planeIndex_);
        }
        if (tags.has("ElapsedTime-ms") && !tags.isNull("ElapsedTime-ms")) {
            metadata_.setPlaneDeltaT(tags.getDouble("ElapsedTime-ms") / 1000.0, seriesIndex,
                    indices.planeIndex_);
        }

    } catch (JSONException e) {
        ReportingUtils.logError("Problem adding tags to OME Metadata");
    }

    indices.planeIndex_++;

    //This code is used is estimating the length of OME XML to be added in, so
    //images arent written into file space reserved for it
    if (omeXMLImageLength_ == -1) {
        //This is the first image plane to be written, so calculate the change in length from the base OME
        //XML length to estimate the approximate memory needed per an image plane
        try {
            OMEXMLService service = new ServiceFactory().getInstance(OMEXMLService.class);
            omeXMLImageLength_ = (int) (1.1 * (service.getOMEXML(metadata_).length() - omeXMLBaseLength_));
        } catch (Exception ex) {
            ReportingUtils.logError("Unable to calculate OME XML Image length");
        }
    }
}