Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

From source file:org.eclipse.orion.server.tests.servlets.git.GitCherryPickTest.java

@Test
public void testCherryPick() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
        String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);

        // get project/folder metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject folder = new JSONObject(response.getText());

        String folderLocation = folder.getString(ProtocolConstants.KEY_LOCATION);
        JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        JSONObject testTxt = getChild(folder, "test.txt");
        modifyFile(testTxt, "first line\nsec. line\nthird line\n");

        addFile(testTxt);/* www  .  j av  a2 s  . c  o m*/

        commitFile(testTxt, "lines in test.txt", false);

        // create new file
        String fileName = "new.txt";
        request = getPostFilesRequest(folderLocation + "/", getNewFileJSON(fileName).toString(), fileName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        // add all
        request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "added new.txt", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // modify
        modifyFile(testTxt, "first line\nsec. line\nthird line\nfourth line\n");

        // add
        addFile(testTxt);

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "enlarged test.txt", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // modify
        modifyFile(testTxt, "first line\nsecond line\nthird line\nfourth line\n");

        // add
        addFile(testTxt);

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "fixed test.txt", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // remember starting point and commit to cherry-pick
        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(5, commitsArray.length());
        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("fixed test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        String toCherryPick = commit.getString(ProtocolConstants.KEY_NAME);
        commit = commitsArray.getJSONObject(3);
        assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        String startingPoint = commit.getString(ProtocolConstants.KEY_NAME);

        // branch
        response = branch(branchesLocation, "side", startingPoint);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
        response = checkoutBranch(cloneLocation, "side");
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // modify
        modifyFile(testTxt, "first line\nsec. line\nthird line\nfeature++\n");

        // add
        addFile(testTxt);

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "enhanced test.txt", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // CHERRY-PICK
        JSONObject cherryPick = cherryPick(gitHeadUri, toCherryPick);
        CherryPickStatus mergeResult = CherryPickStatus.valueOf(cherryPick.getString(GitConstants.KEY_RESULT));
        assertEquals(CherryPickStatus.OK, mergeResult);
        assertTrue(cherryPick.getBoolean(GitConstants.KEY_HEAD_UPDATED));

        // try again, should be OK, but nothing changed
        cherryPick = cherryPick(gitHeadUri, toCherryPick);
        mergeResult = CherryPickStatus.valueOf(cherryPick.getString(GitConstants.KEY_RESULT));
        assertEquals(CherryPickStatus.OK, mergeResult);
        assertFalse(cherryPick.getBoolean(GitConstants.KEY_HEAD_UPDATED));

        // 'new.txt' should be not there
        JSONObject newTxt = getChild(folder, "new.txt");
        assertNull(newTxt);

        // check cherry-pick result in the file
        request = getGetRequest(testTxt.getString(ProtocolConstants.KEY_LOCATION));
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        assertEquals("first line\nsecond line\nthird line\nfeature++\n", response.getText());

        // check log
        commitsArray = log(gitHeadUri);
        assertEquals(4, commitsArray.length());
        commit = commitsArray.getJSONObject(0);
        assertEquals("fixed test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        commit = commitsArray.getJSONObject(1);
        assertEquals("enhanced test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        commit = commitsArray.getJSONObject(2);
        assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        commit = commitsArray.getJSONObject(3);
        assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
    }
}

From source file:com.ecml.MidiOptions.java

/** Initialize the options from a json string
 * // www.ja va2 s.c  o  m
 * @param jsonString
 */
public static MidiOptions fromJson(String jsonString) {
    if (jsonString == null) {
        return null;
    }
    MidiOptions options = new MidiOptions();
    try {
        JSONObject json = new JSONObject(jsonString);
        JSONArray jsonTracks = json.getJSONArray("tracks");
        options.tracks = new boolean[jsonTracks.length()];
        for (int i = 0; i < options.tracks.length; i++) {
            options.tracks[i] = jsonTracks.getBoolean(i);
        }

        JSONArray jsonMute = json.getJSONArray("mute");
        options.mute = new boolean[jsonMute.length()];
        for (int i = 0; i < options.mute.length; i++) {
            options.mute[i] = jsonMute.getBoolean(i);
        }

        JSONArray jsonInstruments = json.getJSONArray("instruments");
        options.instruments = new int[jsonInstruments.length()];
        for (int i = 0; i < options.instruments.length; i++) {
            options.instruments[i] = jsonInstruments.getInt(i);
        }

        if (json.has("time")) {
            JSONObject jsonTime = json.getJSONObject("time");
            int numer = jsonTime.getInt("numerator");
            int denom = jsonTime.getInt("denominator");
            int quarter = jsonTime.getInt("quarter");
            int tempo = jsonTime.getInt("tempo");
            options.time = new TimeSignature(numer, denom, quarter, tempo);
        }

        options.useDefaultInstruments = json.getBoolean("useDefaultInstruments");
        options.scrollVert = json.getBoolean("scrollVert");
        options.showPiano = json.getBoolean("showPiano");
        options.showNoteColors = json.getBoolean("showNoteColors");
        options.showLyrics = json.getBoolean("showLyrics");
        options.delay = json.getInt("delay");
        options.twoStaffs = json.getBoolean("twoStaffs");
        options.showNoteLetters = json.getInt("showNoteLetters");
        options.transpose = json.getInt("transpose");
        options.key = json.getInt("key");
        options.combineInterval = json.getInt("combineInterval");
        options.shade1Color = json.getInt("shade1Color");
        options.shade2Color = json.getInt("shade2Color");
        options.showMeasures = json.getBoolean("showMeasures");
        options.playMeasuresInLoop = json.getBoolean("playMeasuresInLoop");
        options.playMeasuresInLoopStart = json.getInt("playMeasuresInLoopStart");
        options.playMeasuresInLoopEnd = json.getInt("playMeasuresInLoopEnd");
    } catch (Exception e) {
        return null;
    }
    return options;
}

From source file:com.joyfulmongo.db.ContainerObjectDate.java

@Override
public void onQuery(String collectionName, JSONObject theChild) {
    JSONObject childJson = theChild.getJSONObject(key);

    String iso = childJson.getString("iso");

    try {//from ww  w.ja  v  a2 s.  co m
        Date date = Utils.getParseDateFormat().parse(iso);
        theChild.put(key, date);
    } catch (ParseException e) {
        // do nothing
        LOGGER.log(Level.WARNING, "Wrong format of date string, skip convert.");
    }

}

From source file:org.wso2.emm.agent.services.ProcessMessage.java

private void messageExecute(String msg) {
    stillProcessing = true;/*from  www. j ava 2s.  c  o  m*/
    JSONArray repArray = new JSONArray();
    JSONObject jsReply = null;
    String msgId = "";

    JSONArray dataReply = null;
    try {
        JSONArray jArr = new JSONArray(msg.trim());
        for (int i = 0; i < jArr.length(); i++) {
            JSONArray innerArr = new JSONArray(jArr.getJSONObject(i).getString("data"));
            String featureCode = jArr.getJSONObject(i).getString("code");
            dataReply = new JSONArray();
            jsReply = new JSONObject();
            jsReply.put("code", featureCode);

            for (int x = 0; x < innerArr.length(); x++) {
                msgId = innerArr.getJSONObject(x).getString("messageId");
                jsReply.put("messageId", msgId);

                if (featureCode.equals(CommonUtilities.OPERATION_POLICY_BUNDLE)) {
                    SharedPreferences mainPrefp = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);

                    Editor editorp = mainPrefp.edit();
                    editorp.putString("policy", "");
                    editorp.commit();

                    SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);
                    Editor editor = mainPref.edit();
                    String arrToPut = innerArr.getJSONObject(0).getJSONArray("data").toString();

                    editor.putString("policy", arrToPut);
                    editor.commit();
                }

                String msgData = innerArr.getJSONObject(x).getString("data");
                JSONObject dataObj = new JSONObject("{}");
                operation = new Operation(context);
                if (featureCode.equalsIgnoreCase(CommonUtilities.OPERATION_POLICY_REVOKE)) {
                    operation.operate(featureCode, jsReply);
                    jsReply.put("status", msgId);
                } else {
                    if (msgData.charAt(0) == '[') {
                        JSONArray dataArr = new JSONArray(msgData);
                        for (int a = 0; a < dataArr.length(); a++) {
                            JSONObject innterDataObj = dataArr.getJSONObject(a);
                            featureCode = innterDataObj.getString("code");
                            String dataTemp = innterDataObj.getString("data");
                            if (!dataTemp.isEmpty() && dataTemp != null && !dataTemp.equalsIgnoreCase("null"))
                                dataObj = innterDataObj.getJSONObject("data");

                            dataReply = operation.operate(featureCode, dataObj);
                            //dataReply.put(resultJson);
                        }
                    } else {
                        if (!msgData.isEmpty() && msgData != null && !msgData.equalsIgnoreCase("null"))
                            if (msgData.charAt(0) == '{') {
                                dataObj = new JSONObject(msgData);
                            }
                        dataReply = operation.operate(featureCode, dataObj);
                        //dataReply.put(resultJson);
                    }
                }

            }
            jsReply.put("data", dataReply);
            repArray.put(jsReply);
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (Operation.enterpriseWipe == false) {
            SharedPreferences mainPref = context.getSharedPreferences(
                    context.getResources().getString(R.string.shared_pref_package), Context.MODE_PRIVATE);
            String regId = mainPref.getString(context.getResources().getString(R.string.shared_pref_regId), "");
            PayloadParser ps = new PayloadParser();

            replyPayload = ps.generateReply(repArray, regId);
            if (CommonUtilities.DEBUG_MODE_ENABLED) {
                Log.e(TAG, "replyPlayload -" + replyPayload);
            }
            stillProcessing = false;
            getOperations(replyPayload);
        }

    }

}

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFiles() {
    URL urlO = null;//from   ww w .  j  a  v  a 2  s  .c o  m
    try {
        urlO = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject fileJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(fileJson.get("_id").toString());

                if (file == null) {
                    file = new File(fileJson, false);
                } else {
                    file.setName(fileJson.getString("name"));
                    file.setPath(fileJson.getString("path"));
                    file.setCreationDate(fileJson.getString("creationDate"));
                    file.setLastModification(fileJson.getString("lastModification"));
                    file.setTags(fileJson.getString("tags"));

                    if (fileJson.has("binary")) {
                        file.setBinary(fileJson.getJSONObject("binary").toString());
                    }

                    file.setIsFile(true);
                    file.setFileClass(fileJson.getString("class"));
                    file.setMimeType(fileJson.getString("mime"));
                    file.setSize(fileJson.getLong("size"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing file : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName()));

                file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory()
                        + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files"
                        + file.getPath() + "/" + file.getName()));
                file.save();

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault()
                    .post(new FileSyncEvent(SERVICE_ERROR, new JSONObject(result).getString("error")));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}

From source file:at.alladin.rmbt.android.util.CheckSettingsTask.java

/**
* 
*//*from   ww w. j  a  v a 2s  .c  o m*/
@Override
protected void onPostExecute(final JSONArray resultList) {
    try {
        if (serverConn.hasError())
            hasError = true;
        else if (resultList != null && resultList.length() > 0) {

            JSONObject resultListItem;

            try {
                resultListItem = resultList.getJSONObject(0);

                /* UUID */

                final String uuid = resultListItem.optString("uuid", "");
                if (uuid != null && uuid.length() != 0)
                    ConfigHelper.setUUID(activity.getApplicationContext(), uuid);

                /* urls */

                final ConcurrentMap<String, String> volatileSettings = ConfigHelper.getVolatileSettings();

                final JSONObject urls = resultListItem.optJSONObject("urls");
                if (urls != null) {
                    final Iterator<String> keys = urls.keys();

                    while (keys.hasNext()) {
                        final String key = keys.next();
                        final String value = urls.optString(key, null);
                        if (value != null) {
                            volatileSettings.put("url_" + key, value);
                            if ("statistics".equals(key)) {
                                ConfigHelper.setCachedStatisticsUrl(value, activity);
                            } else if ("control_ipv4_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv4(value, activity);
                            } else if ("control_ipv6_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv6(value, activity);
                            } else if ("url_ipv4_check".equals(key)) {
                                ConfigHelper.setCachedIpv4CheckUrl(value, activity);
                            } else if ("url_ipv6_check".equals(key)) {
                                ConfigHelper.setCachedIpv6CheckUrl(value, activity);
                            }
                        }
                    }
                }

                /* qos names */
                final JSONArray qosNames = resultListItem.optJSONArray("qostesttype_desc");
                if (qosNames != null) {
                    final Map<String, String> qosNamesMap = new HashMap<String, String>();
                    for (int i = 0; i < qosNames.length(); i++) {
                        JSONObject json = qosNames.getJSONObject(i);
                        qosNamesMap.put(json.optString("test_type"), json.optString("name"));
                    }
                    ConfigHelper.setCachedQoSNames(qosNamesMap, activity);
                }

                /* map server */

                final JSONObject mapServer = resultListItem.optJSONObject("map_server");
                if (mapServer != null) {
                    final String host = mapServer.optString("host");
                    final int port = mapServer.optInt("port");
                    final boolean ssl = mapServer.optBoolean("ssl");
                    if (host != null && port > 0)
                        ConfigHelper.setMapServer(host, port, ssl);
                }

                /* control server version */
                final JSONObject versions = resultListItem.optJSONObject("versions");
                if (versions != null) {
                    if (versions.has("control_server_version")) {
                        ConfigHelper.setControlServerVersion(activity,
                                versions.optString("control_server_version"));
                    }
                }

                // ///////////////////////////////////////////////////////
                // HISTORY / FILTER

                final JSONObject historyObject = resultListItem.getJSONObject("history");

                final JSONArray deviceArray = historyObject.getJSONArray("devices");
                final JSONArray networkArray = historyObject.getJSONArray("networks");

                final String historyDevices[] = new String[deviceArray.length()];

                for (int i = 0; i < deviceArray.length(); i++)
                    historyDevices[i] = deviceArray.getString(i);

                final String historyNetworks[] = new String[networkArray.length()];

                for (int i = 0; i < networkArray.length(); i++)
                    historyNetworks[i] = networkArray.getString(i);

                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                activity.setSettings(historyDevices, historyNetworks);

                activity.setHistoryDirty(true);

            } catch (final JSONException e) {
                e.printStackTrace();
            }

        } else
            Log.i(DEBUG_TAG, "LEERE LISTE");
    } finally {
        if (endTaskListener != null)
            endTaskListener.taskEnded(resultList);
    }
}

From source file:org.stockchart.series.StockSeries.java

@Override
public void fromJSONObject(JSONObject j) throws JSONException {
    super.fromJSONObject(j);

    fFallAppearance.fromJSONObject(j.getJSONObject("fallAppearance"));
}

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

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

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

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

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

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

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

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

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

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

    return jdataInternalUrl;
}

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

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

