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:org.wso2.carbon.connector.integration.test.amazonsqs.AmazonSQSAuthConnector.java

/**
 * getSortedHeadersMap method used to return list of header values sorted by expected API parameter names.
 *
 * @param signatureRequestObject ESB messageContext.
 * @param namesMap contains a map of esb parameter names and matching API parameter names
 * @return assigned header values as a HashMap.
 * @throws JSONException /*from ww w.  ja v a2 s .  c o m*/
 */
private Map<String, String> getSortedHeadersMap(final JSONObject signatureRequestObject,
        final Map<String, String> namesMap) throws JSONException {

    final String[] headerKeys = getHeaderKeys();
    final Map<String, String> parametersMap = new TreeMap<String, String>();
    // Stores sorted, single valued API parameters
    for (byte index = 0; index < headerKeys.length; index++) {
        final String key = headerKeys[index];
        // builds the parameter map only if provided by the user
        if (signatureRequestObject.has(key) && !("").equals((String) signatureRequestObject.get(key))) {
            parametersMap.put(namesMap.get(key).toLowerCase(), signatureRequestObject.get(key).toString().trim()
                    .replaceAll(AmazonSQSConstants.TRIM_SPACE_REGEX, AmazonSQSConstants.SPACE));
        }
    }
    return parametersMap;
}

From source file:org.entando.entando.plugins.jptrello.aps.system.services.trello.TrelloConfig.java

public TrelloConfig(String xml) {
    if (StringUtils.isNotBlank(xml)) {
        JSONObject json = XML.toJSONObject(xml);
        json = json.getJSONObject(CONFIG_ROOT);

        if (json.has(CONFIG_ORGANIZATION)) {
            _organization = json.getString(CONFIG_ORGANIZATION);
        }//w  w  w  .  j  a  v  a2 s  . c o  m
        if (json.has(CONFIG_KEY)) {
            _apiKey = json.getString(CONFIG_KEY);
        }
        if (json.has(CONFIG_SECRET)) {
            _apiSecret = json.getString(CONFIG_SECRET);
        }
        if (json.has(CONFIG_TOKEN)) {
            _token = json.getString(CONFIG_TOKEN);
        }
    }
}

From source file:org.openmidaas.library.authentication.AuthCallbackForAccessToken.java

private void obtainAccessToken(SubjectToken subjectToken, String deviceToken) throws JSONException {
    AVSServer.getAuthToken(subjectToken, deviceToken, new AsyncHttpResponseHandler() {
        @Override/*www  .  ja  va  2  s .c  om*/
        public void onSuccess(String response) {
            if (response == null || response.isEmpty()) {
                MIDaaS.logError(TAG, "Server response is empty.");
                mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
            } else {
                try {
                    JSONObject accessToken = new JSONObject(response);
                    if ((accessToken.has(Constants.AccessTokenKeys.ACCESS_TOKEN)
                            && !(accessToken.isNull(Constants.AccessTokenKeys.ACCESS_TOKEN)))
                            && (accessToken.has(Constants.AccessTokenKeys.EXPIRES_IN)
                                    && !(accessToken.isNull(Constants.AccessTokenKeys.EXPIRES_IN)))) {
                        AccessToken token = AccessToken.createAccessToken(
                                accessToken.getString(Constants.AccessTokenKeys.ACCESS_TOKEN),
                                accessToken.getInt(Constants.AccessTokenKeys.EXPIRES_IN));
                        if (token != null) {
                            MIDaaS.logDebug(TAG, "got access token: ");
                            mCallback.onSuccess(token);
                        } else {
                            MIDaaS.logError(TAG, "Error could not create access token");
                            mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                        }
                    } else {
                        MIDaaS.logError(TAG, "Server response is not what is expected");
                        mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                    }

                } catch (JSONException e) {
                    MIDaaS.logError(TAG, "Internal error while parsing server JSON response");
                    mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                }

            }

        }

        @Override
        public void onFailure(Throwable e, String response) {
            MIDaaS.logError(TAG, "Server responded with error " + response);
            mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
        }
    });
}

