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.nextgis.maplib.map.VectorLayer.java

public String createFromGeoJSON(JSONObject geoJSONObject) {
    try {//from w  w w.j a  v a  2  s . c  o  m
        //check crs
        boolean isWGS84 = true; //if no crs tag - WGS84 CRS
        if (geoJSONObject.has(GEOJSON_CRS)) {
            JSONObject crsJSONObject = geoJSONObject.getJSONObject(GEOJSON_CRS);
            //the link is unsupported yet.
            if (!crsJSONObject.getString(GEOJSON_TYPE).equals(GEOJSON_NAME)) {
                return mContext.getString(R.string.error_crs_unsuported);
            }
            JSONObject crsPropertiesJSONObject = crsJSONObject.getJSONObject(GEOJSON_PROPERTIES);
            String crsName = crsPropertiesJSONObject.getString(GEOJSON_NAME);
            if (crsName.equals("urn:ogc:def:crs:OGC:1.3:CRS84")) { // WGS84
                isWGS84 = true;
            } else if (crsName.equals("urn:ogc:def:crs:EPSG::3857") || crsName.equals("EPSG:3857")) { //Web Mercator
                isWGS84 = false;
            } else {
                return mContext.getString(R.string.error_crs_unsuported);
            }
        }

        //load contents to memory and reproject if needed
        JSONArray geoJSONFeatures = geoJSONObject.getJSONArray(GEOJSON_TYPE_FEATURES);
        if (0 == geoJSONFeatures.length()) {
            return mContext.getString(R.string.error_empty_dataset);
        }

        List<Feature> features = new ArrayList<>();
        List<Pair<String, Integer>> fields = new ArrayList<>();

        int geometryType = GTNone;
        for (int i = 0; i < geoJSONFeatures.length(); i++) {
            JSONObject jsonFeature = geoJSONFeatures.getJSONObject(i);
            //get geometry
            JSONObject jsonGeometry = jsonFeature.getJSONObject(GEOJSON_GEOMETRY);
            GeoGeometry geometry = GeoGeometry.fromJson(jsonGeometry);
            if (geometryType == GTNone) {
                geometryType = geometry.getType();
            } else if (!Geo.isGeometryTypeSame(geometryType, geometry.getType())) {
                //skip different geometry type
                continue;
            }

            //reproject if needed
            if (isWGS84) {
                geometry.setCRS(CRS_WGS84);
                geometry.project(CRS_WEB_MERCATOR);
            } else {
                geometry.setCRS(CRS_WEB_MERCATOR);
            }

            int nId = i;
            if (jsonFeature.has(GEOJSON_ID))
                nId = jsonFeature.getInt(GEOJSON_ID);
            Feature feature = new Feature(nId, fields); // ID == i
            feature.setGeometry(geometry);

            //normalize attributes
            JSONObject jsonAttributes = jsonFeature.getJSONObject(GEOJSON_PROPERTIES);
            Iterator<String> iter = jsonAttributes.keys();
            while (iter.hasNext()) {
                String key = iter.next();
                Object value = jsonAttributes.get(key);
                int nType = NOT_FOUND;
                //check type
                if (value instanceof Integer || value instanceof Long) {
                    nType = FTInteger;
                } else if (value instanceof Double || value instanceof Float) {
                    nType = FTReal;
                } else if (value instanceof Date) {
                    nType = FTDateTime;
                } else if (value instanceof String) {
                    nType = FTString;
                } else if (value instanceof JSONObject) {
                    nType = NOT_FOUND;
                    //the some list - need to check it type FTIntegerList, FTRealList, FTStringList
                }

                if (nType != NOT_FOUND) {
                    int fieldIndex = NOT_FOUND;
                    for (int j = 0; j < fields.size(); j++) {
                        if (fields.get(j).first.equals(key)) {
                            fieldIndex = j;
                        }
                    }
                    if (fieldIndex == NOT_FOUND) { //add new field
                        Pair<String, Integer> fieldKey = Pair.create(key, nType);
                        fieldIndex = fields.size();
                        fields.add(fieldKey);
                    }
                    feature.setFieldValue(fieldIndex, value);
                }
            }
            features.add(feature);
        }

        String tableCreate = "CREATE TABLE IF NOT EXISTS " + mPath.getName() + " ( " + //table name is the same as the folder of the layer
                "_ID INTEGER PRIMARY KEY, " + "GEOM BLOB";
        for (int i = 0; i < fields.size(); ++i) {
            Pair<String, Integer> field = fields.get(i);

            tableCreate += ", " + field.first + " ";
            switch (field.second) {
            case FTString:
                tableCreate += "TEXT";
                break;
            case FTInteger:
                tableCreate += "INTEGER";
                break;
            case FTReal:
                tableCreate += "REAL";
                break;
            case FTDateTime:
                tableCreate += "TIMESTAMP";
                break;
            }
        }
        tableCreate += " );";

        GeoEnvelope extents = new GeoEnvelope();
        for (Feature feature : features) {
            //update bbox
            extents.merge(feature.getGeometry().getEnvelope());
        }

        //1. create table and populate with values
        MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
        SQLiteDatabase db = map.getDatabase(true);
        db.execSQL(tableCreate);
        for (Feature feature : features) {
            ContentValues values = new ContentValues();
            values.put("_ID", feature.getId());
            try {
                values.put("GEOM", feature.getGeometry().toBlob());
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < fields.size(); ++i) {
                if (!feature.isValuePresent(i))
                    continue;
                switch (fields.get(i).second) {
                case FTString:
                    values.put(fields.get(i).first, feature.getFieldValueAsString(i));
                    break;
                case FTInteger:
                    values.put(fields.get(i).first, (int) feature.getFieldValue(i));
                    break;
                case FTReal:
                    values.put(fields.get(i).first, (double) feature.getFieldValue(i));
                    break;
                case FTDateTime:
                    values.put(fields.get(i).first, feature.getFieldValueAsString(i));
                    break;
                }
            }
            db.insert(mPath.getName(), "", values);
        }

        //2. save the layer properties to config.json
        mGeometryType = geometryType;
        mExtents = extents;
        mIsInitialized = true;
        setDefaultRenderer();

        save();

        //3. fill the geometry and labels array
        mVectorCacheItems = new ArrayList<>();
        for (Feature feature : features) {
            mVectorCacheItems.add(new VectorCacheItem(feature.getGeometry(), feature.getId()));
        }

        if (null != mParent) { //notify the load is over
            LayerGroup layerGroup = (LayerGroup) mParent;
            layerGroup.onLayerChanged(this);
        }

        return "";
    } catch (JSONException e) {
        e.printStackTrace();
        return e.getLocalizedMessage();
    }
}