From source file:com.altamiracorp.lumify.twitter.DefaultLumifyTwitterProcessor.java

@Override
public void extractEntities(final String processId, final JSONObject jsonTweet, final Vertex tweetVertex,
        final TwitterEntityType entityType) {
    // TODO set visibility
    Visibility visibility = new Visibility("");
    String tweetText = JSON_TEXT_PROPERTY.getFrom(jsonTweet);
    // only process if text is found in the tweet
    if (tweetText != null && !tweetText.trim().isEmpty()) {
        String tweetId = tweetVertex.getId().toString();
        User user = getUser();//from  ww w. j a  va  2s .c  om
        Graph graph = getGraph();
        OntologyRepository ontRepo = getOntologyRepository();
        AuditRepository auditRepo = getAuditRepository();

        Concept concept = ontRepo.getConceptByName(entityType.getConceptName());
        Vertex conceptVertex = concept.getVertex();
        String relDispName = conceptVertex.getPropertyValue(LumifyProperties.DISPLAY_NAME.getKey(), 0)
                .toString();

        JSONArray entities = jsonTweet.getJSONObject("entities").getJSONArray(entityType.getJsonKey());
        List<TermMentionModel> mentions = new ArrayList<TermMentionModel>();

        for (int i = 0; i < entities.length(); i++) {
            JSONObject entity = entities.getJSONObject(i);
            String id;
            String sign = entity.getString(entityType.getSignKey());
            if (entityType.getConceptName().equals(CONCEPT_TWITTER_MENTION)) {
                id = TWITTER_USER_PREFIX + entity.get("id");
            } else if (entityType.getConceptName().equals(CONCEPT_TWITTER_HASHTAG)) {
                sign = sign.toLowerCase();
                id = TWITTER_HASHTAG_PREFIX + sign;
            } else {
                try {
                    id = URLEncoder.encode(TWITTER_URL_PREFIX + sign, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("URL id could not be UTF-8 encoded");
                }
            }
            checkNotNull(sign, "Term sign cannot be null");
            JSONArray indices = entity.getJSONArray("indices");
            TermMentionRowKey termMentionRowKey = new TermMentionRowKey(tweetId, indices.getLong(0),
                    indices.getLong(1));
            TermMentionModel termMention = new TermMentionModel(termMentionRowKey);
            termMention.getMetadata().setSign(sign)
                    .setOntologyClassUri(
                            (String) conceptVertex.getPropertyValue(LumifyProperties.DISPLAY_NAME.getKey(), 0))
                    .setConceptGraphVertexId(concept.getId()).setVertexId(id);
            mentions.add(termMention);
        }

        for (TermMentionModel mention : mentions) {
            String sign = mention.getMetadata().getSign().toLowerCase();
            String rowKey = mention.getRowKey().toString();
            String id = mention.getMetadata().getGraphVertexId();

            ElementMutation<Vertex> termVertexMutation;
            Vertex termVertex = graph.getVertex(id, user.getAuthorizations());
            if (termVertex == null) {
                termVertexMutation = graph.prepareVertex(id, visibility, user.getAuthorizations());
            } else {
                termVertexMutation = termVertex.prepareMutation();
            }

            TITLE.setProperty(termVertexMutation, sign, visibility);
            ROW_KEY.setProperty(termVertexMutation, rowKey, visibility);
            CONCEPT_TYPE.setProperty(termVertexMutation, concept.getId(), visibility);

            if (!(termVertexMutation instanceof ExistingElementMutation)) {
                termVertex = termVertexMutation.save();
                getAuditRepository().auditVertexElementMutation(termVertexMutation, termVertex, processId, user,
                        visibility);
            } else {
                getAuditRepository().auditVertexElementMutation(termVertexMutation, termVertex, processId, user,
                        visibility);
                termVertex = termVertexMutation.save();
            }

            String termId = termVertex.getId().toString();

            mention.getMetadata().setVertexId(termId);
            getTermMentionRepository().save(mention);

            graph.addEdge(tweetVertex, termVertex, entityType.getRelationshipLabel(), visibility,
                    user.getAuthorizations());

            auditRepo.auditRelationship(AuditAction.CREATE, tweetVertex, termVertex, relDispName, processId, "",
                    user, visibility);
            graph.flush();
        }
    }
}