From source file:com.cdd.bao.importer.KeywordMapping.java

public JSONObject createAssay(JSONObject keydata, Schema schema, Map<Schema.Assignment, SchemaTree> treeCache)
        throws JSONException, IOException {
    String uniqueID = null;//w  ww .j a va  2s  .c om
    List<String> linesTitle = new ArrayList<>(), linesBlock = new ArrayList<>();
    List<String> linesSkipped = new ArrayList<>(), linesProcessed = new ArrayList<>();
    Set<String> gotAnnot = new HashSet<>(), gotLiteral = new HashSet<>();
    JSONArray jsonAnnot = new JSONArray();
    final String SEP = "::";

    // assertions: these always supply a term
    for (Assertion asrt : assertions) {
        JSONObject obj = new JSONObject();
        obj.put("propURI", ModelSchema.expandPrefix(asrt.propURI));
        obj.put("groupNest", new JSONArray(expandPrefixes(asrt.groupNest)));
        obj.put("valueURI", ModelSchema.expandPrefix(asrt.valueURI));
        jsonAnnot.put(obj);

        String hash = asrt.propURI + SEP + asrt.valueURI + SEP
                + (asrt.groupNest == null ? "" : String.join(SEP, asrt.groupNest));
        gotAnnot.add(hash);
    }

    // go through the columns one at a time
    for (String key : keydata.keySet()) {
        String data = keydata.getString(key);

        Identifier id = findIdentifier(key);
        if (id != null) {
            if (uniqueID == null)
                uniqueID = id.prefix + data;
            continue;
        }

        TextBlock tblk = findTextBlock(key);
        if (tblk != null) {
            if (Util.isBlank(tblk.title))
                linesTitle.add(data);
            else
                linesBlock.add(tblk.title + ": " + data);
        }

        Value val = findValue(key, data);
        if (val != null) {
            if (Util.isBlank(val.valueURI)) {
                linesSkipped.add(key + ": " + data);
            } else {
                String hash = val.propURI + SEP + val.valueURI + SEP
                        + (val.groupNest == null ? "" : String.join(SEP, val.groupNest));
                if (gotAnnot.contains(hash))
                    continue;

                JSONObject obj = new JSONObject();
                obj.put("propURI", ModelSchema.expandPrefix(val.propURI));
                obj.put("groupNest", new JSONArray(expandPrefixes(val.groupNest)));
                obj.put("valueURI", ModelSchema.expandPrefix(val.valueURI));
                jsonAnnot.put(obj);
                gotAnnot.add(hash);
                linesProcessed.add(key + ": " + data);
            }
            continue;
        }

        Literal lit = findLiteral(key, data);
        if (lit != null) {
            String hash = lit.propURI + SEP + (lit.groupNest == null ? "" : String.join(SEP, lit.groupNest))
                    + SEP + data;
            if (gotLiteral.contains(hash))
                continue;

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(lit.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(lit.groupNest)));
            obj.put("valueLabel", data);
            jsonAnnot.put(obj);
            gotLiteral.add(hash);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        Reference ref = findReference(key, data);
        if (ref != null) {
            Pattern ptn = Pattern.compile(ref.valueRegex);
            Matcher m = ptn.matcher(data);
            if (!m.matches() || m.groupCount() < 1)
                throw new IOException(
                        "Pattern /" + ref.valueRegex + "/ did not match '" + data + "' to produce a group.");

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(ref.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(ref.groupNest)));
            obj.put("valueLabel", ref.prefix + m.group(1));
            jsonAnnot.put(obj);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        // probably shouldn't get this far, but just in case
        linesSkipped.add(key + ": " + data);
    }

    // annotation collapsing: sometimes there's a branch sequence that should exclude parent nodes
    for (int n = 0; n < jsonAnnot.length(); n++) {
        JSONObject obj = jsonAnnot.getJSONObject(n);
        String propURI = obj.getString("propURI"), valueURI = obj.optString("valueURI");
        if (valueURI == null)
            continue;
        String[] groupNest = obj.getJSONArray("groupNest").toStringArray();
        Schema.Assignment[] assnList = schema.findAssignmentByProperty(ModelSchema.expandPrefix(propURI),
                groupNest);
        if (assnList.length == 0)
            continue;
        SchemaTree tree = treeCache.get(assnList[0]);
        if (tree == null)
            continue;

        Set<String> exclusion = new HashSet<>();
        for (SchemaTree.Node node = tree.getNode(valueURI); node != null; node = node.parent)
            exclusion.add(node.uri);
        if (exclusion.size() == 0)
            continue;

        for (int i = jsonAnnot.length() - 1; i >= 0; i--)
            if (i != n) {
                obj = jsonAnnot.getJSONObject(i);
                if (!obj.has("valueURI"))
                    continue;
                if (!propURI.equals(obj.getString("propURI")))
                    continue;
                if (!Objects.deepEquals(groupNest, obj.getJSONArray("groupNest").toStringArray()))
                    continue;
                if (!exclusion.contains(obj.getString("valueURI")))
                    continue;
                jsonAnnot.remove(i);
            }
    }

    /*String text = "";
    if (linesBlock.size() > 0) text += String.join("\n", linesBlock) + "\n\n";
    if (linesSkipped.size() > 0) text += "SKIPPED:\n" + String.join("\n", linesSkipped) + "\n\n";
    text += "PROCESSED:\n" + String.join("\n", linesProcessed);*/

    List<String> sections = new ArrayList<>();
    if (linesTitle.size() > 0)
        sections.add(String.join(" / ", linesTitle));
    if (linesBlock.size() > 0)
        sections.add(String.join("\n", linesBlock));
    sections.add("#### IMPORTED ####");
    if (linesSkipped.size() > 0)
        sections.add("SKIPPED:\n" + String.join("\n", linesSkipped));
    if (linesProcessed.size() > 0)
        sections.add("PROCESSED:\n" + String.join("\n", linesProcessed));
    String text = String.join("\n\n", sections);

    JSONObject assay = new JSONObject();
    assay.put("uniqueID", uniqueID);
    assay.put("text", text);
    assay.put("schemaURI", schema.getSchemaPrefix());
    assay.put("annotations", jsonAnnot);
    return assay;
}

