Example usage for org.json.simple JSONObject containsKey

List of usage examples for org.json.simple JSONObject containsKey

Introduction

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

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:org.wso2.carbon.apimgt.impl.utils.APIUtil.java

public static boolean isProductionEndpointsExists(API api) {
    JSONParser parser = new JSONParser();
    JSONObject config = null;
    try {//from   ww  w  . ja  v  a  2  s . c o  m
        config = (JSONObject) parser.parse(api.getEndpointConfig());

        if (config.containsKey("production_endpoints")) {
            return true;
        }
    } catch (ParseException e) {
        log.error(APIConstants.MSG_JSON_PARSE_ERROR, e);
    } catch (ClassCastException e) {
        log.error(APIConstants.MSG_JSON_PARSE_ERROR, e);
    }
    return false;
}

From source file:org.wso2.carbon.apimgt.migration.client.MigrateFrom110to200.java

/**
 * This method generates swagger v2 doc using swagger 1.2 doc
 *
 * @param tenant            Tenant/*from  w w  w  . j  a v a2 s  .  c o  m*/
 * @param swagger12location the location of swagger 1.2 doc
 * @return JSON string of swagger v2 doc
 * @throws java.net.MalformedURLException
 * @throws org.json.simple.parser.ParseException
 * @throws org.wso2.carbon.registry.core.exceptions.RegistryException
 */

private String getSwagger2docUsingSwagger12RegistryResources(Tenant tenant, String swagger12location, API api)
        throws MalformedURLException, ParseException, RegistryException, UserStoreException {
    log.debug("Calling getSwagger2docUsingSwagger12RegistryResources");
    JSONParser parser = new JSONParser();

    Object rawResource = registryService.getGovernanceRegistryResource(swagger12location);
    if (rawResource == null) {
        return "";
    }
    String swaggerRes = ResourceUtil.getResourceContent(rawResource);
    JSONObject swagger12doc = (JSONObject) parser.parse(swaggerRes);
    Object existSecDef = swagger12doc.get(Constants.SECURITY_DEFINITION__KEY);
    if (existSecDef == null) {
        JSONObject existScopes = new JSONObject();
        JSONObject xWso2Security = (JSONObject) swagger12doc.get(Constants.SWAGGER_X_WSO2_SECURITY);
        if (xWso2Security == null) {
            log.info("Security definition 'x-wso2-security' exist in API " + swagger12location
                    + " using default Security definitions");
        } else {
            JSONArray scopes = (JSONArray) ((JSONObject) xWso2Security.get(Constants.SWAGGER_OBJECT_NAME_APIM))
                    .get(Constants.SWAGGER_X_WSO2_SCOPES);
            for (int i = 0; i < scopes.size(); i++) {
                JSONObject scope = (JSONObject) scopes.get(i);
                existScopes.put(scope.get(Constants.SECURITY_DEFINITION_SCOPE_NAME),
                        scope.get(Constants.SECURITY_DEFINITION_SCOPE_KEY));
            }
        }
        JSONObject sec = generateSecurityDefinitionsObject(api.getId().getApiName(), existScopes);
        swagger12doc.put(Constants.SECURITY_DEFINITION__KEY, sec);
    } else {
        log.info("Security definition already exist in API " + swagger12location);
    }
    JSONObject paths = (JSONObject) swagger12doc.get(Constants.SWAGGER_PATHS);
    Set<Map.Entry> res = paths.entrySet();
    for (Map.Entry e : res) {
        JSONObject methods = (JSONObject) e.getValue();
        Set<Map.Entry> mes = methods.entrySet();
        for (Map.Entry m : mes) {
            if (!(m.getValue() instanceof JSONObject)) {
                log.warn("path is expected to be json but string found on " + swagger12location);
                continue;
            }
            JSONObject re = (JSONObject) m.getValue();
            JSONObject xWso2Security = (JSONObject) swagger12doc.get(Constants.SWAGGER_X_WSO2_SECURITY);
            JSONArray scopes = new JSONArray();
            if (xWso2Security != null) {
                scopes = (JSONArray) ((JSONObject) xWso2Security.get(Constants.SWAGGER_OBJECT_NAME_APIM))
                        .get(Constants.SWAGGER_X_WSO2_SCOPES);
            }
            JSONArray scopeList = new JSONArray();
            for (int i = 0; i < scopes.size(); i++) {
                JSONObject scope = (JSONObject) scopes.get(i);
                scopeList.add(scope.get(Constants.SECURITY_DEFINITION_SCOPE_NAME));
            }
            JSONArray authScopeArray = new JSONArray();
            JSONObject authScopeObj = new JSONObject();
            authScopeObj.put(api.getId().getApiName() + Constants.SECURITY_DEFINITION_NAME_KEY_SUFFIX,
                    scopeList);
            authScopeArray.add(authScopeObj);
            re.put(Constants.SWAGGER_PATH_SECURITY_KEY, authScopeArray);

            //setting produce type as array
            Object produceObj = re.get(Constants.SWAGGER_PRODUCES);
            if (produceObj != null && !(produceObj instanceof JSONArray)) {
                JSONArray prodArr = new JSONArray();
                prodArr.add((String) produceObj);
                re.put(Constants.SWAGGER_PRODUCES, prodArr);
            }

            //for resources response object
            JSONObject responses = (JSONObject) re.get(Constants.SWAGGER_RESPONSES);
            if (responses == null) {
                log.warn("responses attribute not present in swagger " + swagger12location);
                continue;
            }
            JSONObject response;
            Iterator itr = responses.keySet().iterator();
            while (itr.hasNext()) {
                String key = (String) itr.next();
                response = (JSONObject) responses.get(key);
                boolean isExist = response.containsKey(Constants.SWAGGER_DESCRIPTION);
                if (!isExist) {
                    response.put(Constants.SWAGGER_DESCRIPTION, "");
                }
            }
        }
    }
    return swagger12doc.toJSONString();
}