From source file:com.nextgis.maplib.map.VectorLayer.java

@Override
public void fromJSON(JSONObject jsonObject) throws JSONException {
    super.fromJSON(jsonObject);
    mGeometryType = jsonObject.getInt(JSON_GEOMETRY_TYPE_KEY);
    mIsInitialized = jsonObject.getBoolean(JSON_IS_INITIALIZED_KEY);
    if (jsonObject.has(JSON_RENDERERPROPS_KEY)) {
        setDefaultRenderer();/*from  w  w  w . jav  a  2  s .co  m*/

        if (null != mRenderer && mRenderer instanceof IJSONStore) {
            IJSONStore jsonStore = (IJSONStore) mRenderer;
            jsonStore.fromJSON(jsonObject.getJSONObject(JSON_RENDERERPROPS_KEY));
        }
    }

    if (mIsInitialized) {
        mExtents = new GeoEnvelope();

        //load vector cache
        MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
        SQLiteDatabase db = map.getDatabase(false);
        String[] columns = new String[] { "_ID", "GEOM" };
        Cursor cursor = db.query(mPath.getName(), columns, null, null, null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            mVectorCacheItems = new ArrayList<>();
            do {
                try {
                    GeoGeometry geoGeometry = GeoGeometry.fromBlob(cursor.getBlob(1));
                    int nId = cursor.getInt(0);
                    mExtents.merge(geoGeometry.getEnvelope());
                    mVectorCacheItems.add(new VectorCacheItem(geoGeometry, nId));
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } while (cursor.moveToNext());
        }
    }
}

From source file:org.brickred.socialauth.provider.MendeleyImpl.java

private Profile getProfile() throws Exception {
    Profile profile = new Profile();
    String url = PROFILE_URL;
    LOG.debug("Obtaining user profile. Profile URL : " + url);
    Response serviceResponse = null;
    try {//from  w w w . j  av a 2s .  co m
        serviceResponse = authenticationStrategy.executeFeed(url);
    } catch (Exception e) {
        throw new SocialAuthException("Failed to retrieve the user profile from  " + url, e);
    }
    if (serviceResponse.getStatus() != 200) {
        throw new SocialAuthException(
                "Failed to retrieve the user profile from  " + url + ". Staus :" + serviceResponse.getStatus());
    }
    String result;
    try {
        result = serviceResponse.getResponseBodyAsString(Constants.ENCODING);
        LOG.debug("User Profile :" + result);
    } catch (Exception exc) {
        throw new SocialAuthException("Failed to read response from  " + url, exc);
    }
    try {
        JSONObject pRes = new JSONObject(result);
        JSONObject pObj = pRes.getJSONObject("main");
        if (pObj.has("profile_id")) {
            profile.setValidatedId(pObj.getString("profile_id"));
        }
        if (pObj.has("name")) {
            String name = pObj.getString("name");
            if (name != null && name.trim().length() > 0) {
                profile.setFirstName(pObj.getString("name"));
            }
        }
        if (pObj.has("photo")) {
            String photo = pObj.getString("photo");
            if (photo != null && photo.trim().length() > 0) {
                profile.setProfileImageURL(pObj.getString("photo"));
            }
        }
        profile.setProviderId(getProviderId());
        userProfile = profile;
        return profile;
    } catch (Exception e) {
        throw new ServerDataException("Failed to parse the user profile json : " + result, e);

    }
}

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

@Override
protected Long handleInternally(JSONObject content) {
    final long id = content.getLong("guild_id");
    if (api.getGuildLock().isLocked(id))
        return id;

    JSONObject userJson = content.getJSONObject("user");
    final long userId = userJson.getLong("id");
    GuildImpl guild = (GuildImpl) api.getGuildMap().get(id);
    if (guild == null) {
        api.getEventCache().cache(EventCache.Type.GUILD, userId, () -> {
            handle(responseNumber, allContent);
        });/*from  w  w  w  .  j  a  va2s.  c o  m*/
        EventCache.LOG.debug("Got GuildMember update but JDA currently does not have the Guild cached. "
                + content.toString());
        return null;
    }

    MemberImpl member = (MemberImpl) guild.getMembersMap().get(userId);
    if (member == null) {
        api.getEventCache().cache(EventCache.Type.USER, userId, () -> {
            handle(responseNumber, allContent);
        });
        EventCache.LOG.debug(
                "Got GuildMember update but Member is not currently present in Guild. " + content.toString());
        return null;
    }

    Set<Role> currentRoles = member.getRoleSet();
    List<Role> newRoles = toRolesList(guild, content.getJSONArray("roles"));

    //If newRoles is null that means that we didn't find a role that was in the array and was cached this event
    if (newRoles == null)
        return null;

    //Find the roles removed.
    List<Role> removedRoles = new LinkedList<>();
    each: for (Role role : currentRoles) {
        for (Iterator<Role> it = newRoles.iterator(); it.hasNext();) {
            Role r = it.next();
            if (role.equals(r)) {
                it.remove();
                continue each;
            }
        }
        removedRoles.add(role);
    }

    if (removedRoles.size() > 0)
        currentRoles.removeAll(removedRoles);
    if (newRoles.size() > 0)
        currentRoles.addAll(newRoles);

    if (removedRoles.size() > 0) {
        api.getEventManager()
                .handle(new GuildMemberRoleRemoveEvent(api, responseNumber, guild, member, removedRoles));
    }
    if (newRoles.size() > 0) {
        api.getEventManager().handle(new GuildMemberRoleAddEvent(api, responseNumber, guild, member, newRoles));
    }
    if (content.has("nick")) {
        String prevNick = member.getNickname();
        String newNick = content.isNull("nick") ? null : content.getString("nick");
        if (!Objects.equals(prevNick, newNick)) {
            member.setNickname(newNick);
            api.getEventManager().handle(
                    new GuildMemberNickChangeEvent(api, responseNumber, guild, member, prevNick, newNick));
        }
    }
    return null;
}

From source file:org.eclipse.orion.internal.server.servlets.file.FileHandlerV1.java

private void handlePatchContents(HttpServletRequest request, BufferedReader requestReader,
        HttpServletResponse response, IFileStore file)
        throws IOException, CoreException, NoSuchAlgorithmException, JSONException, ServletException {
    JSONObject changes = OrionServlet.readJSONRequest(request);
    //read file to memory
    Reader fileReader = new InputStreamReader(file.openInputStream(EFS.NONE, null));
    StringWriter oldFile = new StringWriter();
    IOUtilities.pipe(fileReader, oldFile, true, false);
    StringBuffer oldContents = oldFile.getBuffer();

    JSONArray changeList = changes.getJSONArray("diff");
    for (int i = 0; i < changeList.length(); i++) {
        JSONObject change = changeList.getJSONObject(i);
        long start = change.getLong("start");
        long end = change.getLong("end");
        String text = change.getString("text");
        oldContents.replace((int) start, (int) end, text);
    }//from w w w  . j  a va 2  s .  com

    String newContents = oldContents.toString();
    boolean failed = false;
    if (changes.has("contents")) {
        String contents = changes.getString("contents");
        if (!newContents.equals(contents)) {
            failed = true;
            newContents = contents;
        }
    }
    Writer fileWriter = new OutputStreamWriter(file.openOutputStream(EFS.NONE, null), "UTF-8");
    IOUtilities.pipe(new StringReader(newContents), fileWriter, false, true);
    if (failed) {
        statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_ACCEPTABLE,
                        "Bad File Diffs. Please paste this content in a bug report: \u00A0\u00A0    "
                                + changes.toString(),
                        null));
        return;
    }

    // return metadata with the new Etag
    handleGetMetadata(request, response, response.getWriter(), file);
}