From source file:eu.codeplumbers.cosi.api.tasks.RegisterDeviceTask.java

@Override
protected Device doInBackground(Void... voids) {
    URL urlO = null;//w ww  .ja v  a  2 s .com
    try {
        urlO = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        OutputStream os = conn.getOutputStream();
        os.write(deviceString.getBytes("UTF-8"));
        os.flush();

        // 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();

        JSONObject jsonObject = new JSONObject(result);

        if (jsonObject != null) {
            if (jsonObject.has("login")) {
                resultDevice = new Device();
                resultDevice.setUrl(url.replace("/device/", ""));
                //Log.d(getClass().getName(), "Token="+jsonObject.getString("login"));
                resultDevice.setLogin(jsonObject.getString("login"));
                resultDevice.setPassword(jsonObject.getString("password"));
                resultDevice.setPermissions(jsonObject.getString("permissions"));

                resultDevice.setFirstSyncDone(false);
                resultDevice.setSyncCalls(false);
                resultDevice.setSyncContacts(false);
                resultDevice.setSyncFiles(false);
                resultDevice.setSyncNotes(false);

                resultDevice.save();
            } else {
                errorMessage = jsonObject.getString("error");
            }
        }

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

    } catch (MalformedURLException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (IOException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (JSONException e) {
        errorMessage = e.getLocalizedMessage();
    }

    return resultDevice;
}

From source file:org.wso2.carbon.connector.integration.test.meetup.members.MemberIntegrationTest.java

@Test(enabled = true, groups = { "wso2.esb" }, description = "meetup {getmember_byid} integration test")
public void testgetmember_byidMandatory() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "getmember_byid-mandatory.txt";
    String methodName = "meetup_getmember_byid";

    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    String modifiedJsonString = String.format(jsonString, meetupConnectorProperties.getProperty("key"),
            meetupConnectorProperties.getProperty("id")

    );// w ww  .  j  av  a2 s . co m
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {

        int responseHeader = ConnectorIntegrationUtil
                .sendRequestToRetriveHeaders(getProxyServiceURL(methodName), modifiedJsonString);
        Assert.assertTrue(responseHeader == 200);
        JSONObject jsonObject = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName),
                modifiedJsonString);
        Assert.assertTrue(jsonObject.has("lon"));
        System.out.println("--------------@@@@@@@@---------");

    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.meetup.members.MemberIntegrationTest.java

@Test(enabled = true, groups = {
        "wso2.esb" }, description = "meetup {fetchgroups}  integration test for negative scenario.")
public void testgetmember_byidNegative() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "getmember_byid_negative.txt";
    String methodName = "meetup_getmember_byid";

    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";

    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {//from   ww w.  j  a v a  2 s. c om

        int responseHeader = ConnectorIntegrationUtil
                .sendRequestToRetriveHeaders(getProxyServiceURL(methodName), jsonString);
        Assert.assertTrue(responseHeader == 400);

        JSONObject jsonObject = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName),
                jsonString);
        Assert.assertTrue(jsonObject.has("details"));

    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.meetup.members.MemberIntegrationTest.java