From source file:org.wso2.carbon.apimgt.migration.client.MigrateFrom18to19.java

/**
 * Generate Swagger v2.0 document using Swagger v1.2 resources
 *
 * @param swagger12doc      Old Swagger Document
 * @param apiDefPaths       Paths in API definition
 * @param swagger12BasePath Location of swagger v1.2 document
 * @return Swagger v2.0 document as a JSON object
 * @throws ParseException// w  ww . ja va 2s  .  c o  m
 * @throws MalformedURLException
 */

private static JSONObject generateSwagger2Document(JSONObject swagger12doc, Map<String, JSONArray> apiDefPaths,
        String swagger12BasePath, API api) throws ParseException, MalformedURLException {
    log.debug("Calling generateSwagger2Document");

    //create swagger 2.0 doc
    JSONObject swagger20doc = new JSONObject();

    //set swagger version
    swagger20doc.put(Constants.SWAGGER, Constants.SWAGGER_V2);

    //set the info object
    JSONObject info = generateInfoObject(swagger12doc);
    //update info object
    swagger20doc.put(Constants.SWAGGER_INFO, info);

    //set the paths object
    JSONObject pathObj = generatePathsObj(api);
    swagger20doc.put(Constants.SWAGGER_PATHS, pathObj);

    //securityDefinitions
    if (swagger12doc.containsKey(Constants.SWAGGER_AUTHORIZATIONS)) {
        JSONObject securityDefinitions = generateSecurityDefinitionsObject(api);
        swagger20doc.put(Constants.SWAGGER_SECURITY_DEFINITIONS, securityDefinitions);
    }
    return swagger20doc;
}

From source file:org.wso2.carbon.apimgt.migration.client.MigrateFrom18to19.java

/**
 * generate swagger v2 info object using swagger 1.2 doc.
 * See <a href="https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#infoObject">Swagger v2 info
 * object</a>/*from  ww w .  j a v  a  2 s .com*/
 *
 * @param swagger12doc Old Swagger Document
 * @return swagger v2 infoObject
 * @throws ParseException
 */