From source file:edu.stanford.mobisocial.dungbeetle.DungBeetleContentProvider.java

/**
 * Inserts a message locally that has been received from some agent,
 * typically from a remote device./*ww  w .  ja v  a 2 s  . co  m*/
 */
@Override
public Uri insert(Uri uri, ContentValues values) {
    ContentResolver resolver = getContext().getContentResolver();
    if (DBG)
        Log.i(TAG, "Inserting at uri: " + uri + ", " + values);

    final String appId = getCallingActivityId();
    if (appId == null) {
        Log.d(TAG, "No AppId for calling activity. Ignoring query.");
        return null;
    }

    List<String> segs = uri.getPathSegments();
    if (match(uri, "feeds", "me")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }

        long objId = mHelper.addToFeed(appId, "friend", values);
        Uri objUri = DbObject.uriForObj(objId);
        resolver.notifyChange(Feed.uriForName("me"), null);
        resolver.notifyChange(Feed.uriForName("friend"), null);
        resolver.notifyChange(objUri, null);
        return objUri;
    } else if (match(uri, "feeds", ".+")) {
        String feedName = segs.get(1);
        String type = values.getAsString(DbObject.TYPE);
        try {
            JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
            String objHash = null;
            if (feedName.contains(":")) {
                String[] parts = feedName.split(":");
                feedName = parts[0];
                objHash = parts[1];
            }
            if (objHash != null) {
                json.put(DbObjects.TARGET_HASH, Long.parseLong(objHash));
                json.put(DbObjects.TARGET_RELATION, DbRelation.RELATION_PARENT);
                values.put(DbObject.JSON, json.toString());
            }

            String appAuthority = appId;
            if (SUPER_APP_ID.equals(appId)) {
                if (AppObj.TYPE.equals(type)) {
                    if (json.has(AppObj.ANDROID_PACKAGE_NAME)) {
                        appAuthority = json.getString(AppObj.ANDROID_PACKAGE_NAME);
                    }
                }
            }

            long objId = mHelper.addToFeed(appAuthority, feedName, values);
            Uri objUri = DbObject.uriForObj(objId);
            resolver.notifyChange(objUri, null);
            notifyDependencies(mHelper, resolver, segs.get(1));
            if (DBG)
                Log.d(TAG, "just inserted " + values.getAsString(DbObject.JSON));
            return objUri;
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "out")) {
        try {
            JSONObject obj = new JSONObject(values.getAsString("json"));
            long objId = mHelper.addToOutgoing(appId, values.getAsString(DbObject.DESTINATION),
                    values.getAsString(DbObject.TYPE), obj);
            resolver.notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
            return DbObject.uriForObj(objId);
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "contacts")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertContact(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "subscribers")) {
        // Question: Should this be restricted?
        // if(!appId.equals(SUPER_APP_ID)) return null;
        long id = mHelper.insertSubscriber(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/subscribers"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "groups")) {
        if (!appId.equals(SUPER_APP_ID))
            return null;
        long id = mHelper.insertGroup(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "group_members")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertGroupMember(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"), null);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"), null);
        return uriWithId(uri, id);
    }

    else if (match(uri, "group_invitations")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        String groupName = values.getAsString(InviteToGroupObj.GROUP_NAME);
        Uri dynUpdateUri = Uri.parse(values.getAsString(InviteToGroupObj.DYN_UPDATE_URI));
        long gid = values.getAsLong("groupId");
        SQLiteDatabase db = mHelper.getWritableDatabase();
        mHelper.addToOutgoing(db, appId, values.getAsString(InviteToGroupObj.PARTICIPANTS),
                InviteToGroupObj.TYPE, InviteToGroupObj.json(groupName, dynUpdateUri));
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
        return uriWithId(uri, gid);
    }

    else if (match(uri, "dynamic_groups")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        Uri gUri = Uri.parse(values.getAsString("uri"));
        GroupProviders.GroupProvider gp = GroupProviders.forUri(gUri);
        String feedName = gp.feedName(gUri);
        Maybe<Group> mg = mHelper.groupByFeedName(feedName);
        long id = -1;
        try {
            Group g = mg.get();
            id = g.id;
        } catch (Maybe.NoValError e) {
            ContentValues cv = new ContentValues();
            cv.put(Group.NAME, gp.groupName(gUri));
            cv.put(Group.FEED_NAME, feedName);
            cv.put(Group.DYN_UPDATE_URI, gUri.toString());

            String table = DbObject.TABLE;
            String[] columns = new String[] { DbObject.FEED_NAME };
            String selection = DbObject.CHILD_FEED_NAME + " = ?";
            String[] selectionArgs = new String[] { feedName };
            Cursor parent = mHelper.getReadableDatabase().query(table, columns, selection, selectionArgs, null,
                    null, null);
            try {
                if (parent.moveToFirst()) {
                    String parentName = parent.getString(0);
                    table = Group.TABLE;
                    columns = new String[] { Group._ID };
                    selection = Group.FEED_NAME + " = ?";
                    selectionArgs = new String[] { parentName };

                    Cursor parent2 = mHelper.getReadableDatabase().query(table, columns, selection,
                            selectionArgs, null, null, null);
                    try {
                        if (parent2.moveToFirst()) {
                            cv.put(Group.PARENT_FEED_ID, parent2.getLong(0));
                        } else {
                            Log.e(TAG, "Parent feed found but no id for " + parentName);
                        }
                    } finally {
                        parent2.close();
                    }
                } else {
                    Log.w(TAG, "No parent feed for " + feedName);
                }
            } finally {
                parent.close();
            }
            id = mHelper.insertGroup(cv);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/dynamic_groups"), null);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        }
        return uriWithId(uri, id);
    }

    else if (match(uri, "dynamic_group_member")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        SQLiteDatabase db = mHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            String pubKeyStr = values.getAsString(Contact.PUBLIC_KEY);
            RSAPublicKey k = RSACrypto.publicKeyFromString(pubKeyStr);
            String personId = mIdent.personIdForPublicKey(k);
            if (!personId.equals(mIdent.userPersonId())) {
                cv.put(Contact.PUBLIC_KEY, values.getAsString(Contact.PUBLIC_KEY));
                cv.put(Contact.NAME, values.getAsString(Contact.NAME));
                cv.put(Contact.EMAIL, values.getAsString(Contact.EMAIL));
                if (values.getAsString(Contact.PICTURE) != null) {
                    cv.put(Contact.PICTURE, values.getAsByteArray(Contact.PICTURE));
                }

                long cid = -1;
                Contact contact = mHelper.contactForPersonId(personId).otherwise(Contact.NA());
                if (contact.id > -1) {
                    cid = contact.id;
                } else {
                    cid = mHelper.insertContact(db, cv);
                }

                if (cid > -1) {

                    ContentValues gv = new ContentValues();
                    gv.put(GroupMember.GLOBAL_CONTACT_ID, values.getAsString(GroupMember.GLOBAL_CONTACT_ID));
                    gv.put(GroupMember.GROUP_ID, values.getAsLong(GroupMember.GROUP_ID));
                    gv.put(GroupMember.CONTACT_ID, cid);
                    mHelper.insertGroupMember(db, gv);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"),
                            null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"),
                            null);

                    // Add subscription to this private group feed
                    ContentValues sv = new ContentValues();
                    sv = new ContentValues();
                    sv.put(Subscriber.CONTACT_ID, cid);
                    sv.put(Subscriber.FEED_NAME, values.getAsString(Group.FEED_NAME));
                    mHelper.insertSubscriber(db, sv);

                    ContentValues xv = new ContentValues();
                    xv.put(Subscriber.CONTACT_ID, cid);
                    xv.put(Subscriber.FEED_NAME, "friend");
                    mHelper.insertSubscriber(db, xv);

                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/subscribers"),
                            null);

                    db.setTransactionSuccessful();
                }
                return uriWithId(uri, cid);
            } else {
                Log.i(TAG, "Omitting self.");
                return uriWithId(uri, Contact.MY_ID);
            }
        } finally {
            db.endTransaction();
        }
    } else {
        Log.e(TAG, "Failed to insert into " + uri);
        return null;
    }
}

