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.loklak.android.client.SearchClient.java

public static Timeline search(final String protocolhostportstub, final String query, final Timeline.Order order,
        final String source, final int count, final int timezoneOffset, final long timeout) throws IOException {
    Timeline tl = new Timeline(order);
    String urlstring = "";
    try {//w w w. j a v a  2 s .c o  m
        urlstring = protocolhostportstub + "/api/search.json?q="
                + URLEncoder.encode(query.replace(' ', '+'), "UTF-8") + "&timezoneOffset=" + timezoneOffset
                + "&maximumRecords=" + count + "&source=" + (source == null ? "all" : source)
                + "&minified=true&timeout=" + timeout;
        JSONObject json = JsonIO.loadJson(urlstring);
        if (json == null || json.length() == 0)
            return tl;
        JSONArray statuses = json.getJSONArray("statuses");
        if (statuses != null) {
            for (int i = 0; i < statuses.length(); i++) {
                JSONObject tweet = statuses.getJSONObject(i);
                JSONObject user = tweet.getJSONObject("user");
                if (user == null)
                    continue;
                tweet.remove("user");
                UserEntry u = new UserEntry(user);
                MessageEntry t = new MessageEntry(tweet);
                tl.add(t, u);
            }
        }
        if (json.has("search_metadata")) {
            JSONObject metadata = json.getJSONObject("search_metadata");
            if (metadata.has("hits")) {
                tl.setHits((Integer) metadata.get("hits"));
            }
            if (metadata.has("scraperInfo")) {
                String scraperInfo = (String) metadata.get("scraperInfo");
                tl.setScraperInfo(scraperInfo);
            }
        }
    } catch (Throwable e) {
        Log.e("SeachClient", e.getMessage(), e);
    }
    //System.out.println(parser.text());
    return tl;
}

From source file:org.wso2.carbon.dataservices.core.description.query.MongoQuery.java

private String getElementValueFromJson(String jsonString, JSONObject object, String jsonPath)
        throws JSONException {
    String value = null;/*from  ww w . j av  a 2s. c  o m*/
    JSONObject tempObject = object;
    JSONArray tempArray;
    String[] tokens = jsonPath.split("\\.");
    if (tokens[0].equals(DBConstants.MongoDB.RESULT_COLUMN_NAME.toLowerCase())) {
        if (tokens.length == 1) {
            value = jsonString;
        } else {
            for (int i = 1; i < tokens.length; i++) {
                if (i == tokens.length - 1) {
                    if (tokens[i].contains("[")) {
                        Object[] arrayObjects = getArrayElementKeys(tokens[i]);
                        tempArray = tempObject.getJSONArray(arrayObjects[0].toString());
                        value = tempArray.getString((Integer) arrayObjects[1]);
                    } else {
                        value = tempObject.getString(tokens[i]);
                    }
                } else {
                    if (tokens[i].contains("[")) {
                        Object[] arrayObjects = getArrayElementKeys(tokens[i]);
                        tempArray = tempObject.getJSONArray(arrayObjects[0].toString());
                        tempObject = tempArray.getJSONObject((Integer) arrayObjects[1]);
                    } else {
                        tempObject = tempObject.getJSONObject(tokens[i]);
                    }
                }
            }
        }
        return value;
    } else {
        return null;
    }
}

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

@Test
public void testIndexModifiedByOrion() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());

    String projectName = getMethodName();
    JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString());

    JSONObject testTxt = getChild(project, "test.txt");
    modifyFile(testTxt, "hello");

    JSONObject gitSection = testTxt.getJSONObject(GitConstants.KEY_GIT);
    String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);

    WebRequest request = getGetGitIndexRequest(gitIndexUri);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals("test", response.getText());
}

From source file:com.webwoz.wizard.server.components.MToutGoogle.java