@Test(enabled = true, groups = { "wso2.esb" }, description = "meetup {getmembers} integration test")
public void testgetmembersMandatory() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "getmembers_mandatory.txt";
    String methodName = "meetup_getmembers";

    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    String modifiedJsonString = String.format(jsonString, meetupConnectorProperties.getProperty("key"),
            meetupConnectorProperties.getProperty("group_id"),
            meetupConnectorProperties.getProperty("group_urlname"),
            meetupConnectorProperties.getProperty("service"),
            meetupConnectorProperties.getProperty("member_id"), meetupConnectorProperties.getProperty("topic"),
            meetupConnectorProperties.getProperty("groupnum")

    );/*from w  ww. ja v  a  2s .c  o m*/
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {

        int responseHeader = ConnectorIntegrationUtil
                .sendRequestToRetriveHeaders(getProxyServiceURL(methodName), modifiedJsonString);
        Assert.assertTrue(responseHeader == 200);
        JSONObject jsonObject = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName),
                modifiedJsonString);
        Assert.assertTrue(jsonObject.has("results"));
        System.out.println("--------------@@@@@@@@---------");

    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.meetup.members.MemberIntegrationTest.java

@Test(enabled = false, groups = { "wso2.esb" }, description = "meetup {delete_member_photo} integration test")
public void testdelete_member_photoMandatory() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "delete_member_photo_mandatory.txt";
    String methodName = "meetup_delete_member_photo";

    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    String modifiedJsonString = String.format(jsonString, meetupConnectorProperties.getProperty("key"),

            meetupConnectorProperties.getProperty("id")

    );/*from  w  w  w. java  2 s  .  c om*/
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {

        int responseHeader = ConnectorIntegrationUtil
                .sendRequestToRetriveHeaders(getProxyServiceURL(methodName), modifiedJsonString);
        Assert.assertTrue(responseHeader == 401);
        JSONObject jsonObject = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName),
                modifiedJsonString);
        Assert.assertTrue(jsonObject.has("problem"));

    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:org.wso2.carbon.connector.integration.test.meetup.members.MemberIntegrationTest.java

@Test(enabled = false, groups = {
        "wso2.esb" }, description = "meetup {edit_member}  integration test for negative scenario.")
public void testedit_memberNegative() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "edit_member_negative.txt";
    String methodName = "meetup_edit_member";

    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";

    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {//from w  w w  . j a  va 2 s.  c om

        int responseHeader = ConnectorIntegrationUtil
                .sendRequestToRetriveHeaders(getProxyServiceURL(methodName), jsonString);
        Assert.assertTrue(responseHeader == 404);

        JSONObject jsonObject = ConnectorIntegrationUtil.sendRequest(getProxyServiceURL(methodName),
                jsonString);
        Assert.assertTrue(jsonObject.has("details"));

    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}