private static JSONObject generateInfoObject(JSONObject swagger12doc) throws ParseException {

    JSONObject infoObj = (JSONObject) swagger12doc.get("info");
    JSONParser parser = new JSONParser();
    JSONObject swagger2InfoObj = (JSONObject) parser.parse(Constants.DEFAULT_INFO);

    //set the required parameters first
    String title = (String) infoObj.get("title");
    String version = (String) swagger12doc.get("apiVersion");

    swagger2InfoObj.put(Constants.SWAGGER_TITLE, title);
    swagger2InfoObj.put(Constants.SWAGGER_VER, version);

    if (infoObj.containsKey(Constants.SWAGGER_DESCRIPTION)) {
        swagger2InfoObj.put(Constants.SWAGGER_DESCRIPTION, infoObj.get("description"));
    }
    if (infoObj.containsKey(Constants.SWAGGER_TERMS_OF_SERVICE_URL)) {
        swagger2InfoObj.put(Constants.SWAGGER_TERMS_OF_SERVICE,
                infoObj.get(Constants.SWAGGER_TERMS_OF_SERVICE_URL));
    }

    //contact object
    if (infoObj.containsKey(Constants.SWAGGER_CONTACT)) {
        JSONObject contactsObj = new JSONObject();
        String contact = (String) infoObj.get(Constants.SWAGGER_CONTACT);
        if (contact.contains("http")) {
            contactsObj.put(Constants.SWAGGER_URL, contact);
        } else if (contact.contains("@")) {
            contactsObj.put(Constants.SWAGGER_EMAIL, contact);
        } else {
            contactsObj.put(Constants.SWAGGER_NAME, contact);
        }
        swagger2InfoObj.put(Constants.SWAGGER_CONTACT, contactsObj);
    }

    //licence object
    JSONObject licenseObj = new JSONObject();
    if (infoObj.containsKey(Constants.SWAGGER_LICENCE)) {
        licenseObj.put(Constants.SWAGGER_NAME, infoObj.get(Constants.SWAGGER_LICENCE));
    }
    if (infoObj.containsKey(Constants.SWAGGER_LICENCE_URL)) {
        licenseObj.put(Constants.SWAGGER_URL, infoObj.get(Constants.SWAGGER_LICENCE_URL));
    }
    if (!licenseObj.isEmpty()) {
        swagger2InfoObj.put(Constants.SWAGGER_LICENCE, licenseObj);
    }
    return swagger2InfoObj;
}

From source file:org.wso2.carbon.apimgt.migration.Swagger19Migration.java

/**
 * Generate Swagger v2.0 document using Swagger v1.2 resources
 *
 * @param swagger12doc      Old Swagger Document
 * @param apiDefPaths       Paths in API definition
 * @param swagger12BasePath Location of swagger v1.2 document
 * @return Swagger v2.0 document as a JSON object
 * @throws ParseException/* w  ww .ja v a2  s.c  om*/
 * @throws MalformedURLException
 */

private static JSONObject generateSwagger2Document(JSONObject swagger12doc, Map<String, JSONArray> apiDefPaths,
        String swagger12BasePath) throws ParseException, MalformedURLException {
    //create swagger 2.0 doc
    JSONObject swagger20doc = new JSONObject();

    //set swagger version
    swagger20doc.put("swagger", "2.0");

    //set the info object
    JSONObject info = generateInfoObject(swagger12doc);
    //update info object
    swagger20doc.put("info", info);

    //set the paths object
    JSONObject pathObj = generatePathsObj(apiDefPaths);
    swagger20doc.put("paths", pathObj);

    URL url = new URL(swagger12BasePath);
    swagger20doc.put("host", url.getHost());
    swagger20doc.put("basePath", url.getPath());

    JSONArray schemes = new JSONArray();
    schemes.add(url.getProtocol());
    swagger20doc.put("schemes", schemes);

    //securityDefinitions
    if (swagger12doc.containsKey("authorizations")) {
        JSONObject securityDefinitions = generateSecurityDefinitionsObject(swagger12doc);
        swagger20doc.put("securityDefinitions", securityDefinitions);
    }

    return swagger20doc;
}