/**
 * Submits text to Google AJAX Language API for translation.
 * //  ww  w  .j a  v  a 2  s . c  om
 * @param sourceText
 * @param sourceLanguage
 * @param targetLanguage
 * @param sourceTextFormat
 *            The format of the source Text (either "text" or "html", as
 *            specified by Google Language AJAX API).
 * @param apiKey
 *            API Key, obtained after registering with Google.
 * @param userIP
 *            IP address of end user (i.e. currently temporarily set to my
 *            IP or IP address of the PMIR framework's server machine)
 * @param referer
 *            URL of the referrer (e.g. URL of the PMIR framework's main
 *            page).
 * @return An object of <code>TransaltedText</code> object.
 * @throws MalformedLanguageAcronymException
 *             if the length of a language acronym (source or target) does
 *             not match the standard acronym length used throughout the
 *             framework.
 * @throws UnsupportedLanguageException
 *             if a language (source or target) is not supported in the
 *             framework.
 */
public String translate(String inputText, String srcLang, String trgLang) {

    // initialize connection
    // adapt proxy and settings to fit your server environment
    initializeConnection("www-proxy.cs.tcd.ie", 8080);
    String translation = null;
    String query = inputText;
    String sourceTextFormat = "html";
    String userIP = "134.226.35.174";
    String referer = "http://kdeg-vm14.cs.tcd.ie";
    String GOOGLE_TRANSLATION_BASE_URL = "https://ajax.googleapis.com/ajax/services/language/translate?v=1.0";

    try {
        // encode text
        query = URLEncoder.encode(query, "UTF-8");
        // exchange + for space
        query = query.replace("+", "%20");
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }

    String requestURL = GOOGLE_TRANSLATION_BASE_URL + "&q=" + query + "&langpair=" + srcLang + "%7C" + trgLang + // %7C
            "&format=" + sourceTextFormat + "&userip=" + userIP;

    HttpGet getRequest = new HttpGet(requestURL);

    getRequest.addHeader("Referer", referer);

    try {
        HttpResponse response = httpClient.execute(getRequest);
        HttpEntity responseEntity = response.getEntity();

        StringBuilder jsonStringBuilder = new StringBuilder();

        if (responseEntity != null) {
            InputStream inputStream = responseEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;
            while ((line = reader.readLine()) != null) {
                jsonStringBuilder.append(line);
            }

            inputStream.close();
            reader.close();
        }

        String jsonString = jsonStringBuilder.toString();
        JSONObject wholeJSONObject = new JSONObject(jsonString);

        JSONObject responseDataObject = wholeJSONObject.getJSONObject("responseData");

        translation = responseDataObject.getString("translatedText");

    } catch (Exception ex) {
        ex.printStackTrace();
        translation = ex.toString();
    }

    shutDownConnection();
    return translation;
}

From source file:edu.txstate.dmlab.clusteringwiki.rest.TestController.java