From source file:fr.liglab.adele.cilia.workbench.restmonitoring.parser.platform.PlatformChain.java

public PlatformChain(JSONObject json, PlatformModel platform) throws CiliaException {
    super(getJSONname(json));

    this.platform = platform;
    this.refArchitectureID = null;

    PlatformID platformId = platform.getPlatformID();
    String chainId = getName();//w ww  .  j  a  v  a2  s. c om

    try {
        JSONArray mediatorsList = json.getJSONArray("Mediators");
        for (int i = 0; i < mediatorsList.length(); i++) {
            String mediatorName = (String) mediatorsList.get(i);

            JSONObject jsonNode = CiliaRestHelper.getMediatorContent(platform.getPlatformID(), getName(),
                    mediatorName);
            String state = jsonNode.getString("State");
            String type = jsonNode.getString("Type");
            String namespace = jsonNode.getString("Namespace");
            NameNamespaceID mediatorTypeID = new NameNamespaceID(type, namespace);

            mediators.add(new MediatorInstanceRef(mediatorName, mediatorTypeID, state, platformId, chainId));
        }
    } catch (JSONException e) {
        throw new CiliaException("error while parsing mediators list", e);
    }

    try {
        JSONObject adaptersRoot = json.getJSONObject("Adapters");

        if (adaptersRoot.has("in-only")) {
            JSONArray inAdaptersList = adaptersRoot.getJSONArray("in-only");
            for (int i = 0; i < inAdaptersList.length(); i++) {
                String adapterName = (String) inAdaptersList.get(i);
                NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName);

                JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(),
                        adapterName);
                String state = jsonNode.getString("State");
                adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId));
            }
        }

        if (adaptersRoot.has("out-only")) {
            JSONArray outAdaptersList = adaptersRoot.getJSONArray("out-only");
            for (int i = 0; i < outAdaptersList.length(); i++) {
                String adapterName = (String) outAdaptersList.get(i);
                NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName);

                JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(),
                        adapterName);
                String state = jsonNode.getString("State");
                adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId));
            }
        }

        if (adaptersRoot.has("in-out")) {
            JSONArray inOutAdaptersList = adaptersRoot.getJSONArray("in-out");
            for (int i = 0; i < inOutAdaptersList.length(); i++) {
                String adapterName = (String) inOutAdaptersList.get(i);
                NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName);

                JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(),
                        adapterName);
                String state = jsonNode.getString("State");
                adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId));
            }
        }

        if (adaptersRoot.has("unknown")) {
            JSONArray unknownAdaptersList = adaptersRoot.getJSONArray("unknown");
            for (int i = 0; i < unknownAdaptersList.length(); i++) {
                String adapterName = (String) unknownAdaptersList.get(i);
                NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName);

                JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(),
                        adapterName);
                String state = jsonNode.getString("State");
                adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId));
            }
        }

    } catch (JSONException e) {
        throw new CiliaException("error while parsing adapters list", e);
    }

    try {
        JSONArray bindingsList = json.getJSONArray("Bindings");
        for (int i = 0; i < bindingsList.length(); i++) {
            JSONObject binding = (JSONObject) bindingsList.get(i);
            bindings.add(new BindingInstance(binding, platformId, chainId));
        }
    } catch (JSONException e) {
        throw new CiliaException("error while parsing adapters list", e);
    }
}