From source file:org.wso2.carbon.apimgt.migration.Swagger19Migration.java

/**
 * Generate swagger v2 security definition object
 * See <a href="https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#securityDefinitionsObject">Swagger v2 definition object</a>
 *
 * @param swagger12doc Old Swagger Document
 * @return security definition object/*  www . ja  v a2 s  .c  om*/
 * @throws ParseException
 */
private static JSONObject generateSecurityDefinitionsObject(JSONObject swagger12doc) throws ParseException {
    JSONParser parser = new JSONParser();
    JSONObject securityDefinitionObject = new JSONObject();
    JSONObject securitySchemeObject = (JSONObject) parser.parse(Constants.DEFAULT_SECURITY_SCHEME);

    JSONObject authorizations = (JSONObject) swagger12doc.get("authorizations");
    Set authTypes = authorizations.keySet();

    for (Object obj : authTypes) {
        JSONObject authObj = (JSONObject) authorizations.get(obj.toString());
        if (authObj.containsKey("scopes")) {
            //Put it to custom WSO2 scopes
            securitySchemeObject.put("x-wso2-scopes", authObj.get("scopes"));
        }
        securityDefinitionObject.put(obj.toString(), securitySchemeObject);
    }
    return securityDefinitionObject;
}

From source file:org.wso2.carbon.apimgt.migration.Swagger19Migration.java

/**
 * generate swagger v2 info object using swagger 1.2 doc.
 * See <a href="https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#infoObject">Swagger v2 info object</a>
 *
 * @param swagger12doc Old Swagger Document
 * @return swagger v2 infoObject//ww  w .  ja v a2s  . c o  m
 * @throws ParseException
 */
private static JSONObject generateInfoObject(JSONObject swagger12doc) throws ParseException {

    JSONObject infoObj = (JSONObject) swagger12doc.get("info");
    JSONParser parser = new JSONParser();
    JSONObject swagger2InfoObj = (JSONObject) parser.parse(Constants.DEFAULT_INFO);

    //set the required parameters first
    String title = (String) infoObj.get("title");
    String version = (String) swagger12doc.get("apiVersion");

    swagger2InfoObj.put("title", title);
    swagger2InfoObj.put("version", version);

    if (infoObj.containsKey("description")) {
        swagger2InfoObj.put("description", infoObj.get("description"));
    }
    if (infoObj.containsKey("termsOfServiceUrl")) {
        swagger2InfoObj.put("termsOfService", infoObj.get("termsOfServiceUrl"));
    }

    //contact object
    if (infoObj.containsKey("contact")) {
        JSONObject contactsObj = new JSONObject();
        String contact = (String) infoObj.get("contact");
        if (contact.contains("http")) {
            contactsObj.put("url", contact);
        } else if (contact.contains("@")) {
            contactsObj.put("email", contact);
        } else {
            contactsObj.put("name", contact);
        }
        swagger2InfoObj.put("contact", contactsObj);
    }

    //licence object
    JSONObject licenseObj = new JSONObject();
    if (infoObj.containsKey("license")) {
        licenseObj.put("name", infoObj.get("license"));
    }
    if (infoObj.containsKey("licenseUrl")) {
        licenseObj.put("url", infoObj.get("licenseUrl"));
    }
    if (!licenseObj.isEmpty()) {
        swagger2InfoObj.put("license", licenseObj);
    }
    return swagger2InfoObj;
}

From source file:org.wso2.carbon.apimgt.migration.Swagger19Migration.java

/**
 * Generate Swagger v2 paths object from swagger v1.2 document
 * See <a href="https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#paths-object">Swagger v2 paths object</a>
 *
 * @param apiDefinitionPaths API definition paths
 * @return swagger v2 paths object/*from   ww  w  . j  a v a  2  s . com*/
 * @throws ParseException
 */