/**
 * Save the details of the last executed step
 * @param executionId the execution id for the current test
 * @param model// ww  w.  ja v a  2s . c  om
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
@RequestMapping("/test/put/{executionId}")
public void saveStep(@PathVariable("executionId") String execId, HttpServletRequest request,
        HttpServletResponse response, Model model) throws Exception {

    String executionId = _cleanExtensions(execId);

    if (!isValidTest(request, executionId)) {
        sendOutput(response, "{\"error\":\"Invalid test execution id.\"}");
        return;
    }

    try {

        String data = null;
        InputStream is = request.getInputStream();

        if (is != null) {
            try {
                StringBuilder sb = new StringBuilder();
                String line;
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                data = sb.toString();
            } finally {
                is.close();
            }

        }

        if (data == null) {
            sendOutput(response, "{\"error\":\"No data received.\"}");
            return;
        }

        final JSONObject info = new JSONObject(data);

        final Integer stepId = info.getInt("stepId");
        final String cluster = info.getJSONObject("cluster").toString();
        final String times = info.getJSONObject("times").toString();
        final JSONObject tagExecutionInfo = info.getJSONObject("tagExecutionInfo");

        int itemCount = 0;
        final Iterator keys = tagExecutionInfo.keys();
        while (keys.hasNext()) {
            final String cnt = (String) keys.next();
            final Integer tagCount = Integer.valueOf(cnt);
            TestStepExecution exec = this.testStepExecutionDao.selectTestStepExecution(executionId, stepId,
                    tagCount);

            if (exec != null) {
                sendOutput(response,
                        "{\"error\":\"This step has already been saved. Please contact an administrator.\"}");
                return;
            }

            final JSONObject itemInfo = tagExecutionInfo.getJSONObject(cnt);

            exec = new TestStepExecution();
            exec.setExecutionId(executionId);
            exec.setTagCount(tagCount);
            exec.setBaseEffort(itemInfo.getDouble("baseEffort"));
            exec.setBaseRelevantEffort(itemInfo.getDouble("baseRelevantEffort"));
            exec.setUserEffort(itemInfo.getDouble("userEffort"));
            exec.setCluster(cluster);
            exec.setTimes(times);
            exec.setStepId(stepId);
            exec.setTags(itemInfo.getJSONObject("tags").toString());

            if (this.isLoggedIn()) {
                exec.setUid(applicationUser.getUserId());
            }

            this.testStepExecutionDao.saveTestStepExecution(exec);
            itemCount++;
        }

        //if no tagged items
        if (itemCount == 0) {
            TestStepExecution exec = this.testStepExecutionDao.selectTestStepExecution(executionId, stepId, 0);

            if (exec != null) {
                sendOutput(response,
                        "{\"error\":\"This step has already been saved. Please contact an administrator.\"}");
                return;
            }

            exec = new TestStepExecution();
            exec.setExecutionId(executionId);
            exec.setTagCount(0);
            exec.setBaseEffort(0.0D);
            exec.setBaseRelevantEffort(0.0D);
            exec.setUserEffort(0.0D);
            exec.setCluster(cluster);
            exec.setTimes(times);
            exec.setStepId(stepId);
            exec.setTags("{}");

            if (this.isLoggedIn()) {
                exec.setUid(applicationUser.getUserId());
            }

            this.testStepExecutionDao.saveTestStepExecution(exec);
        }

        sendOutput(response, "{\"success\":true}");

    } catch (Exception e) {
        sendOutput(response, "{\"error\":" + JSONObject.quote(e.getMessage()) + "}");
        return;
    }

}

From source file:com.astifter.circatext.YahooJSONParser.java

private static JSONObject getObject(String tagName, JSONObject jObj) throws JSONException {
    return jObj.getJSONObject(tagName);
}

From source file:com.vk.sdk.api.VKRequest.java

public VKAbstractOperation getOperation() {
    if (this.parseModel) {
        if (this.mModelClass != null) {
            mLoadingOperation = new VKModelOperation(getPreparedRequest(), this.mModelClass);
        } else if (this.mModelParser != null) {
            mLoadingOperation = new VKModelOperation(getPreparedRequest(), this.mModelParser);
        }//from ww  w.ja v  a 2  s  .c  o m
    }
    if (mLoadingOperation == null)
        mLoadingOperation = new VKJsonOperation(getPreparedRequest());
    ((VKJsonOperation) mLoadingOperation).setJsonOperationListener(new VKJSONOperationCompleteListener() {
        @Override
        public void onComplete(VKJsonOperation operation, JSONObject response) {
            if (response.has("error")) {
                try {
                    VKError error = new VKError(response.getJSONObject("error"));
                    if (VKSdk.DEBUG && VKSdk.DEBUG_API_ERRORS) {
                        Log.w(VKSdk.SDK_TAG, operation.getResponseString());
                    }
                    if (processCommonError(error))
                        return;
                    provideError(error);
                } catch (JSONException e) {
                    if (VKSdk.DEBUG)
                        e.printStackTrace();
                }

                return;
            }
            provideResponse(response,
                    mLoadingOperation instanceof VKModelOperation
                            ? ((VKModelOperation) mLoadingOperation).parsedModel
                            : null);
        }

        @Override
        public void onError(VKJsonOperation operation, VKError error) {
            //??? ??? ???????? ????, ??? ????????? ??????????? ????? ??? ??????? ????????
            if (error.errorCode != VKError.VK_CANCELED && error.errorCode != VKError.VK_API_ERROR
                    && operation != null && operation.response != null
                    && operation.response.getStatusLine().getStatusCode() == 200) {
                provideResponse(operation.getResponseJson(), null);
                return;
            }
            if (VKSdk.DEBUG && VKSdk.DEBUG_API_ERRORS && operation != null
                    && operation.getResponseString() != null) {
                Log.w(VKSdk.SDK_TAG, operation.getResponseString());
            }
            if (attempts == 0 || ++mAttemptsUsed < attempts) {
                if (requestListener != null)
                    requestListener.attemptFailed(VKRequest.this, mAttemptsUsed, attempts);
                runOnLooper(new Runnable() {
                    @Override
                    public void run() {
                        start();
                    }
                }, 300);
                return;
            }
            provideError(error);
        }
    });
    return mLoadingOperation;
}

From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClientHandler.java

/**
 * Process authentication request/*from  ww  w.  j a v  a2  s.c  o m*/
 * @param channel netty channel
 * @param requestObj json request data object
 * @throws UserStoreException
 */