From source file:de.damdi.fitness.db.parser.MuscleJSONParser.java

/**
 * Parses the JSON-String to a list of {@link Muscle}s.
 * //from   w  w w.j  a  v a  2s .co m
 * Example for such a .json File:
 * 
 *  [{
  *     "de": { "name" : "Bizeps" },
  *     "en": { "name" : "Biceps", "alternative_names":["Biceps muscle"] }
  *   }, ...]
  *   
  * @param jsonString The String to parse.
  * 
  * @return A list of {@link Muscle}s, null if an Error occurs..
  * 
 */
@Override
public List<Muscle> parse(String jsonString) {
    List<Muscle> muscleList = new ArrayList<Muscle>();

    JSONArray jsonArray;
    try {
        jsonArray = new JSONArray(jsonString);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject muscleObject = jsonArray.getJSONObject(i);

            Muscle m = null;

            for (String locale : TAG_LOCALES) {
                if (muscleObject.has(locale)) {
                    JSONObject languageObject = muscleObject.getJSONObject(locale);

                    // name
                    String name = languageObject.getString(TAG_NAME);

                    // first name is primary name, all other names are alternative names
                    List<String> nameList = new ArrayList<String>();
                    nameList.add(name);

                    // alternative names   
                    if (languageObject.has(TAG_ALTERNATIVE_NAMES)) {
                        JSONArray alternativeNameJSONArray = languageObject.getJSONArray(TAG_ALTERNATIVE_NAMES);
                        String[] alternativeNameArray = this.jsonArrayToStringArray(alternativeNameJSONArray);

                        for (int t = 0; t < alternativeNameArray.length; t++) {
                            String altName = alternativeNameArray[t];
                            nameList.add(altName);
                        }
                    }

                    if (m == null) {
                        m = new Muscle(new Locale(locale), nameList);
                    } else {
                        m.addNames(new Locale(locale), nameList);
                    }
                }
            }

            // Log.d(TAG, "Finished parsing Muscle: \n" + m.toDebugString());
            muscleList.add(m);

        }

    } catch (JSONException e) {
        Log.e(TAG, "Error during parsing JSON File.", e);
        return null;
    }

    if (muscleList.isEmpty())
        throw new AssertionError("JSON parsing failed: no muscles parsed.");
    return muscleList;
}

From source file:com.trellmor.berrytube.ChatUser.java

/**
 * Constructs a <code>ChatUser</code> from a <code>JSONObject</code>
 * //from w ww .  j  av a2s  .c  om
 * @param user
 *            <code>JSONObject<code> containing user data
 * @throws JSONException
 */
public ChatUser(JSONObject user) throws JSONException {
    this(user.getString("nick"));

    if (user.has("type"))
        this.type = user.getInt("type");
}

From source file:com.voidsearch.data.provider.facebook.SimpleGraphAPIClient.java

/**
 * check whether return object has pagination
 *
 * @param object//from   ww  w.j  a  v  a2  s.  co  m
 * @return
 */
private boolean hasMore(JSONObject object) throws Exception {
    return object.has("paging");
}