private static JSONObject generatePathsObj(Map<String, JSONArray> apiDefinitionPaths) throws ParseException {
    JSONObject pathsObj = new JSONObject();
    JSONParser jsonParser = new JSONParser();

    for (Map.Entry<String, JSONArray> entry : apiDefinitionPaths.entrySet()) {
        String key = entry.getKey();
        JSONArray operations = entry.getValue();
        JSONObject pathItemObj = new JSONObject();
        for (Object operation : operations) {
            JSONObject operationObject = (JSONObject) operation;
            String method = (String) operationObject.get("method");
            JSONArray swagger2ParamObjects = (JSONArray) operationObject.get("parameters");
            JSONObject swagger2OperationsObj = new JSONObject();
            JSONArray newParameters = new JSONArray();
            for (Object swagger2ParamObj : swagger2ParamObjects) {
                JSONObject oldParam = (JSONObject) swagger2ParamObj;
                JSONObject paramObj = new JSONObject();
                paramObj.put("name", oldParam.get("name"));
                paramObj.put("in", oldParam.get("paramType"));
                paramObj.put("required", oldParam.get("required"));
                if (paramObj.containsKey("description")) {
                    paramObj.put("description", oldParam.get("description"));
                } else {
                    paramObj.put("description", "");
                }
                newParameters.add(paramObj);
            }

            //generate the Operation object (https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operationObject)
            swagger2OperationsObj.put("operationId", operationObject.get("nickname"));
            //setting operation level params
            swagger2OperationsObj.put("parameters", newParameters);
            if (operationObject.containsKey("notes")) {
                swagger2OperationsObj.put("description", operationObject.get("notes"));
            }
            if (operationObject.containsKey("summary")) {
                swagger2OperationsObj.put("summary", operationObject.get("summary"));
            }

            //set pathItem object for the resource(https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#pathItemObject)
            pathItemObj.put(method.toLowerCase(), swagger2OperationsObj);

            //set the responseObject (https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#responsesObject)
            JSONObject responseObject = null;
            if (operationObject.containsKey("responseMessages")) {
                responseObject = new JSONObject();
                JSONArray responseMessages = (JSONArray) operationObject.get("responseMessages");
                for (Object responseMessage : responseMessages) {
                    JSONObject errorObj = (JSONObject) responseMessage;
                    responseObject.put(errorObj.get("code"), errorObj.get("message"));
                }
            }
            if (responseObject == null) {
                //set a default response message since this is required field
                responseObject = (JSONObject) jsonParser.parse(Constants.DEFAULT_RESPONSE);
            }
            swagger2OperationsObj.put("responses", responseObject);
        }
        pathsObj.put(key, pathItemObj);
    }
    return pathsObj;
}

From source file:org.wso2.carbon.apimgt.migration.util.ResourceUtil.java

/**
 * Modify the resource in registry location '1.2' to be compatible with the
 * AM 1.8. add the// w w w .  j  ava2 s.  c  o m
 * parameters to operations element, add 'nickname' variable and the
 * 'basePath' variable
 * 
 * @param resource
 *            resource inside the 1.2 location
 * @param allParameters
 *            map containing all the parameters extracted from api-doc
 *            containing
 *            resources for swagger 1.1
 * @param allOperations 
 * @param basePath
 *            base path for the resource
 * @return modified resource for the api
 */