private void processAuthenticationRequest(Channel channel, JSONObject requestObj) throws UserStoreException {

    JSONObject requestData = requestObj.getJSONObject(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA);
    UserStoreManager userStoreManager = UserStoreManagerBuilder.getUserStoreManager();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Starting to authenticate user "
                + requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME));
    }

    boolean isAuthenticated = userStoreManager.doAuthenticate(
            requestData.getString(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME),
            requestData.getString(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_PASSWORD));
    String authenticationResult = UserAgentConstants.UM_OPERATION_AUTHENTICATE_RESULT_FAIL;

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Authentication completed. User: "
                + requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME) + " result: "
                + isAuthenticated);
    }
    if (isAuthenticated) {
        authenticationResult = UserAgentConstants.UM_OPERATION_AUTHENTICATE_RESULT_SUCCESS;
    }
    writeResponse(channel,
            (String) requestObj.get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID),
            authenticationResult);
}

From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClientHandler.java

/**
 * Process Get claims request//w  w w  .j  a va 2  s  . co  m
 * @param channel netty channel
 * @param requestObj json request data object
 * @throws UserStoreException
 */
private void processGetClaimsRequest(Channel channel, JSONObject requestObj) throws UserStoreException {

    JSONObject requestData = requestObj.getJSONObject(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Starting to get claims for user: "
                + requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME));
    }

    String username = (String) requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME);
    String claims = (String) requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_CLAIMS);
    String[] claimArray = claims.split(CommonConstants.ATTRIBUTE_LIST_SEPERATOR);
    UserStoreManager userStoreManager = UserStoreManagerBuilder.getUserStoreManager();

    Map<String, String> propertyMap = userStoreManager.getUserClaimValues(username, claimArray);
    JSONObject returnObject = new JSONObject(propertyMap);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Claims retrieval completed. User: "
                + requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME) + " claims: "
                + propertyMap.toString());
    }
    writeResponse(channel,
            (String) requestObj.get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID),
            returnObject.toString());
}

From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClientHandler.java

/**
 * Process get user roles request//from  w  w w  . ja  v  a 2  s.c o m
 * @param channel netty channel
 * @param requestObj json request data object
 * @throws UserStoreException
 */
private void processGetUserRolesRequest(Channel channel, JSONObject requestObj) throws UserStoreException {
    JSONObject requestData = requestObj.getJSONObject(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Starting to get user roles for user: "
                + requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME));
    }
    String username = (String) requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME);

    UserStoreManager userStoreManager = UserStoreManagerBuilder.getUserStoreManager();
    String[] roles = userStoreManager.doGetExternalRoleListOfUser(username);
    JSONObject jsonObject = new JSONObject();
    JSONArray usernameArray = new JSONArray(roles);
    jsonObject.put("groups", usernameArray);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("User roles retrieval completed. User: "
                + requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME) + " roles: "
                + Arrays.toString(roles));
    }
    writeResponse(channel,
            (String) requestObj.get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID),
            jsonObject.toString());
}