public static String getUpdatedSwagger12Resource(JSONObject resource, Map<String, JSONArray> allParameters,
        Map<String, JSONObject> allOperations, String basePath) {

    JSONArray apis = (JSONArray) resource.get(Constants.API_DOC_12_APIS);
    for (int i = 0; i < apis.size(); i++) {
        JSONObject apiInfo = (JSONObject) apis.get(i);
        String path = (String) apiInfo.get(Constants.API_DOC_12_PATH);
        JSONArray operations = (JSONArray) apiInfo.get(Constants.API_DOC_12_OPERATIONS);

        for (int j = 0; j < operations.size(); j++) {
            JSONObject operation = (JSONObject) operations.get(j);
            String method = (String) operation.get(Constants.API_DOC_12_METHOD);

            // nickname is method name + "_" + path without starting "/"
            // symbol
            String nickname = method.toLowerCase() + "_" + path.substring(1);
            // add nickname variable
            operation.put(Constants.API_DOC_12_NICKNAME, nickname);
            String key = path + "_" + method.toLowerCase();

            JSONArray parameters = new JSONArray();
            if (allParameters.containsKey(key)) {
                parameters = allParameters.get(key);

                //setting the 'type' to 'string' if this variable is missing
                for (int m = 0; m < parameters.size(); m++) {
                    JSONObject para = (JSONObject) parameters.get(m);
                    if (!para.containsKey("type")) {
                        para.put("type", "string");
                    }
                }

            } else {
                parameters = getDefaultParameters();

            }
            //if there are parameters already in this 
            JSONArray existingParams = (JSONArray) operation.get(Constants.API_DOC_12_PARAMETERS);
            if (existingParams.isEmpty()) {
                JSONParser parser = new JSONParser();
                if (path.contains("{")) {
                    List<String> urlParams = ResourceUtil.getURLTemplateParams(path);
                    for (String p : urlParams) {
                        try {
                            JSONObject paramObj = (JSONObject) parser
                                    .parse(Constants.DEFAULT_PARAM_FOR_URL_TEMPLATE);
                            paramObj.put("name", p);
                            parameters.add(paramObj);
                        } catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
                // add parameters array
                operation.put(Constants.API_DOC_12_PARAMETERS, parameters);
            } else {
                for (int k = 0; k < existingParams.size(); k++) {
                    parameters.add(existingParams.get(k));
                }
                operation.put(Constants.API_DOC_12_PARAMETERS, parameters);
            }

            //updating the resource description and nickname using values in the swagger 1.1 doc
            if (allOperations.containsKey(key)) {

                //update info related to object
                JSONObject operationObj11 = allOperations.get(key);
                //add summery
                if (operationObj11.containsKey("summary")) {
                    operation.put("summary", operationObj11.get("summery"));
                }

            }
        }
    }

    // add basePath variable
    resource.put(Constants.API_DOC_12_BASE_PATH, basePath);

    return resource.toJSONString();
}

From source file:org.wso2.carbon.apimgt.rest.api.publisher.v1.utils.mappings.APIMappingUtil.java

/**
 * This method converts endpointconfig json to corresponding APIEndpointDTO object
 *
 * @param type           production_endpoints, sandbox_endpoints
 * @param endpointConfig endpoint config
 * @param endpointProtocolType endpoint protocol type; eg: http
 * @return APIEndpointDTO apiEndpointDTO
 *//*  w  ww  .  ja  va  2  s  . c  o  m*/
public static APIEndpointDTO convertToAPIEndpointDTO(String type, JSONObject endpointConfig,
        String endpointProtocolType) {

    APIEndpointDTO apiEndpointDTO = new APIEndpointDTO();
    apiEndpointDTO.setType(type);
    if (endpointConfig.containsKey(APIConstants.API_DATA_URL)) {
        String url = endpointConfig.get(APIConstants.API_DATA_URL).toString();
        EndpointDTO endpointDTO = new EndpointDTO();
        EndpointEndpointConfigDTO endpointEndpointConfigDTO = new EndpointEndpointConfigDTO();
        List<EndpointConfigDTO> list = new ArrayList<>();
        EndpointConfigDTO endpointConfigDTO = new EndpointConfigDTO();
        endpointConfigDTO.setUrl(url);
        if (endpointConfig.containsKey(APIConstants.API_ENDPOINT_CONFIG_TIMEOUT)) {
            endpointConfigDTO
                    .setTimeout(endpointConfig.get(APIConstants.API_ENDPOINT_CONFIG_TIMEOUT).toString());
        }
        list.add(endpointConfigDTO);
        endpointEndpointConfigDTO.setList(list);

        //todo: fix for other types of endpoints eg: load balanced, failover 
        endpointEndpointConfigDTO.setEndpointType(EndpointEndpointConfigDTO.EndpointTypeEnum.SINGLE);

        endpointDTO.setEndpointConfig(endpointEndpointConfigDTO);
        endpointDTO.setType(endpointProtocolType);
        apiEndpointDTO.setInline(endpointDTO);
    }
    return apiEndpointDTO;
}